bpf: Inherit expanded/patched seen count from old aux data
[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{
10bf4e83 1401 return a > U32_MIN && a < U32_MAX;
3f50f132
JF
1402}
1403
1404static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1405{
1406 __mark_reg32_unbounded(reg);
1407
b0270958 1408 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1409 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1410 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1411 }
10bf4e83 1412 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 1413 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 1414 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 1415 }
3f50f132
JF
1416
1417 /* Intersecting with the old var_off might have improved our bounds
1418 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1419 * then new var_off is (0; 0x7f...fc) which improves our umax.
1420 */
1421 __reg_deduce_bounds(reg);
1422 __reg_bound_offset(reg);
1423 __update_reg_bounds(reg);
b03c9f9f
EC
1424}
1425
f1174f77 1426/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1427static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1428 struct bpf_reg_state *reg)
f1174f77 1429{
a9c676bc
AS
1430 /*
1431 * Clear type, id, off, and union(map_ptr, range) and
1432 * padding between 'type' and union
1433 */
1434 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1435 reg->type = SCALAR_VALUE;
f1174f77 1436 reg->var_off = tnum_unknown;
f4d7e40a 1437 reg->frameno = 0;
2c78ee89 1438 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1439 __mark_reg_unbounded(reg);
f1174f77
EC
1440}
1441
61bd5218
JK
1442static void mark_reg_unknown(struct bpf_verifier_env *env,
1443 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1444{
1445 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1446 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1447 /* Something bad happened, let's kill all regs except FP */
1448 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1449 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1450 return;
1451 }
f54c7898 1452 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1453}
1454
f54c7898
DB
1455static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1456 struct bpf_reg_state *reg)
f1174f77 1457{
f54c7898 1458 __mark_reg_unknown(env, reg);
f1174f77
EC
1459 reg->type = NOT_INIT;
1460}
1461
61bd5218
JK
1462static void mark_reg_not_init(struct bpf_verifier_env *env,
1463 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1464{
1465 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1466 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1467 /* Something bad happened, let's kill all regs except FP */
1468 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1469 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1470 return;
1471 }
f54c7898 1472 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1473}
1474
41c48f3a
AI
1475static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1476 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1477 enum bpf_reg_type reg_type,
1478 struct btf *btf, u32 btf_id)
41c48f3a
AI
1479{
1480 if (reg_type == SCALAR_VALUE) {
1481 mark_reg_unknown(env, regs, regno);
1482 return;
1483 }
1484 mark_reg_known_zero(env, regs, regno);
1485 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1486 regs[regno].btf = btf;
41c48f3a
AI
1487 regs[regno].btf_id = btf_id;
1488}
1489
5327ed3d 1490#define DEF_NOT_SUBREG (0)
61bd5218 1491static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1492 struct bpf_func_state *state)
17a52670 1493{
f4d7e40a 1494 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1495 int i;
1496
dc503a8a 1497 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1498 mark_reg_not_init(env, regs, i);
dc503a8a 1499 regs[i].live = REG_LIVE_NONE;
679c782d 1500 regs[i].parent = NULL;
5327ed3d 1501 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1502 }
17a52670
AS
1503
1504 /* frame pointer */
f1174f77 1505 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1506 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1507 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1508}
1509
f4d7e40a
AS
1510#define BPF_MAIN_FUNC (-1)
1511static void init_func_state(struct bpf_verifier_env *env,
1512 struct bpf_func_state *state,
1513 int callsite, int frameno, int subprogno)
1514{
1515 state->callsite = callsite;
1516 state->frameno = frameno;
1517 state->subprogno = subprogno;
1518 init_reg_state(env, state);
1519}
1520
17a52670
AS
1521enum reg_arg_type {
1522 SRC_OP, /* register is used as source operand */
1523 DST_OP, /* register is used as destination operand */
1524 DST_OP_NO_MARK /* same as above, check only, don't mark */
1525};
1526
cc8b0b92
AS
1527static int cmp_subprogs(const void *a, const void *b)
1528{
9c8105bd
JW
1529 return ((struct bpf_subprog_info *)a)->start -
1530 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1531}
1532
1533static int find_subprog(struct bpf_verifier_env *env, int off)
1534{
9c8105bd 1535 struct bpf_subprog_info *p;
cc8b0b92 1536
9c8105bd
JW
1537 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1538 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1539 if (!p)
1540 return -ENOENT;
9c8105bd 1541 return p - env->subprog_info;
cc8b0b92
AS
1542
1543}
1544
1545static int add_subprog(struct bpf_verifier_env *env, int off)
1546{
1547 int insn_cnt = env->prog->len;
1548 int ret;
1549
1550 if (off >= insn_cnt || off < 0) {
1551 verbose(env, "call to invalid destination\n");
1552 return -EINVAL;
1553 }
1554 ret = find_subprog(env, off);
1555 if (ret >= 0)
282a0f46 1556 return ret;
4cb3d99c 1557 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1558 verbose(env, "too many subprograms\n");
1559 return -E2BIG;
1560 }
e6ac2450 1561 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
1562 env->subprog_info[env->subprog_cnt++].start = off;
1563 sort(env->subprog_info, env->subprog_cnt,
1564 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1565 return env->subprog_cnt - 1;
cc8b0b92
AS
1566}
1567
e6ac2450
MKL
1568struct bpf_kfunc_desc {
1569 struct btf_func_model func_model;
1570 u32 func_id;
1571 s32 imm;
1572};
1573
1574#define MAX_KFUNC_DESCS 256
1575struct bpf_kfunc_desc_tab {
1576 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1577 u32 nr_descs;
1578};
1579
1580static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1581{
1582 const struct bpf_kfunc_desc *d0 = a;
1583 const struct bpf_kfunc_desc *d1 = b;
1584
1585 /* func_id is not greater than BTF_MAX_TYPE */
1586 return d0->func_id - d1->func_id;
1587}
1588
1589static const struct bpf_kfunc_desc *
1590find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1591{
1592 struct bpf_kfunc_desc desc = {
1593 .func_id = func_id,
1594 };
1595 struct bpf_kfunc_desc_tab *tab;
1596
1597 tab = prog->aux->kfunc_tab;
1598 return bsearch(&desc, tab->descs, tab->nr_descs,
1599 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1600}
1601
1602static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1603{
1604 const struct btf_type *func, *func_proto;
1605 struct bpf_kfunc_desc_tab *tab;
1606 struct bpf_prog_aux *prog_aux;
1607 struct bpf_kfunc_desc *desc;
1608 const char *func_name;
1609 unsigned long addr;
1610 int err;
1611
1612 prog_aux = env->prog->aux;
1613 tab = prog_aux->kfunc_tab;
1614 if (!tab) {
1615 if (!btf_vmlinux) {
1616 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1617 return -ENOTSUPP;
1618 }
1619
1620 if (!env->prog->jit_requested) {
1621 verbose(env, "JIT is required for calling kernel function\n");
1622 return -ENOTSUPP;
1623 }
1624
1625 if (!bpf_jit_supports_kfunc_call()) {
1626 verbose(env, "JIT does not support calling kernel function\n");
1627 return -ENOTSUPP;
1628 }
1629
1630 if (!env->prog->gpl_compatible) {
1631 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1632 return -EINVAL;
1633 }
1634
1635 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1636 if (!tab)
1637 return -ENOMEM;
1638 prog_aux->kfunc_tab = tab;
1639 }
1640
1641 if (find_kfunc_desc(env->prog, func_id))
1642 return 0;
1643
1644 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1645 verbose(env, "too many different kernel function calls\n");
1646 return -E2BIG;
1647 }
1648
1649 func = btf_type_by_id(btf_vmlinux, func_id);
1650 if (!func || !btf_type_is_func(func)) {
1651 verbose(env, "kernel btf_id %u is not a function\n",
1652 func_id);
1653 return -EINVAL;
1654 }
1655 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1656 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1657 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1658 func_id);
1659 return -EINVAL;
1660 }
1661
1662 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1663 addr = kallsyms_lookup_name(func_name);
1664 if (!addr) {
1665 verbose(env, "cannot find address for kernel function %s\n",
1666 func_name);
1667 return -EINVAL;
1668 }
1669
1670 desc = &tab->descs[tab->nr_descs++];
1671 desc->func_id = func_id;
1672 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1673 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1674 func_proto, func_name,
1675 &desc->func_model);
1676 if (!err)
1677 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1678 kfunc_desc_cmp_by_id, NULL);
1679 return err;
1680}
1681
1682static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1683{
1684 const struct bpf_kfunc_desc *d0 = a;
1685 const struct bpf_kfunc_desc *d1 = b;
1686
1687 if (d0->imm > d1->imm)
1688 return 1;
1689 else if (d0->imm < d1->imm)
1690 return -1;
1691 return 0;
1692}
1693
1694static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1695{
1696 struct bpf_kfunc_desc_tab *tab;
1697
1698 tab = prog->aux->kfunc_tab;
1699 if (!tab)
1700 return;
1701
1702 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1703 kfunc_desc_cmp_by_imm, NULL);
1704}
1705
1706bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1707{
1708 return !!prog->aux->kfunc_tab;
1709}
1710
1711const struct btf_func_model *
1712bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1713 const struct bpf_insn *insn)
1714{
1715 const struct bpf_kfunc_desc desc = {
1716 .imm = insn->imm,
1717 };
1718 const struct bpf_kfunc_desc *res;
1719 struct bpf_kfunc_desc_tab *tab;
1720
1721 tab = prog->aux->kfunc_tab;
1722 res = bsearch(&desc, tab->descs, tab->nr_descs,
1723 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1724
1725 return res ? &res->func_model : NULL;
1726}
1727
1728static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 1729{
9c8105bd 1730 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 1731 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 1732 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 1733
f910cefa
JW
1734 /* Add entry function. */
1735 ret = add_subprog(env, 0);
e6ac2450 1736 if (ret)
f910cefa
JW
1737 return ret;
1738
e6ac2450
MKL
1739 for (i = 0; i < insn_cnt; i++, insn++) {
1740 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1741 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 1742 continue;
e6ac2450 1743
2c78ee89 1744 if (!env->bpf_capable) {
e6ac2450 1745 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1746 return -EPERM;
1747 }
e6ac2450
MKL
1748
1749 if (bpf_pseudo_func(insn)) {
1750 ret = add_subprog(env, i + insn->imm + 1);
1751 if (ret >= 0)
1752 /* remember subprog */
1753 insn[1].imm = ret;
1754 } else if (bpf_pseudo_call(insn)) {
1755 ret = add_subprog(env, i + insn->imm + 1);
1756 } else {
1757 ret = add_kfunc_call(env, insn->imm);
1758 }
1759
cc8b0b92
AS
1760 if (ret < 0)
1761 return ret;
1762 }
1763
4cb3d99c
JW
1764 /* Add a fake 'exit' subprog which could simplify subprog iteration
1765 * logic. 'subprog_cnt' should not be increased.
1766 */
1767 subprog[env->subprog_cnt].start = insn_cnt;
1768
06ee7115 1769 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1770 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1771 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 1772
e6ac2450
MKL
1773 return 0;
1774}
1775
1776static int check_subprogs(struct bpf_verifier_env *env)
1777{
1778 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1779 struct bpf_subprog_info *subprog = env->subprog_info;
1780 struct bpf_insn *insn = env->prog->insnsi;
1781 int insn_cnt = env->prog->len;
1782
cc8b0b92 1783 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1784 subprog_start = subprog[cur_subprog].start;
1785 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1786 for (i = 0; i < insn_cnt; i++) {
1787 u8 code = insn[i].code;
1788
7f6e4312
MF
1789 if (code == (BPF_JMP | BPF_CALL) &&
1790 insn[i].imm == BPF_FUNC_tail_call &&
1791 insn[i].src_reg != BPF_PSEUDO_CALL)
1792 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1793 if (BPF_CLASS(code) == BPF_LD &&
1794 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1795 subprog[cur_subprog].has_ld_abs = true;
092ed096 1796 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1797 goto next;
1798 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1799 goto next;
1800 off = i + insn[i].off + 1;
1801 if (off < subprog_start || off >= subprog_end) {
1802 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1803 return -EINVAL;
1804 }
1805next:
1806 if (i == subprog_end - 1) {
1807 /* to avoid fall-through from one subprog into another
1808 * the last insn of the subprog should be either exit
1809 * or unconditional jump back
1810 */
1811 if (code != (BPF_JMP | BPF_EXIT) &&
1812 code != (BPF_JMP | BPF_JA)) {
1813 verbose(env, "last insn is not an exit or jmp\n");
1814 return -EINVAL;
1815 }
1816 subprog_start = subprog_end;
4cb3d99c
JW
1817 cur_subprog++;
1818 if (cur_subprog < env->subprog_cnt)
9c8105bd 1819 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1820 }
1821 }
1822 return 0;
1823}
1824
679c782d
EC
1825/* Parentage chain of this register (or stack slot) should take care of all
1826 * issues like callee-saved registers, stack slot allocation time, etc.
1827 */
f4d7e40a 1828static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1829 const struct bpf_reg_state *state,
5327ed3d 1830 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1831{
1832 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1833 int cnt = 0;
dc503a8a
EC
1834
1835 while (parent) {
1836 /* if read wasn't screened by an earlier write ... */
679c782d 1837 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1838 break;
9242b5f5
AS
1839 if (parent->live & REG_LIVE_DONE) {
1840 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1841 reg_type_str[parent->type],
1842 parent->var_off.value, parent->off);
1843 return -EFAULT;
1844 }
5327ed3d
JW
1845 /* The first condition is more likely to be true than the
1846 * second, checked it first.
1847 */
1848 if ((parent->live & REG_LIVE_READ) == flag ||
1849 parent->live & REG_LIVE_READ64)
25af32da
AS
1850 /* The parentage chain never changes and
1851 * this parent was already marked as LIVE_READ.
1852 * There is no need to keep walking the chain again and
1853 * keep re-marking all parents as LIVE_READ.
1854 * This case happens when the same register is read
1855 * multiple times without writes into it in-between.
5327ed3d
JW
1856 * Also, if parent has the stronger REG_LIVE_READ64 set,
1857 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1858 */
1859 break;
dc503a8a 1860 /* ... then we depend on parent's value */
5327ed3d
JW
1861 parent->live |= flag;
1862 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1863 if (flag == REG_LIVE_READ64)
1864 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1865 state = parent;
1866 parent = state->parent;
f4d7e40a 1867 writes = true;
06ee7115 1868 cnt++;
dc503a8a 1869 }
06ee7115
AS
1870
1871 if (env->longest_mark_read_walk < cnt)
1872 env->longest_mark_read_walk = cnt;
f4d7e40a 1873 return 0;
dc503a8a
EC
1874}
1875
5327ed3d
JW
1876/* This function is supposed to be used by the following 32-bit optimization
1877 * code only. It returns TRUE if the source or destination register operates
1878 * on 64-bit, otherwise return FALSE.
1879 */
1880static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1881 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1882{
1883 u8 code, class, op;
1884
1885 code = insn->code;
1886 class = BPF_CLASS(code);
1887 op = BPF_OP(code);
1888 if (class == BPF_JMP) {
1889 /* BPF_EXIT for "main" will reach here. Return TRUE
1890 * conservatively.
1891 */
1892 if (op == BPF_EXIT)
1893 return true;
1894 if (op == BPF_CALL) {
1895 /* BPF to BPF call will reach here because of marking
1896 * caller saved clobber with DST_OP_NO_MARK for which we
1897 * don't care the register def because they are anyway
1898 * marked as NOT_INIT already.
1899 */
1900 if (insn->src_reg == BPF_PSEUDO_CALL)
1901 return false;
1902 /* Helper call will reach here because of arg type
1903 * check, conservatively return TRUE.
1904 */
1905 if (t == SRC_OP)
1906 return true;
1907
1908 return false;
1909 }
1910 }
1911
1912 if (class == BPF_ALU64 || class == BPF_JMP ||
1913 /* BPF_END always use BPF_ALU class. */
1914 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1915 return true;
1916
1917 if (class == BPF_ALU || class == BPF_JMP32)
1918 return false;
1919
1920 if (class == BPF_LDX) {
1921 if (t != SRC_OP)
1922 return BPF_SIZE(code) == BPF_DW;
1923 /* LDX source must be ptr. */
1924 return true;
1925 }
1926
1927 if (class == BPF_STX) {
83a28819
IL
1928 /* BPF_STX (including atomic variants) has multiple source
1929 * operands, one of which is a ptr. Check whether the caller is
1930 * asking about it.
1931 */
1932 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
1933 return true;
1934 return BPF_SIZE(code) == BPF_DW;
1935 }
1936
1937 if (class == BPF_LD) {
1938 u8 mode = BPF_MODE(code);
1939
1940 /* LD_IMM64 */
1941 if (mode == BPF_IMM)
1942 return true;
1943
1944 /* Both LD_IND and LD_ABS return 32-bit data. */
1945 if (t != SRC_OP)
1946 return false;
1947
1948 /* Implicit ctx ptr. */
1949 if (regno == BPF_REG_6)
1950 return true;
1951
1952 /* Explicit source could be any width. */
1953 return true;
1954 }
1955
1956 if (class == BPF_ST)
1957 /* The only source register for BPF_ST is a ptr. */
1958 return true;
1959
1960 /* Conservatively return true at default. */
1961 return true;
1962}
1963
83a28819
IL
1964/* Return the regno defined by the insn, or -1. */
1965static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 1966{
83a28819
IL
1967 switch (BPF_CLASS(insn->code)) {
1968 case BPF_JMP:
1969 case BPF_JMP32:
1970 case BPF_ST:
1971 return -1;
1972 case BPF_STX:
1973 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1974 (insn->imm & BPF_FETCH)) {
1975 if (insn->imm == BPF_CMPXCHG)
1976 return BPF_REG_0;
1977 else
1978 return insn->src_reg;
1979 } else {
1980 return -1;
1981 }
1982 default:
1983 return insn->dst_reg;
1984 }
b325fbca
JW
1985}
1986
1987/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1988static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1989{
83a28819
IL
1990 int dst_reg = insn_def_regno(insn);
1991
1992 if (dst_reg == -1)
b325fbca
JW
1993 return false;
1994
83a28819 1995 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
1996}
1997
5327ed3d
JW
1998static void mark_insn_zext(struct bpf_verifier_env *env,
1999 struct bpf_reg_state *reg)
2000{
2001 s32 def_idx = reg->subreg_def;
2002
2003 if (def_idx == DEF_NOT_SUBREG)
2004 return;
2005
2006 env->insn_aux_data[def_idx - 1].zext_dst = true;
2007 /* The dst will be zero extended, so won't be sub-register anymore. */
2008 reg->subreg_def = DEF_NOT_SUBREG;
2009}
2010
dc503a8a 2011static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
2012 enum reg_arg_type t)
2013{
f4d7e40a
AS
2014 struct bpf_verifier_state *vstate = env->cur_state;
2015 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 2016 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 2017 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 2018 bool rw64;
dc503a8a 2019
17a52670 2020 if (regno >= MAX_BPF_REG) {
61bd5218 2021 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
2022 return -EINVAL;
2023 }
2024
c342dc10 2025 reg = &regs[regno];
5327ed3d 2026 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
2027 if (t == SRC_OP) {
2028 /* check whether register used as source operand can be read */
c342dc10 2029 if (reg->type == NOT_INIT) {
61bd5218 2030 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
2031 return -EACCES;
2032 }
679c782d 2033 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
2034 if (regno == BPF_REG_FP)
2035 return 0;
2036
5327ed3d
JW
2037 if (rw64)
2038 mark_insn_zext(env, reg);
2039
2040 return mark_reg_read(env, reg, reg->parent,
2041 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
2042 } else {
2043 /* check whether register used as dest operand can be written to */
2044 if (regno == BPF_REG_FP) {
61bd5218 2045 verbose(env, "frame pointer is read only\n");
17a52670
AS
2046 return -EACCES;
2047 }
c342dc10 2048 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 2049 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 2050 if (t == DST_OP)
61bd5218 2051 mark_reg_unknown(env, regs, regno);
17a52670
AS
2052 }
2053 return 0;
2054}
2055
b5dc0163
AS
2056/* for any branch, call, exit record the history of jmps in the given state */
2057static int push_jmp_history(struct bpf_verifier_env *env,
2058 struct bpf_verifier_state *cur)
2059{
2060 u32 cnt = cur->jmp_history_cnt;
2061 struct bpf_idx_pair *p;
2062
2063 cnt++;
2064 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2065 if (!p)
2066 return -ENOMEM;
2067 p[cnt - 1].idx = env->insn_idx;
2068 p[cnt - 1].prev_idx = env->prev_insn_idx;
2069 cur->jmp_history = p;
2070 cur->jmp_history_cnt = cnt;
2071 return 0;
2072}
2073
2074/* Backtrack one insn at a time. If idx is not at the top of recorded
2075 * history then previous instruction came from straight line execution.
2076 */
2077static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2078 u32 *history)
2079{
2080 u32 cnt = *history;
2081
2082 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2083 i = st->jmp_history[cnt - 1].prev_idx;
2084 (*history)--;
2085 } else {
2086 i--;
2087 }
2088 return i;
2089}
2090
e6ac2450
MKL
2091static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2092{
2093 const struct btf_type *func;
2094
2095 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2096 return NULL;
2097
2098 func = btf_type_by_id(btf_vmlinux, insn->imm);
2099 return btf_name_by_offset(btf_vmlinux, func->name_off);
2100}
2101
b5dc0163
AS
2102/* For given verifier state backtrack_insn() is called from the last insn to
2103 * the first insn. Its purpose is to compute a bitmask of registers and
2104 * stack slots that needs precision in the parent verifier state.
2105 */
2106static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2107 u32 *reg_mask, u64 *stack_mask)
2108{
2109 const struct bpf_insn_cbs cbs = {
e6ac2450 2110 .cb_call = disasm_kfunc_name,
b5dc0163
AS
2111 .cb_print = verbose,
2112 .private_data = env,
2113 };
2114 struct bpf_insn *insn = env->prog->insnsi + idx;
2115 u8 class = BPF_CLASS(insn->code);
2116 u8 opcode = BPF_OP(insn->code);
2117 u8 mode = BPF_MODE(insn->code);
2118 u32 dreg = 1u << insn->dst_reg;
2119 u32 sreg = 1u << insn->src_reg;
2120 u32 spi;
2121
2122 if (insn->code == 0)
2123 return 0;
2124 if (env->log.level & BPF_LOG_LEVEL) {
2125 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2126 verbose(env, "%d: ", idx);
2127 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2128 }
2129
2130 if (class == BPF_ALU || class == BPF_ALU64) {
2131 if (!(*reg_mask & dreg))
2132 return 0;
2133 if (opcode == BPF_MOV) {
2134 if (BPF_SRC(insn->code) == BPF_X) {
2135 /* dreg = sreg
2136 * dreg needs precision after this insn
2137 * sreg needs precision before this insn
2138 */
2139 *reg_mask &= ~dreg;
2140 *reg_mask |= sreg;
2141 } else {
2142 /* dreg = K
2143 * dreg needs precision after this insn.
2144 * Corresponding register is already marked
2145 * as precise=true in this verifier state.
2146 * No further markings in parent are necessary
2147 */
2148 *reg_mask &= ~dreg;
2149 }
2150 } else {
2151 if (BPF_SRC(insn->code) == BPF_X) {
2152 /* dreg += sreg
2153 * both dreg and sreg need precision
2154 * before this insn
2155 */
2156 *reg_mask |= sreg;
2157 } /* else dreg += K
2158 * dreg still needs precision before this insn
2159 */
2160 }
2161 } else if (class == BPF_LDX) {
2162 if (!(*reg_mask & dreg))
2163 return 0;
2164 *reg_mask &= ~dreg;
2165
2166 /* scalars can only be spilled into stack w/o losing precision.
2167 * Load from any other memory can be zero extended.
2168 * The desire to keep that precision is already indicated
2169 * by 'precise' mark in corresponding register of this state.
2170 * No further tracking necessary.
2171 */
2172 if (insn->src_reg != BPF_REG_FP)
2173 return 0;
2174 if (BPF_SIZE(insn->code) != BPF_DW)
2175 return 0;
2176
2177 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2178 * that [fp - off] slot contains scalar that needs to be
2179 * tracked with precision
2180 */
2181 spi = (-insn->off - 1) / BPF_REG_SIZE;
2182 if (spi >= 64) {
2183 verbose(env, "BUG spi %d\n", spi);
2184 WARN_ONCE(1, "verifier backtracking bug");
2185 return -EFAULT;
2186 }
2187 *stack_mask |= 1ull << spi;
b3b50f05 2188 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2189 if (*reg_mask & dreg)
b3b50f05 2190 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2191 * to access memory. It means backtracking
2192 * encountered a case of pointer subtraction.
2193 */
2194 return -ENOTSUPP;
2195 /* scalars can only be spilled into stack */
2196 if (insn->dst_reg != BPF_REG_FP)
2197 return 0;
2198 if (BPF_SIZE(insn->code) != BPF_DW)
2199 return 0;
2200 spi = (-insn->off - 1) / BPF_REG_SIZE;
2201 if (spi >= 64) {
2202 verbose(env, "BUG spi %d\n", spi);
2203 WARN_ONCE(1, "verifier backtracking bug");
2204 return -EFAULT;
2205 }
2206 if (!(*stack_mask & (1ull << spi)))
2207 return 0;
2208 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2209 if (class == BPF_STX)
2210 *reg_mask |= sreg;
b5dc0163
AS
2211 } else if (class == BPF_JMP || class == BPF_JMP32) {
2212 if (opcode == BPF_CALL) {
2213 if (insn->src_reg == BPF_PSEUDO_CALL)
2214 return -ENOTSUPP;
2215 /* regular helper call sets R0 */
2216 *reg_mask &= ~1;
2217 if (*reg_mask & 0x3f) {
2218 /* if backtracing was looking for registers R1-R5
2219 * they should have been found already.
2220 */
2221 verbose(env, "BUG regs %x\n", *reg_mask);
2222 WARN_ONCE(1, "verifier backtracking bug");
2223 return -EFAULT;
2224 }
2225 } else if (opcode == BPF_EXIT) {
2226 return -ENOTSUPP;
2227 }
2228 } else if (class == BPF_LD) {
2229 if (!(*reg_mask & dreg))
2230 return 0;
2231 *reg_mask &= ~dreg;
2232 /* It's ld_imm64 or ld_abs or ld_ind.
2233 * For ld_imm64 no further tracking of precision
2234 * into parent is necessary
2235 */
2236 if (mode == BPF_IND || mode == BPF_ABS)
2237 /* to be analyzed */
2238 return -ENOTSUPP;
b5dc0163
AS
2239 }
2240 return 0;
2241}
2242
2243/* the scalar precision tracking algorithm:
2244 * . at the start all registers have precise=false.
2245 * . scalar ranges are tracked as normal through alu and jmp insns.
2246 * . once precise value of the scalar register is used in:
2247 * . ptr + scalar alu
2248 * . if (scalar cond K|scalar)
2249 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2250 * backtrack through the verifier states and mark all registers and
2251 * stack slots with spilled constants that these scalar regisers
2252 * should be precise.
2253 * . during state pruning two registers (or spilled stack slots)
2254 * are equivalent if both are not precise.
2255 *
2256 * Note the verifier cannot simply walk register parentage chain,
2257 * since many different registers and stack slots could have been
2258 * used to compute single precise scalar.
2259 *
2260 * The approach of starting with precise=true for all registers and then
2261 * backtrack to mark a register as not precise when the verifier detects
2262 * that program doesn't care about specific value (e.g., when helper
2263 * takes register as ARG_ANYTHING parameter) is not safe.
2264 *
2265 * It's ok to walk single parentage chain of the verifier states.
2266 * It's possible that this backtracking will go all the way till 1st insn.
2267 * All other branches will be explored for needing precision later.
2268 *
2269 * The backtracking needs to deal with cases like:
2270 * 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)
2271 * r9 -= r8
2272 * r5 = r9
2273 * if r5 > 0x79f goto pc+7
2274 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2275 * r5 += 1
2276 * ...
2277 * call bpf_perf_event_output#25
2278 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2279 *
2280 * and this case:
2281 * r6 = 1
2282 * call foo // uses callee's r6 inside to compute r0
2283 * r0 += r6
2284 * if r0 == 0 goto
2285 *
2286 * to track above reg_mask/stack_mask needs to be independent for each frame.
2287 *
2288 * Also if parent's curframe > frame where backtracking started,
2289 * the verifier need to mark registers in both frames, otherwise callees
2290 * may incorrectly prune callers. This is similar to
2291 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2292 *
2293 * For now backtracking falls back into conservative marking.
2294 */
2295static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2296 struct bpf_verifier_state *st)
2297{
2298 struct bpf_func_state *func;
2299 struct bpf_reg_state *reg;
2300 int i, j;
2301
2302 /* big hammer: mark all scalars precise in this path.
2303 * pop_stack may still get !precise scalars.
2304 */
2305 for (; st; st = st->parent)
2306 for (i = 0; i <= st->curframe; i++) {
2307 func = st->frame[i];
2308 for (j = 0; j < BPF_REG_FP; j++) {
2309 reg = &func->regs[j];
2310 if (reg->type != SCALAR_VALUE)
2311 continue;
2312 reg->precise = true;
2313 }
2314 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2315 if (func->stack[j].slot_type[0] != STACK_SPILL)
2316 continue;
2317 reg = &func->stack[j].spilled_ptr;
2318 if (reg->type != SCALAR_VALUE)
2319 continue;
2320 reg->precise = true;
2321 }
2322 }
2323}
2324
a3ce685d
AS
2325static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2326 int spi)
b5dc0163
AS
2327{
2328 struct bpf_verifier_state *st = env->cur_state;
2329 int first_idx = st->first_insn_idx;
2330 int last_idx = env->insn_idx;
2331 struct bpf_func_state *func;
2332 struct bpf_reg_state *reg;
a3ce685d
AS
2333 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2334 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2335 bool skip_first = true;
a3ce685d 2336 bool new_marks = false;
b5dc0163
AS
2337 int i, err;
2338
2c78ee89 2339 if (!env->bpf_capable)
b5dc0163
AS
2340 return 0;
2341
2342 func = st->frame[st->curframe];
a3ce685d
AS
2343 if (regno >= 0) {
2344 reg = &func->regs[regno];
2345 if (reg->type != SCALAR_VALUE) {
2346 WARN_ONCE(1, "backtracing misuse");
2347 return -EFAULT;
2348 }
2349 if (!reg->precise)
2350 new_marks = true;
2351 else
2352 reg_mask = 0;
2353 reg->precise = true;
b5dc0163 2354 }
b5dc0163 2355
a3ce685d
AS
2356 while (spi >= 0) {
2357 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2358 stack_mask = 0;
2359 break;
2360 }
2361 reg = &func->stack[spi].spilled_ptr;
2362 if (reg->type != SCALAR_VALUE) {
2363 stack_mask = 0;
2364 break;
2365 }
2366 if (!reg->precise)
2367 new_marks = true;
2368 else
2369 stack_mask = 0;
2370 reg->precise = true;
2371 break;
2372 }
2373
2374 if (!new_marks)
2375 return 0;
2376 if (!reg_mask && !stack_mask)
2377 return 0;
b5dc0163
AS
2378 for (;;) {
2379 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2380 u32 history = st->jmp_history_cnt;
2381
2382 if (env->log.level & BPF_LOG_LEVEL)
2383 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2384 for (i = last_idx;;) {
2385 if (skip_first) {
2386 err = 0;
2387 skip_first = false;
2388 } else {
2389 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2390 }
2391 if (err == -ENOTSUPP) {
2392 mark_all_scalars_precise(env, st);
2393 return 0;
2394 } else if (err) {
2395 return err;
2396 }
2397 if (!reg_mask && !stack_mask)
2398 /* Found assignment(s) into tracked register in this state.
2399 * Since this state is already marked, just return.
2400 * Nothing to be tracked further in the parent state.
2401 */
2402 return 0;
2403 if (i == first_idx)
2404 break;
2405 i = get_prev_insn_idx(st, i, &history);
2406 if (i >= env->prog->len) {
2407 /* This can happen if backtracking reached insn 0
2408 * and there are still reg_mask or stack_mask
2409 * to backtrack.
2410 * It means the backtracking missed the spot where
2411 * particular register was initialized with a constant.
2412 */
2413 verbose(env, "BUG backtracking idx %d\n", i);
2414 WARN_ONCE(1, "verifier backtracking bug");
2415 return -EFAULT;
2416 }
2417 }
2418 st = st->parent;
2419 if (!st)
2420 break;
2421
a3ce685d 2422 new_marks = false;
b5dc0163
AS
2423 func = st->frame[st->curframe];
2424 bitmap_from_u64(mask, reg_mask);
2425 for_each_set_bit(i, mask, 32) {
2426 reg = &func->regs[i];
a3ce685d
AS
2427 if (reg->type != SCALAR_VALUE) {
2428 reg_mask &= ~(1u << i);
b5dc0163 2429 continue;
a3ce685d 2430 }
b5dc0163
AS
2431 if (!reg->precise)
2432 new_marks = true;
2433 reg->precise = true;
2434 }
2435
2436 bitmap_from_u64(mask, stack_mask);
2437 for_each_set_bit(i, mask, 64) {
2438 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2439 /* the sequence of instructions:
2440 * 2: (bf) r3 = r10
2441 * 3: (7b) *(u64 *)(r3 -8) = r0
2442 * 4: (79) r4 = *(u64 *)(r10 -8)
2443 * doesn't contain jmps. It's backtracked
2444 * as a single block.
2445 * During backtracking insn 3 is not recognized as
2446 * stack access, so at the end of backtracking
2447 * stack slot fp-8 is still marked in stack_mask.
2448 * However the parent state may not have accessed
2449 * fp-8 and it's "unallocated" stack space.
2450 * In such case fallback to conservative.
b5dc0163 2451 */
2339cd6c
AS
2452 mark_all_scalars_precise(env, st);
2453 return 0;
b5dc0163
AS
2454 }
2455
a3ce685d
AS
2456 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2457 stack_mask &= ~(1ull << i);
b5dc0163 2458 continue;
a3ce685d 2459 }
b5dc0163 2460 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2461 if (reg->type != SCALAR_VALUE) {
2462 stack_mask &= ~(1ull << i);
b5dc0163 2463 continue;
a3ce685d 2464 }
b5dc0163
AS
2465 if (!reg->precise)
2466 new_marks = true;
2467 reg->precise = true;
2468 }
2469 if (env->log.level & BPF_LOG_LEVEL) {
2470 print_verifier_state(env, func);
2471 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2472 new_marks ? "didn't have" : "already had",
2473 reg_mask, stack_mask);
2474 }
2475
a3ce685d
AS
2476 if (!reg_mask && !stack_mask)
2477 break;
b5dc0163
AS
2478 if (!new_marks)
2479 break;
2480
2481 last_idx = st->last_insn_idx;
2482 first_idx = st->first_insn_idx;
2483 }
2484 return 0;
2485}
2486
a3ce685d
AS
2487static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2488{
2489 return __mark_chain_precision(env, regno, -1);
2490}
2491
2492static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2493{
2494 return __mark_chain_precision(env, -1, spi);
2495}
b5dc0163 2496
1be7f75d
AS
2497static bool is_spillable_regtype(enum bpf_reg_type type)
2498{
2499 switch (type) {
2500 case PTR_TO_MAP_VALUE:
2501 case PTR_TO_MAP_VALUE_OR_NULL:
2502 case PTR_TO_STACK:
2503 case PTR_TO_CTX:
969bf05e 2504 case PTR_TO_PACKET:
de8f3a83 2505 case PTR_TO_PACKET_META:
969bf05e 2506 case PTR_TO_PACKET_END:
d58e468b 2507 case PTR_TO_FLOW_KEYS:
1be7f75d 2508 case CONST_PTR_TO_MAP:
c64b7983
JS
2509 case PTR_TO_SOCKET:
2510 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2511 case PTR_TO_SOCK_COMMON:
2512 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2513 case PTR_TO_TCP_SOCK:
2514 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2515 case PTR_TO_XDP_SOCK:
65726b5b 2516 case PTR_TO_BTF_ID:
b121b341 2517 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2518 case PTR_TO_RDONLY_BUF:
2519 case PTR_TO_RDONLY_BUF_OR_NULL:
2520 case PTR_TO_RDWR_BUF:
2521 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2522 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2523 case PTR_TO_MEM:
2524 case PTR_TO_MEM_OR_NULL:
69c087ba
YS
2525 case PTR_TO_FUNC:
2526 case PTR_TO_MAP_KEY:
1be7f75d
AS
2527 return true;
2528 default:
2529 return false;
2530 }
2531}
2532
cc2b14d5
AS
2533/* Does this register contain a constant zero? */
2534static bool register_is_null(struct bpf_reg_state *reg)
2535{
2536 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2537}
2538
f7cf25b2
AS
2539static bool register_is_const(struct bpf_reg_state *reg)
2540{
2541 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2542}
2543
5689d49b
YS
2544static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2545{
2546 return tnum_is_unknown(reg->var_off) &&
2547 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2548 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2549 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2550 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2551}
2552
2553static bool register_is_bounded(struct bpf_reg_state *reg)
2554{
2555 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2556}
2557
6e7e63cb
JH
2558static bool __is_pointer_value(bool allow_ptr_leaks,
2559 const struct bpf_reg_state *reg)
2560{
2561 if (allow_ptr_leaks)
2562 return false;
2563
2564 return reg->type != SCALAR_VALUE;
2565}
2566
f7cf25b2
AS
2567static void save_register_state(struct bpf_func_state *state,
2568 int spi, struct bpf_reg_state *reg)
2569{
2570 int i;
2571
2572 state->stack[spi].spilled_ptr = *reg;
2573 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2574
2575 for (i = 0; i < BPF_REG_SIZE; i++)
2576 state->stack[spi].slot_type[i] = STACK_SPILL;
2577}
2578
01f810ac 2579/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2580 * stack boundary and alignment are checked in check_mem_access()
2581 */
01f810ac
AM
2582static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2583 /* stack frame we're writing to */
2584 struct bpf_func_state *state,
2585 int off, int size, int value_regno,
2586 int insn_idx)
17a52670 2587{
f4d7e40a 2588 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2589 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2590 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2591 struct bpf_reg_state *reg = NULL;
638f5b90 2592
f4d7e40a 2593 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2594 state->acquired_refs, true);
638f5b90
AS
2595 if (err)
2596 return err;
9c399760
AS
2597 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2598 * so it's aligned access and [off, off + size) are within stack limits
2599 */
638f5b90
AS
2600 if (!env->allow_ptr_leaks &&
2601 state->stack[spi].slot_type[0] == STACK_SPILL &&
2602 size != BPF_REG_SIZE) {
2603 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2604 return -EACCES;
2605 }
17a52670 2606
f4d7e40a 2607 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2608 if (value_regno >= 0)
2609 reg = &cur->regs[value_regno];
17a52670 2610
5689d49b 2611 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2612 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2613 if (dst_reg != BPF_REG_FP) {
2614 /* The backtracking logic can only recognize explicit
2615 * stack slot address like [fp - 8]. Other spill of
2616 * scalar via different register has to be conervative.
2617 * Backtrack from here and mark all registers as precise
2618 * that contributed into 'reg' being a constant.
2619 */
2620 err = mark_chain_precision(env, value_regno);
2621 if (err)
2622 return err;
2623 }
f7cf25b2
AS
2624 save_register_state(state, spi, reg);
2625 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2626 /* register containing pointer is being spilled into stack */
9c399760 2627 if (size != BPF_REG_SIZE) {
f7cf25b2 2628 verbose_linfo(env, insn_idx, "; ");
61bd5218 2629 verbose(env, "invalid size of register spill\n");
17a52670
AS
2630 return -EACCES;
2631 }
2632
f7cf25b2 2633 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2634 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2635 return -EINVAL;
2636 }
2637
2c78ee89 2638 if (!env->bypass_spec_v4) {
f7cf25b2 2639 bool sanitize = false;
17a52670 2640
f7cf25b2
AS
2641 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2642 register_is_const(&state->stack[spi].spilled_ptr))
2643 sanitize = true;
2644 for (i = 0; i < BPF_REG_SIZE; i++)
2645 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2646 sanitize = true;
2647 break;
2648 }
2649 if (sanitize) {
af86ca4e
AS
2650 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2651 int soff = (-spi - 1) * BPF_REG_SIZE;
2652
2653 /* detected reuse of integer stack slot with a pointer
2654 * which means either llvm is reusing stack slot or
2655 * an attacker is trying to exploit CVE-2018-3639
2656 * (speculative store bypass)
2657 * Have to sanitize that slot with preemptive
2658 * store of zero.
2659 */
2660 if (*poff && *poff != soff) {
2661 /* disallow programs where single insn stores
2662 * into two different stack slots, since verifier
2663 * cannot sanitize them
2664 */
2665 verbose(env,
2666 "insn %d cannot access two stack slots fp%d and fp%d",
2667 insn_idx, *poff, soff);
2668 return -EINVAL;
2669 }
2670 *poff = soff;
2671 }
af86ca4e 2672 }
f7cf25b2 2673 save_register_state(state, spi, reg);
9c399760 2674 } else {
cc2b14d5
AS
2675 u8 type = STACK_MISC;
2676
679c782d
EC
2677 /* regular write of data into stack destroys any spilled ptr */
2678 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2679 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2680 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2681 for (i = 0; i < BPF_REG_SIZE; i++)
2682 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2683
cc2b14d5
AS
2684 /* only mark the slot as written if all 8 bytes were written
2685 * otherwise read propagation may incorrectly stop too soon
2686 * when stack slots are partially written.
2687 * This heuristic means that read propagation will be
2688 * conservative, since it will add reg_live_read marks
2689 * to stack slots all the way to first state when programs
2690 * writes+reads less than 8 bytes
2691 */
2692 if (size == BPF_REG_SIZE)
2693 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2694
2695 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2696 if (reg && register_is_null(reg)) {
2697 /* backtracking doesn't work for STACK_ZERO yet. */
2698 err = mark_chain_precision(env, value_regno);
2699 if (err)
2700 return err;
cc2b14d5 2701 type = STACK_ZERO;
b5dc0163 2702 }
cc2b14d5 2703
0bae2d4d 2704 /* Mark slots affected by this stack write. */
9c399760 2705 for (i = 0; i < size; i++)
638f5b90 2706 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2707 type;
17a52670
AS
2708 }
2709 return 0;
2710}
2711
01f810ac
AM
2712/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2713 * known to contain a variable offset.
2714 * This function checks whether the write is permitted and conservatively
2715 * tracks the effects of the write, considering that each stack slot in the
2716 * dynamic range is potentially written to.
2717 *
2718 * 'off' includes 'regno->off'.
2719 * 'value_regno' can be -1, meaning that an unknown value is being written to
2720 * the stack.
2721 *
2722 * Spilled pointers in range are not marked as written because we don't know
2723 * what's going to be actually written. This means that read propagation for
2724 * future reads cannot be terminated by this write.
2725 *
2726 * For privileged programs, uninitialized stack slots are considered
2727 * initialized by this write (even though we don't know exactly what offsets
2728 * are going to be written to). The idea is that we don't want the verifier to
2729 * reject future reads that access slots written to through variable offsets.
2730 */
2731static int check_stack_write_var_off(struct bpf_verifier_env *env,
2732 /* func where register points to */
2733 struct bpf_func_state *state,
2734 int ptr_regno, int off, int size,
2735 int value_regno, int insn_idx)
2736{
2737 struct bpf_func_state *cur; /* state of the current function */
2738 int min_off, max_off;
2739 int i, err;
2740 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2741 bool writing_zero = false;
2742 /* set if the fact that we're writing a zero is used to let any
2743 * stack slots remain STACK_ZERO
2744 */
2745 bool zero_used = false;
2746
2747 cur = env->cur_state->frame[env->cur_state->curframe];
2748 ptr_reg = &cur->regs[ptr_regno];
2749 min_off = ptr_reg->smin_value + off;
2750 max_off = ptr_reg->smax_value + off + size;
2751 if (value_regno >= 0)
2752 value_reg = &cur->regs[value_regno];
2753 if (value_reg && register_is_null(value_reg))
2754 writing_zero = true;
2755
2756 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2757 state->acquired_refs, true);
2758 if (err)
2759 return err;
2760
2761
2762 /* Variable offset writes destroy any spilled pointers in range. */
2763 for (i = min_off; i < max_off; i++) {
2764 u8 new_type, *stype;
2765 int slot, spi;
2766
2767 slot = -i - 1;
2768 spi = slot / BPF_REG_SIZE;
2769 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2770
2771 if (!env->allow_ptr_leaks
2772 && *stype != NOT_INIT
2773 && *stype != SCALAR_VALUE) {
2774 /* Reject the write if there's are spilled pointers in
2775 * range. If we didn't reject here, the ptr status
2776 * would be erased below (even though not all slots are
2777 * actually overwritten), possibly opening the door to
2778 * leaks.
2779 */
2780 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2781 insn_idx, i);
2782 return -EINVAL;
2783 }
2784
2785 /* Erase all spilled pointers. */
2786 state->stack[spi].spilled_ptr.type = NOT_INIT;
2787
2788 /* Update the slot type. */
2789 new_type = STACK_MISC;
2790 if (writing_zero && *stype == STACK_ZERO) {
2791 new_type = STACK_ZERO;
2792 zero_used = true;
2793 }
2794 /* If the slot is STACK_INVALID, we check whether it's OK to
2795 * pretend that it will be initialized by this write. The slot
2796 * might not actually be written to, and so if we mark it as
2797 * initialized future reads might leak uninitialized memory.
2798 * For privileged programs, we will accept such reads to slots
2799 * that may or may not be written because, if we're reject
2800 * them, the error would be too confusing.
2801 */
2802 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2803 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2804 insn_idx, i);
2805 return -EINVAL;
2806 }
2807 *stype = new_type;
2808 }
2809 if (zero_used) {
2810 /* backtracking doesn't work for STACK_ZERO yet. */
2811 err = mark_chain_precision(env, value_regno);
2812 if (err)
2813 return err;
2814 }
2815 return 0;
2816}
2817
2818/* When register 'dst_regno' is assigned some values from stack[min_off,
2819 * max_off), we set the register's type according to the types of the
2820 * respective stack slots. If all the stack values are known to be zeros, then
2821 * so is the destination reg. Otherwise, the register is considered to be
2822 * SCALAR. This function does not deal with register filling; the caller must
2823 * ensure that all spilled registers in the stack range have been marked as
2824 * read.
2825 */
2826static void mark_reg_stack_read(struct bpf_verifier_env *env,
2827 /* func where src register points to */
2828 struct bpf_func_state *ptr_state,
2829 int min_off, int max_off, int dst_regno)
2830{
2831 struct bpf_verifier_state *vstate = env->cur_state;
2832 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2833 int i, slot, spi;
2834 u8 *stype;
2835 int zeros = 0;
2836
2837 for (i = min_off; i < max_off; i++) {
2838 slot = -i - 1;
2839 spi = slot / BPF_REG_SIZE;
2840 stype = ptr_state->stack[spi].slot_type;
2841 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2842 break;
2843 zeros++;
2844 }
2845 if (zeros == max_off - min_off) {
2846 /* any access_size read into register is zero extended,
2847 * so the whole register == const_zero
2848 */
2849 __mark_reg_const_zero(&state->regs[dst_regno]);
2850 /* backtracking doesn't support STACK_ZERO yet,
2851 * so mark it precise here, so that later
2852 * backtracking can stop here.
2853 * Backtracking may not need this if this register
2854 * doesn't participate in pointer adjustment.
2855 * Forward propagation of precise flag is not
2856 * necessary either. This mark is only to stop
2857 * backtracking. Any register that contributed
2858 * to const 0 was marked precise before spill.
2859 */
2860 state->regs[dst_regno].precise = true;
2861 } else {
2862 /* have read misc data from the stack */
2863 mark_reg_unknown(env, state->regs, dst_regno);
2864 }
2865 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2866}
2867
2868/* Read the stack at 'off' and put the results into the register indicated by
2869 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2870 * spilled reg.
2871 *
2872 * 'dst_regno' can be -1, meaning that the read value is not going to a
2873 * register.
2874 *
2875 * The access is assumed to be within the current stack bounds.
2876 */
2877static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2878 /* func where src register points to */
2879 struct bpf_func_state *reg_state,
2880 int off, int size, int dst_regno)
17a52670 2881{
f4d7e40a
AS
2882 struct bpf_verifier_state *vstate = env->cur_state;
2883 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2884 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2885 struct bpf_reg_state *reg;
638f5b90 2886 u8 *stype;
17a52670 2887
f4d7e40a 2888 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2889 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2890
638f5b90 2891 if (stype[0] == STACK_SPILL) {
9c399760 2892 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2893 if (reg->type != SCALAR_VALUE) {
2894 verbose_linfo(env, env->insn_idx, "; ");
2895 verbose(env, "invalid size of register fill\n");
2896 return -EACCES;
2897 }
01f810ac
AM
2898 if (dst_regno >= 0) {
2899 mark_reg_unknown(env, state->regs, dst_regno);
2900 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2901 }
2902 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2903 return 0;
17a52670 2904 }
9c399760 2905 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2906 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2907 verbose(env, "corrupted spill memory\n");
17a52670
AS
2908 return -EACCES;
2909 }
2910 }
2911
01f810ac 2912 if (dst_regno >= 0) {
17a52670 2913 /* restore register state from stack */
01f810ac 2914 state->regs[dst_regno] = *reg;
2f18f62e
AS
2915 /* mark reg as written since spilled pointer state likely
2916 * has its liveness marks cleared by is_state_visited()
2917 * which resets stack/reg liveness for state transitions
2918 */
01f810ac 2919 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2920 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 2921 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2922 * it is acceptable to use this value as a SCALAR_VALUE
2923 * (e.g. for XADD).
2924 * We must not allow unprivileged callers to do that
2925 * with spilled pointers.
2926 */
2927 verbose(env, "leaking pointer from stack off %d\n",
2928 off);
2929 return -EACCES;
dc503a8a 2930 }
f7cf25b2 2931 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2932 } else {
01f810ac 2933 u8 type;
cc2b14d5 2934
17a52670 2935 for (i = 0; i < size; i++) {
01f810ac
AM
2936 type = stype[(slot - i) % BPF_REG_SIZE];
2937 if (type == STACK_MISC)
cc2b14d5 2938 continue;
01f810ac 2939 if (type == STACK_ZERO)
cc2b14d5 2940 continue;
cc2b14d5
AS
2941 verbose(env, "invalid read from stack off %d+%d size %d\n",
2942 off, i, size);
2943 return -EACCES;
2944 }
f7cf25b2 2945 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
2946 if (dst_regno >= 0)
2947 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2948 }
f7cf25b2 2949 return 0;
17a52670
AS
2950}
2951
01f810ac
AM
2952enum stack_access_src {
2953 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2954 ACCESS_HELPER = 2, /* the access is performed by a helper */
2955};
2956
2957static int check_stack_range_initialized(struct bpf_verifier_env *env,
2958 int regno, int off, int access_size,
2959 bool zero_size_allowed,
2960 enum stack_access_src type,
2961 struct bpf_call_arg_meta *meta);
2962
2963static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2964{
2965 return cur_regs(env) + regno;
2966}
2967
2968/* Read the stack at 'ptr_regno + off' and put the result into the register
2969 * 'dst_regno'.
2970 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2971 * but not its variable offset.
2972 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2973 *
2974 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2975 * filling registers (i.e. reads of spilled register cannot be detected when
2976 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2977 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2978 * offset; for a fixed offset check_stack_read_fixed_off should be used
2979 * instead.
2980 */
2981static int check_stack_read_var_off(struct bpf_verifier_env *env,
2982 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2983{
01f810ac
AM
2984 /* The state of the source register. */
2985 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2986 struct bpf_func_state *ptr_state = func(env, reg);
2987 int err;
2988 int min_off, max_off;
2989
2990 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2991 */
01f810ac
AM
2992 err = check_stack_range_initialized(env, ptr_regno, off, size,
2993 false, ACCESS_DIRECT, NULL);
2994 if (err)
2995 return err;
2996
2997 min_off = reg->smin_value + off;
2998 max_off = reg->smax_value + off;
2999 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3000 return 0;
3001}
3002
3003/* check_stack_read dispatches to check_stack_read_fixed_off or
3004 * check_stack_read_var_off.
3005 *
3006 * The caller must ensure that the offset falls within the allocated stack
3007 * bounds.
3008 *
3009 * 'dst_regno' is a register which will receive the value from the stack. It
3010 * can be -1, meaning that the read value is not going to a register.
3011 */
3012static int check_stack_read(struct bpf_verifier_env *env,
3013 int ptr_regno, int off, int size,
3014 int dst_regno)
3015{
3016 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3017 struct bpf_func_state *state = func(env, reg);
3018 int err;
3019 /* Some accesses are only permitted with a static offset. */
3020 bool var_off = !tnum_is_const(reg->var_off);
3021
3022 /* The offset is required to be static when reads don't go to a
3023 * register, in order to not leak pointers (see
3024 * check_stack_read_fixed_off).
3025 */
3026 if (dst_regno < 0 && var_off) {
e4298d25
DB
3027 char tn_buf[48];
3028
3029 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 3030 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
3031 tn_buf, off, size);
3032 return -EACCES;
3033 }
01f810ac
AM
3034 /* Variable offset is prohibited for unprivileged mode for simplicity
3035 * since it requires corresponding support in Spectre masking for stack
3036 * ALU. See also retrieve_ptr_limit().
3037 */
3038 if (!env->bypass_spec_v1 && var_off) {
3039 char tn_buf[48];
e4298d25 3040
01f810ac
AM
3041 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3042 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3043 ptr_regno, tn_buf);
e4298d25
DB
3044 return -EACCES;
3045 }
3046
01f810ac
AM
3047 if (!var_off) {
3048 off += reg->var_off.value;
3049 err = check_stack_read_fixed_off(env, state, off, size,
3050 dst_regno);
3051 } else {
3052 /* Variable offset stack reads need more conservative handling
3053 * than fixed offset ones. Note that dst_regno >= 0 on this
3054 * branch.
3055 */
3056 err = check_stack_read_var_off(env, ptr_regno, off, size,
3057 dst_regno);
3058 }
3059 return err;
3060}
3061
3062
3063/* check_stack_write dispatches to check_stack_write_fixed_off or
3064 * check_stack_write_var_off.
3065 *
3066 * 'ptr_regno' is the register used as a pointer into the stack.
3067 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3068 * 'value_regno' is the register whose value we're writing to the stack. It can
3069 * be -1, meaning that we're not writing from a register.
3070 *
3071 * The caller must ensure that the offset falls within the maximum stack size.
3072 */
3073static int check_stack_write(struct bpf_verifier_env *env,
3074 int ptr_regno, int off, int size,
3075 int value_regno, int insn_idx)
3076{
3077 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3078 struct bpf_func_state *state = func(env, reg);
3079 int err;
3080
3081 if (tnum_is_const(reg->var_off)) {
3082 off += reg->var_off.value;
3083 err = check_stack_write_fixed_off(env, state, off, size,
3084 value_regno, insn_idx);
3085 } else {
3086 /* Variable offset stack reads need more conservative handling
3087 * than fixed offset ones.
3088 */
3089 err = check_stack_write_var_off(env, state,
3090 ptr_regno, off, size,
3091 value_regno, insn_idx);
3092 }
3093 return err;
e4298d25
DB
3094}
3095
591fe988
DB
3096static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3097 int off, int size, enum bpf_access_type type)
3098{
3099 struct bpf_reg_state *regs = cur_regs(env);
3100 struct bpf_map *map = regs[regno].map_ptr;
3101 u32 cap = bpf_map_flags_to_cap(map);
3102
3103 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3104 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3105 map->value_size, off, size);
3106 return -EACCES;
3107 }
3108
3109 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3110 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3111 map->value_size, off, size);
3112 return -EACCES;
3113 }
3114
3115 return 0;
3116}
3117
457f4436
AN
3118/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3119static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3120 int off, int size, u32 mem_size,
3121 bool zero_size_allowed)
17a52670 3122{
457f4436
AN
3123 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3124 struct bpf_reg_state *reg;
3125
3126 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3127 return 0;
17a52670 3128
457f4436
AN
3129 reg = &cur_regs(env)[regno];
3130 switch (reg->type) {
69c087ba
YS
3131 case PTR_TO_MAP_KEY:
3132 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3133 mem_size, off, size);
3134 break;
457f4436 3135 case PTR_TO_MAP_VALUE:
61bd5218 3136 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
3137 mem_size, off, size);
3138 break;
3139 case PTR_TO_PACKET:
3140 case PTR_TO_PACKET_META:
3141 case PTR_TO_PACKET_END:
3142 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3143 off, size, regno, reg->id, off, mem_size);
3144 break;
3145 case PTR_TO_MEM:
3146 default:
3147 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3148 mem_size, off, size);
17a52670 3149 }
457f4436
AN
3150
3151 return -EACCES;
17a52670
AS
3152}
3153
457f4436
AN
3154/* check read/write into a memory region with possible variable offset */
3155static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3156 int off, int size, u32 mem_size,
3157 bool zero_size_allowed)
dbcfe5f7 3158{
f4d7e40a
AS
3159 struct bpf_verifier_state *vstate = env->cur_state;
3160 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
3161 struct bpf_reg_state *reg = &state->regs[regno];
3162 int err;
3163
457f4436 3164 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
3165 * need to try adding each of min_value and max_value to off
3166 * to make sure our theoretical access will be safe.
dbcfe5f7 3167 */
06ee7115 3168 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 3169 print_verifier_state(env, state);
b7137c4e 3170
dbcfe5f7
GB
3171 /* The minimum value is only important with signed
3172 * comparisons where we can't assume the floor of a
3173 * value is 0. If we are using signed variables for our
3174 * index'es we need to make sure that whatever we use
3175 * will have a set floor within our range.
3176 */
b7137c4e
DB
3177 if (reg->smin_value < 0 &&
3178 (reg->smin_value == S64_MIN ||
3179 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3180 reg->smin_value + off < 0)) {
61bd5218 3181 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
3182 regno);
3183 return -EACCES;
3184 }
457f4436
AN
3185 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3186 mem_size, zero_size_allowed);
dbcfe5f7 3187 if (err) {
457f4436 3188 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3189 regno);
dbcfe5f7
GB
3190 return err;
3191 }
3192
b03c9f9f
EC
3193 /* If we haven't set a max value then we need to bail since we can't be
3194 * sure we won't do bad things.
3195 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3196 */
b03c9f9f 3197 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3198 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3199 regno);
3200 return -EACCES;
3201 }
457f4436
AN
3202 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3203 mem_size, zero_size_allowed);
3204 if (err) {
3205 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3206 regno);
457f4436
AN
3207 return err;
3208 }
3209
3210 return 0;
3211}
d83525ca 3212
457f4436
AN
3213/* check read/write into a map element with possible variable offset */
3214static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3215 int off, int size, bool zero_size_allowed)
3216{
3217 struct bpf_verifier_state *vstate = env->cur_state;
3218 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3219 struct bpf_reg_state *reg = &state->regs[regno];
3220 struct bpf_map *map = reg->map_ptr;
3221 int err;
3222
3223 err = check_mem_region_access(env, regno, off, size, map->value_size,
3224 zero_size_allowed);
3225 if (err)
3226 return err;
3227
3228 if (map_value_has_spin_lock(map)) {
3229 u32 lock = map->spin_lock_off;
d83525ca
AS
3230
3231 /* if any part of struct bpf_spin_lock can be touched by
3232 * load/store reject this program.
3233 * To check that [x1, x2) overlaps with [y1, y2)
3234 * it is sufficient to check x1 < y2 && y1 < x2.
3235 */
3236 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3237 lock < reg->umax_value + off + size) {
3238 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3239 return -EACCES;
3240 }
3241 }
f1174f77 3242 return err;
dbcfe5f7
GB
3243}
3244
969bf05e
AS
3245#define MAX_PACKET_OFF 0xffff
3246
7e40781c
UP
3247static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3248{
3aac1ead 3249 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
3250}
3251
58e2af8b 3252static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3253 const struct bpf_call_arg_meta *meta,
3254 enum bpf_access_type t)
4acf6c0b 3255{
7e40781c
UP
3256 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3257
3258 switch (prog_type) {
5d66fa7d 3259 /* Program types only with direct read access go here! */
3a0af8fd
TG
3260 case BPF_PROG_TYPE_LWT_IN:
3261 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3262 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3263 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3264 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3265 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3266 if (t == BPF_WRITE)
3267 return false;
8731745e 3268 fallthrough;
5d66fa7d
DB
3269
3270 /* Program types with direct read + write access go here! */
36bbef52
DB
3271 case BPF_PROG_TYPE_SCHED_CLS:
3272 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3273 case BPF_PROG_TYPE_XDP:
3a0af8fd 3274 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3275 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3276 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3277 if (meta)
3278 return meta->pkt_access;
3279
3280 env->seen_direct_write = true;
4acf6c0b 3281 return true;
0d01da6a
SF
3282
3283 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3284 if (t == BPF_WRITE)
3285 env->seen_direct_write = true;
3286
3287 return true;
3288
4acf6c0b
BB
3289 default:
3290 return false;
3291 }
3292}
3293
f1174f77 3294static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3295 int size, bool zero_size_allowed)
f1174f77 3296{
638f5b90 3297 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3298 struct bpf_reg_state *reg = &regs[regno];
3299 int err;
3300
3301 /* We may have added a variable offset to the packet pointer; but any
3302 * reg->range we have comes after that. We are only checking the fixed
3303 * offset.
3304 */
3305
3306 /* We don't allow negative numbers, because we aren't tracking enough
3307 * detail to prove they're safe.
3308 */
b03c9f9f 3309 if (reg->smin_value < 0) {
61bd5218 3310 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3311 regno);
3312 return -EACCES;
3313 }
6d94e741
AS
3314
3315 err = reg->range < 0 ? -EINVAL :
3316 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3317 zero_size_allowed);
f1174f77 3318 if (err) {
61bd5218 3319 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3320 return err;
3321 }
e647815a 3322
457f4436 3323 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3324 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3325 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3326 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3327 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3328 */
3329 env->prog->aux->max_pkt_offset =
3330 max_t(u32, env->prog->aux->max_pkt_offset,
3331 off + reg->umax_value + size - 1);
3332
f1174f77
EC
3333 return err;
3334}
3335
3336/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3337static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3338 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3339 struct btf **btf, u32 *btf_id)
17a52670 3340{
f96da094
DB
3341 struct bpf_insn_access_aux info = {
3342 .reg_type = *reg_type,
9e15db66 3343 .log = &env->log,
f96da094 3344 };
31fd8581 3345
4f9218aa 3346 if (env->ops->is_valid_access &&
5e43f899 3347 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3348 /* A non zero info.ctx_field_size indicates that this field is a
3349 * candidate for later verifier transformation to load the whole
3350 * field and then apply a mask when accessed with a narrower
3351 * access than actual ctx access size. A zero info.ctx_field_size
3352 * will only allow for whole field access and rejects any other
3353 * type of narrower access.
31fd8581 3354 */
23994631 3355 *reg_type = info.reg_type;
31fd8581 3356
22dc4a0f
AN
3357 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3358 *btf = info.btf;
9e15db66 3359 *btf_id = info.btf_id;
22dc4a0f 3360 } else {
9e15db66 3361 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3362 }
32bbe007
AS
3363 /* remember the offset of last byte accessed in ctx */
3364 if (env->prog->aux->max_ctx_offset < off + size)
3365 env->prog->aux->max_ctx_offset = off + size;
17a52670 3366 return 0;
32bbe007 3367 }
17a52670 3368
61bd5218 3369 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3370 return -EACCES;
3371}
3372
d58e468b
PP
3373static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3374 int size)
3375{
3376 if (size < 0 || off < 0 ||
3377 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3378 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3379 off, size);
3380 return -EACCES;
3381 }
3382 return 0;
3383}
3384
5f456649
MKL
3385static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3386 u32 regno, int off, int size,
3387 enum bpf_access_type t)
c64b7983
JS
3388{
3389 struct bpf_reg_state *regs = cur_regs(env);
3390 struct bpf_reg_state *reg = &regs[regno];
5f456649 3391 struct bpf_insn_access_aux info = {};
46f8bc92 3392 bool valid;
c64b7983
JS
3393
3394 if (reg->smin_value < 0) {
3395 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3396 regno);
3397 return -EACCES;
3398 }
3399
46f8bc92
MKL
3400 switch (reg->type) {
3401 case PTR_TO_SOCK_COMMON:
3402 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3403 break;
3404 case PTR_TO_SOCKET:
3405 valid = bpf_sock_is_valid_access(off, size, t, &info);
3406 break;
655a51e5
MKL
3407 case PTR_TO_TCP_SOCK:
3408 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3409 break;
fada7fdc
JL
3410 case PTR_TO_XDP_SOCK:
3411 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3412 break;
46f8bc92
MKL
3413 default:
3414 valid = false;
c64b7983
JS
3415 }
3416
5f456649 3417
46f8bc92
MKL
3418 if (valid) {
3419 env->insn_aux_data[insn_idx].ctx_field_size =
3420 info.ctx_field_size;
3421 return 0;
3422 }
3423
3424 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3425 regno, reg_type_str[reg->type], off, size);
3426
3427 return -EACCES;
c64b7983
JS
3428}
3429
4cabc5b1
DB
3430static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3431{
2a159c6f 3432 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3433}
3434
f37a8cb8
DB
3435static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3436{
2a159c6f 3437 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3438
46f8bc92
MKL
3439 return reg->type == PTR_TO_CTX;
3440}
3441
3442static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3443{
3444 const struct bpf_reg_state *reg = reg_state(env, regno);
3445
3446 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3447}
3448
ca369602
DB
3449static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3450{
2a159c6f 3451 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3452
3453 return type_is_pkt_pointer(reg->type);
3454}
3455
4b5defde
DB
3456static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3457{
3458 const struct bpf_reg_state *reg = reg_state(env, regno);
3459
3460 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3461 return reg->type == PTR_TO_FLOW_KEYS;
3462}
3463
61bd5218
JK
3464static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3465 const struct bpf_reg_state *reg,
d1174416 3466 int off, int size, bool strict)
969bf05e 3467{
f1174f77 3468 struct tnum reg_off;
e07b98d9 3469 int ip_align;
d1174416
DM
3470
3471 /* Byte size accesses are always allowed. */
3472 if (!strict || size == 1)
3473 return 0;
3474
e4eda884
DM
3475 /* For platforms that do not have a Kconfig enabling
3476 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3477 * NET_IP_ALIGN is universally set to '2'. And on platforms
3478 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3479 * to this code only in strict mode where we want to emulate
3480 * the NET_IP_ALIGN==2 checking. Therefore use an
3481 * unconditional IP align value of '2'.
e07b98d9 3482 */
e4eda884 3483 ip_align = 2;
f1174f77
EC
3484
3485 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3486 if (!tnum_is_aligned(reg_off, size)) {
3487 char tn_buf[48];
3488
3489 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3490 verbose(env,
3491 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3492 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3493 return -EACCES;
3494 }
79adffcd 3495
969bf05e
AS
3496 return 0;
3497}
3498
61bd5218
JK
3499static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3500 const struct bpf_reg_state *reg,
f1174f77
EC
3501 const char *pointer_desc,
3502 int off, int size, bool strict)
79adffcd 3503{
f1174f77
EC
3504 struct tnum reg_off;
3505
3506 /* Byte size accesses are always allowed. */
3507 if (!strict || size == 1)
3508 return 0;
3509
3510 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3511 if (!tnum_is_aligned(reg_off, size)) {
3512 char tn_buf[48];
3513
3514 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3515 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3516 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3517 return -EACCES;
3518 }
3519
969bf05e
AS
3520 return 0;
3521}
3522
e07b98d9 3523static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3524 const struct bpf_reg_state *reg, int off,
3525 int size, bool strict_alignment_once)
79adffcd 3526{
ca369602 3527 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3528 const char *pointer_desc = "";
d1174416 3529
79adffcd
DB
3530 switch (reg->type) {
3531 case PTR_TO_PACKET:
de8f3a83
DB
3532 case PTR_TO_PACKET_META:
3533 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3534 * right in front, treat it the very same way.
3535 */
61bd5218 3536 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3537 case PTR_TO_FLOW_KEYS:
3538 pointer_desc = "flow keys ";
3539 break;
69c087ba
YS
3540 case PTR_TO_MAP_KEY:
3541 pointer_desc = "key ";
3542 break;
f1174f77
EC
3543 case PTR_TO_MAP_VALUE:
3544 pointer_desc = "value ";
3545 break;
3546 case PTR_TO_CTX:
3547 pointer_desc = "context ";
3548 break;
3549 case PTR_TO_STACK:
3550 pointer_desc = "stack ";
01f810ac
AM
3551 /* The stack spill tracking logic in check_stack_write_fixed_off()
3552 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3553 * aligned.
3554 */
3555 strict = true;
f1174f77 3556 break;
c64b7983
JS
3557 case PTR_TO_SOCKET:
3558 pointer_desc = "sock ";
3559 break;
46f8bc92
MKL
3560 case PTR_TO_SOCK_COMMON:
3561 pointer_desc = "sock_common ";
3562 break;
655a51e5
MKL
3563 case PTR_TO_TCP_SOCK:
3564 pointer_desc = "tcp_sock ";
3565 break;
fada7fdc
JL
3566 case PTR_TO_XDP_SOCK:
3567 pointer_desc = "xdp_sock ";
3568 break;
79adffcd 3569 default:
f1174f77 3570 break;
79adffcd 3571 }
61bd5218
JK
3572 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3573 strict);
79adffcd
DB
3574}
3575
f4d7e40a
AS
3576static int update_stack_depth(struct bpf_verifier_env *env,
3577 const struct bpf_func_state *func,
3578 int off)
3579{
9c8105bd 3580 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3581
3582 if (stack >= -off)
3583 return 0;
3584
3585 /* update known max for given subprogram */
9c8105bd 3586 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3587 return 0;
3588}
f4d7e40a 3589
70a87ffe
AS
3590/* starting from main bpf function walk all instructions of the function
3591 * and recursively walk all callees that given function can call.
3592 * Ignore jump and exit insns.
3593 * Since recursion is prevented by check_cfg() this algorithm
3594 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3595 */
3596static int check_max_stack_depth(struct bpf_verifier_env *env)
3597{
9c8105bd
JW
3598 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3599 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3600 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3601 bool tail_call_reachable = false;
70a87ffe
AS
3602 int ret_insn[MAX_CALL_FRAMES];
3603 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3604 int j;
f4d7e40a 3605
70a87ffe 3606process_func:
7f6e4312
MF
3607 /* protect against potential stack overflow that might happen when
3608 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3609 * depth for such case down to 256 so that the worst case scenario
3610 * would result in 8k stack size (32 which is tailcall limit * 256 =
3611 * 8k).
3612 *
3613 * To get the idea what might happen, see an example:
3614 * func1 -> sub rsp, 128
3615 * subfunc1 -> sub rsp, 256
3616 * tailcall1 -> add rsp, 256
3617 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3618 * subfunc2 -> sub rsp, 64
3619 * subfunc22 -> sub rsp, 128
3620 * tailcall2 -> add rsp, 128
3621 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3622 *
3623 * tailcall will unwind the current stack frame but it will not get rid
3624 * of caller's stack as shown on the example above.
3625 */
3626 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3627 verbose(env,
3628 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3629 depth);
3630 return -EACCES;
3631 }
70a87ffe
AS
3632 /* round up to 32-bytes, since this is granularity
3633 * of interpreter stack size
3634 */
9c8105bd 3635 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3636 if (depth > MAX_BPF_STACK) {
f4d7e40a 3637 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3638 frame + 1, depth);
f4d7e40a
AS
3639 return -EACCES;
3640 }
70a87ffe 3641continue_func:
4cb3d99c 3642 subprog_end = subprog[idx + 1].start;
70a87ffe 3643 for (; i < subprog_end; i++) {
69c087ba 3644 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3645 continue;
3646 /* remember insn and function to return to */
3647 ret_insn[frame] = i + 1;
9c8105bd 3648 ret_prog[frame] = idx;
70a87ffe
AS
3649
3650 /* find the callee */
3651 i = i + insn[i].imm + 1;
9c8105bd
JW
3652 idx = find_subprog(env, i);
3653 if (idx < 0) {
70a87ffe
AS
3654 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3655 i);
3656 return -EFAULT;
3657 }
ebf7d1f5
MF
3658
3659 if (subprog[idx].has_tail_call)
3660 tail_call_reachable = true;
3661
70a87ffe
AS
3662 frame++;
3663 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3664 verbose(env, "the call stack of %d frames is too deep !\n",
3665 frame);
3666 return -E2BIG;
70a87ffe
AS
3667 }
3668 goto process_func;
3669 }
ebf7d1f5
MF
3670 /* if tail call got detected across bpf2bpf calls then mark each of the
3671 * currently present subprog frames as tail call reachable subprogs;
3672 * this info will be utilized by JIT so that we will be preserving the
3673 * tail call counter throughout bpf2bpf calls combined with tailcalls
3674 */
3675 if (tail_call_reachable)
3676 for (j = 0; j < frame; j++)
3677 subprog[ret_prog[j]].tail_call_reachable = true;
3678
70a87ffe
AS
3679 /* end of for() loop means the last insn of the 'subprog'
3680 * was reached. Doesn't matter whether it was JA or EXIT
3681 */
3682 if (frame == 0)
3683 return 0;
9c8105bd 3684 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3685 frame--;
3686 i = ret_insn[frame];
9c8105bd 3687 idx = ret_prog[frame];
70a87ffe 3688 goto continue_func;
f4d7e40a
AS
3689}
3690
19d28fbd 3691#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3692static int get_callee_stack_depth(struct bpf_verifier_env *env,
3693 const struct bpf_insn *insn, int idx)
3694{
3695 int start = idx + insn->imm + 1, subprog;
3696
3697 subprog = find_subprog(env, start);
3698 if (subprog < 0) {
3699 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3700 start);
3701 return -EFAULT;
3702 }
9c8105bd 3703 return env->subprog_info[subprog].stack_depth;
1ea47e01 3704}
19d28fbd 3705#endif
1ea47e01 3706
51c39bb1
AS
3707int check_ctx_reg(struct bpf_verifier_env *env,
3708 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3709{
3710 /* Access to ctx or passing it to a helper is only allowed in
3711 * its original, unmodified form.
3712 */
3713
3714 if (reg->off) {
3715 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3716 regno, reg->off);
3717 return -EACCES;
3718 }
3719
3720 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3721 char tn_buf[48];
3722
3723 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3724 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3725 return -EACCES;
3726 }
3727
3728 return 0;
3729}
3730
afbf21dc
YS
3731static int __check_buffer_access(struct bpf_verifier_env *env,
3732 const char *buf_info,
3733 const struct bpf_reg_state *reg,
3734 int regno, int off, int size)
9df1c28b
MM
3735{
3736 if (off < 0) {
3737 verbose(env,
4fc00b79 3738 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3739 regno, buf_info, off, size);
9df1c28b
MM
3740 return -EACCES;
3741 }
3742 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3743 char tn_buf[48];
3744
3745 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3746 verbose(env,
4fc00b79 3747 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3748 regno, off, tn_buf);
3749 return -EACCES;
3750 }
afbf21dc
YS
3751
3752 return 0;
3753}
3754
3755static int check_tp_buffer_access(struct bpf_verifier_env *env,
3756 const struct bpf_reg_state *reg,
3757 int regno, int off, int size)
3758{
3759 int err;
3760
3761 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3762 if (err)
3763 return err;
3764
9df1c28b
MM
3765 if (off + size > env->prog->aux->max_tp_access)
3766 env->prog->aux->max_tp_access = off + size;
3767
3768 return 0;
3769}
3770
afbf21dc
YS
3771static int check_buffer_access(struct bpf_verifier_env *env,
3772 const struct bpf_reg_state *reg,
3773 int regno, int off, int size,
3774 bool zero_size_allowed,
3775 const char *buf_info,
3776 u32 *max_access)
3777{
3778 int err;
3779
3780 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3781 if (err)
3782 return err;
3783
3784 if (off + size > *max_access)
3785 *max_access = off + size;
3786
3787 return 0;
3788}
3789
3f50f132
JF
3790/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3791static void zext_32_to_64(struct bpf_reg_state *reg)
3792{
3793 reg->var_off = tnum_subreg(reg->var_off);
3794 __reg_assign_32_into_64(reg);
3795}
9df1c28b 3796
0c17d1d2
JH
3797/* truncate register to smaller size (in bytes)
3798 * must be called with size < BPF_REG_SIZE
3799 */
3800static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3801{
3802 u64 mask;
3803
3804 /* clear high bits in bit representation */
3805 reg->var_off = tnum_cast(reg->var_off, size);
3806
3807 /* fix arithmetic bounds */
3808 mask = ((u64)1 << (size * 8)) - 1;
3809 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3810 reg->umin_value &= mask;
3811 reg->umax_value &= mask;
3812 } else {
3813 reg->umin_value = 0;
3814 reg->umax_value = mask;
3815 }
3816 reg->smin_value = reg->umin_value;
3817 reg->smax_value = reg->umax_value;
3f50f132
JF
3818
3819 /* If size is smaller than 32bit register the 32bit register
3820 * values are also truncated so we push 64-bit bounds into
3821 * 32-bit bounds. Above were truncated < 32-bits already.
3822 */
3823 if (size >= 4)
3824 return;
3825 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3826}
3827
a23740ec
AN
3828static bool bpf_map_is_rdonly(const struct bpf_map *map)
3829{
3830 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3831}
3832
3833static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3834{
3835 void *ptr;
3836 u64 addr;
3837 int err;
3838
3839 err = map->ops->map_direct_value_addr(map, &addr, off);
3840 if (err)
3841 return err;
2dedd7d2 3842 ptr = (void *)(long)addr + off;
a23740ec
AN
3843
3844 switch (size) {
3845 case sizeof(u8):
3846 *val = (u64)*(u8 *)ptr;
3847 break;
3848 case sizeof(u16):
3849 *val = (u64)*(u16 *)ptr;
3850 break;
3851 case sizeof(u32):
3852 *val = (u64)*(u32 *)ptr;
3853 break;
3854 case sizeof(u64):
3855 *val = *(u64 *)ptr;
3856 break;
3857 default:
3858 return -EINVAL;
3859 }
3860 return 0;
3861}
3862
9e15db66
AS
3863static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3864 struct bpf_reg_state *regs,
3865 int regno, int off, int size,
3866 enum bpf_access_type atype,
3867 int value_regno)
3868{
3869 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3870 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3871 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3872 u32 btf_id;
3873 int ret;
3874
9e15db66
AS
3875 if (off < 0) {
3876 verbose(env,
3877 "R%d is ptr_%s invalid negative access: off=%d\n",
3878 regno, tname, off);
3879 return -EACCES;
3880 }
3881 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3882 char tn_buf[48];
3883
3884 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3885 verbose(env,
3886 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3887 regno, tname, off, tn_buf);
3888 return -EACCES;
3889 }
3890
27ae7997 3891 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3892 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3893 off, size, atype, &btf_id);
27ae7997
MKL
3894 } else {
3895 if (atype != BPF_READ) {
3896 verbose(env, "only read is supported\n");
3897 return -EACCES;
3898 }
3899
22dc4a0f
AN
3900 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3901 atype, &btf_id);
27ae7997
MKL
3902 }
3903
9e15db66
AS
3904 if (ret < 0)
3905 return ret;
3906
41c48f3a 3907 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3908 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3909
3910 return 0;
3911}
3912
3913static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3914 struct bpf_reg_state *regs,
3915 int regno, int off, int size,
3916 enum bpf_access_type atype,
3917 int value_regno)
3918{
3919 struct bpf_reg_state *reg = regs + regno;
3920 struct bpf_map *map = reg->map_ptr;
3921 const struct btf_type *t;
3922 const char *tname;
3923 u32 btf_id;
3924 int ret;
3925
3926 if (!btf_vmlinux) {
3927 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3928 return -ENOTSUPP;
3929 }
3930
3931 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3932 verbose(env, "map_ptr access not supported for map type %d\n",
3933 map->map_type);
3934 return -ENOTSUPP;
3935 }
3936
3937 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3938 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3939
3940 if (!env->allow_ptr_to_map_access) {
3941 verbose(env,
3942 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3943 tname);
3944 return -EPERM;
9e15db66 3945 }
27ae7997 3946
41c48f3a
AI
3947 if (off < 0) {
3948 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3949 regno, tname, off);
3950 return -EACCES;
3951 }
3952
3953 if (atype != BPF_READ) {
3954 verbose(env, "only read from %s is supported\n", tname);
3955 return -EACCES;
3956 }
3957
22dc4a0f 3958 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3959 if (ret < 0)
3960 return ret;
3961
3962 if (value_regno >= 0)
22dc4a0f 3963 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3964
9e15db66
AS
3965 return 0;
3966}
3967
01f810ac
AM
3968/* Check that the stack access at the given offset is within bounds. The
3969 * maximum valid offset is -1.
3970 *
3971 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3972 * -state->allocated_stack for reads.
3973 */
3974static int check_stack_slot_within_bounds(int off,
3975 struct bpf_func_state *state,
3976 enum bpf_access_type t)
3977{
3978 int min_valid_off;
3979
3980 if (t == BPF_WRITE)
3981 min_valid_off = -MAX_BPF_STACK;
3982 else
3983 min_valid_off = -state->allocated_stack;
3984
3985 if (off < min_valid_off || off > -1)
3986 return -EACCES;
3987 return 0;
3988}
3989
3990/* Check that the stack access at 'regno + off' falls within the maximum stack
3991 * bounds.
3992 *
3993 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3994 */
3995static int check_stack_access_within_bounds(
3996 struct bpf_verifier_env *env,
3997 int regno, int off, int access_size,
3998 enum stack_access_src src, enum bpf_access_type type)
3999{
4000 struct bpf_reg_state *regs = cur_regs(env);
4001 struct bpf_reg_state *reg = regs + regno;
4002 struct bpf_func_state *state = func(env, reg);
4003 int min_off, max_off;
4004 int err;
4005 char *err_extra;
4006
4007 if (src == ACCESS_HELPER)
4008 /* We don't know if helpers are reading or writing (or both). */
4009 err_extra = " indirect access to";
4010 else if (type == BPF_READ)
4011 err_extra = " read from";
4012 else
4013 err_extra = " write to";
4014
4015 if (tnum_is_const(reg->var_off)) {
4016 min_off = reg->var_off.value + off;
4017 if (access_size > 0)
4018 max_off = min_off + access_size - 1;
4019 else
4020 max_off = min_off;
4021 } else {
4022 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4023 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4024 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4025 err_extra, regno);
4026 return -EACCES;
4027 }
4028 min_off = reg->smin_value + off;
4029 if (access_size > 0)
4030 max_off = reg->smax_value + off + access_size - 1;
4031 else
4032 max_off = min_off;
4033 }
4034
4035 err = check_stack_slot_within_bounds(min_off, state, type);
4036 if (!err)
4037 err = check_stack_slot_within_bounds(max_off, state, type);
4038
4039 if (err) {
4040 if (tnum_is_const(reg->var_off)) {
4041 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4042 err_extra, regno, off, access_size);
4043 } else {
4044 char tn_buf[48];
4045
4046 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4047 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4048 err_extra, regno, tn_buf, access_size);
4049 }
4050 }
4051 return err;
4052}
41c48f3a 4053
17a52670
AS
4054/* check whether memory at (regno + off) is accessible for t = (read | write)
4055 * if t==write, value_regno is a register which value is stored into memory
4056 * if t==read, value_regno is a register which will receive the value from memory
4057 * if t==write && value_regno==-1, some unknown value is stored into memory
4058 * if t==read && value_regno==-1, don't care what we read from memory
4059 */
ca369602
DB
4060static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4061 int off, int bpf_size, enum bpf_access_type t,
4062 int value_regno, bool strict_alignment_once)
17a52670 4063{
638f5b90
AS
4064 struct bpf_reg_state *regs = cur_regs(env);
4065 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 4066 struct bpf_func_state *state;
17a52670
AS
4067 int size, err = 0;
4068
4069 size = bpf_size_to_bytes(bpf_size);
4070 if (size < 0)
4071 return size;
4072
f1174f77 4073 /* alignment checks will add in reg->off themselves */
ca369602 4074 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
4075 if (err)
4076 return err;
17a52670 4077
f1174f77
EC
4078 /* for access checks, reg->off is just part of off */
4079 off += reg->off;
4080
69c087ba
YS
4081 if (reg->type == PTR_TO_MAP_KEY) {
4082 if (t == BPF_WRITE) {
4083 verbose(env, "write to change key R%d not allowed\n", regno);
4084 return -EACCES;
4085 }
4086
4087 err = check_mem_region_access(env, regno, off, size,
4088 reg->map_ptr->key_size, false);
4089 if (err)
4090 return err;
4091 if (value_regno >= 0)
4092 mark_reg_unknown(env, regs, value_regno);
4093 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
4094 if (t == BPF_WRITE && value_regno >= 0 &&
4095 is_pointer_value(env, value_regno)) {
61bd5218 4096 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
4097 return -EACCES;
4098 }
591fe988
DB
4099 err = check_map_access_type(env, regno, off, size, t);
4100 if (err)
4101 return err;
9fd29c08 4102 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
4103 if (!err && t == BPF_READ && value_regno >= 0) {
4104 struct bpf_map *map = reg->map_ptr;
4105
4106 /* if map is read-only, track its contents as scalars */
4107 if (tnum_is_const(reg->var_off) &&
4108 bpf_map_is_rdonly(map) &&
4109 map->ops->map_direct_value_addr) {
4110 int map_off = off + reg->var_off.value;
4111 u64 val = 0;
4112
4113 err = bpf_map_direct_read(map, map_off, size,
4114 &val);
4115 if (err)
4116 return err;
4117
4118 regs[value_regno].type = SCALAR_VALUE;
4119 __mark_reg_known(&regs[value_regno], val);
4120 } else {
4121 mark_reg_unknown(env, regs, value_regno);
4122 }
4123 }
457f4436
AN
4124 } else if (reg->type == PTR_TO_MEM) {
4125 if (t == BPF_WRITE && value_regno >= 0 &&
4126 is_pointer_value(env, value_regno)) {
4127 verbose(env, "R%d leaks addr into mem\n", value_regno);
4128 return -EACCES;
4129 }
4130 err = check_mem_region_access(env, regno, off, size,
4131 reg->mem_size, false);
4132 if (!err && t == BPF_READ && value_regno >= 0)
4133 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 4134 } else if (reg->type == PTR_TO_CTX) {
f1174f77 4135 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 4136 struct btf *btf = NULL;
9e15db66 4137 u32 btf_id = 0;
19de99f7 4138
1be7f75d
AS
4139 if (t == BPF_WRITE && value_regno >= 0 &&
4140 is_pointer_value(env, value_regno)) {
61bd5218 4141 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
4142 return -EACCES;
4143 }
f1174f77 4144
58990d1f
DB
4145 err = check_ctx_reg(env, reg, regno);
4146 if (err < 0)
4147 return err;
4148
22dc4a0f 4149 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
4150 if (err)
4151 verbose_linfo(env, insn_idx, "; ");
969bf05e 4152 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 4153 /* ctx access returns either a scalar, or a
de8f3a83
DB
4154 * PTR_TO_PACKET[_META,_END]. In the latter
4155 * case, we know the offset is zero.
f1174f77 4156 */
46f8bc92 4157 if (reg_type == SCALAR_VALUE) {
638f5b90 4158 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4159 } else {
638f5b90 4160 mark_reg_known_zero(env, regs,
61bd5218 4161 value_regno);
46f8bc92
MKL
4162 if (reg_type_may_be_null(reg_type))
4163 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
4164 /* A load of ctx field could have different
4165 * actual load size with the one encoded in the
4166 * insn. When the dst is PTR, it is for sure not
4167 * a sub-register.
4168 */
4169 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 4170 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
4171 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4172 regs[value_regno].btf = btf;
9e15db66 4173 regs[value_regno].btf_id = btf_id;
22dc4a0f 4174 }
46f8bc92 4175 }
638f5b90 4176 regs[value_regno].type = reg_type;
969bf05e 4177 }
17a52670 4178
f1174f77 4179 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
4180 /* Basic bounds checks. */
4181 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
4182 if (err)
4183 return err;
8726679a 4184
f4d7e40a
AS
4185 state = func(env, reg);
4186 err = update_stack_depth(env, state, off);
4187 if (err)
4188 return err;
8726679a 4189
01f810ac
AM
4190 if (t == BPF_READ)
4191 err = check_stack_read(env, regno, off, size,
61bd5218 4192 value_regno);
01f810ac
AM
4193 else
4194 err = check_stack_write(env, regno, off, size,
4195 value_regno, insn_idx);
de8f3a83 4196 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 4197 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 4198 verbose(env, "cannot write into packet\n");
969bf05e
AS
4199 return -EACCES;
4200 }
4acf6c0b
BB
4201 if (t == BPF_WRITE && value_regno >= 0 &&
4202 is_pointer_value(env, value_regno)) {
61bd5218
JK
4203 verbose(env, "R%d leaks addr into packet\n",
4204 value_regno);
4acf6c0b
BB
4205 return -EACCES;
4206 }
9fd29c08 4207 err = check_packet_access(env, regno, off, size, false);
969bf05e 4208 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 4209 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
4210 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4211 if (t == BPF_WRITE && value_regno >= 0 &&
4212 is_pointer_value(env, value_regno)) {
4213 verbose(env, "R%d leaks addr into flow keys\n",
4214 value_regno);
4215 return -EACCES;
4216 }
4217
4218 err = check_flow_keys_access(env, off, size);
4219 if (!err && t == BPF_READ && value_regno >= 0)
4220 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4221 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4222 if (t == BPF_WRITE) {
46f8bc92
MKL
4223 verbose(env, "R%d cannot write into %s\n",
4224 regno, reg_type_str[reg->type]);
c64b7983
JS
4225 return -EACCES;
4226 }
5f456649 4227 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4228 if (!err && value_regno >= 0)
4229 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4230 } else if (reg->type == PTR_TO_TP_BUFFER) {
4231 err = check_tp_buffer_access(env, reg, regno, off, size);
4232 if (!err && t == BPF_READ && value_regno >= 0)
4233 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
4234 } else if (reg->type == PTR_TO_BTF_ID) {
4235 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4236 value_regno);
41c48f3a
AI
4237 } else if (reg->type == CONST_PTR_TO_MAP) {
4238 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4239 value_regno);
afbf21dc
YS
4240 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4241 if (t == BPF_WRITE) {
4242 verbose(env, "R%d cannot write into %s\n",
4243 regno, reg_type_str[reg->type]);
4244 return -EACCES;
4245 }
f6dfbe31
CIK
4246 err = check_buffer_access(env, reg, regno, off, size, false,
4247 "rdonly",
afbf21dc
YS
4248 &env->prog->aux->max_rdonly_access);
4249 if (!err && value_regno >= 0)
4250 mark_reg_unknown(env, regs, value_regno);
4251 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
4252 err = check_buffer_access(env, reg, regno, off, size, false,
4253 "rdwr",
afbf21dc
YS
4254 &env->prog->aux->max_rdwr_access);
4255 if (!err && t == BPF_READ && value_regno >= 0)
4256 mark_reg_unknown(env, regs, value_regno);
17a52670 4257 } else {
61bd5218
JK
4258 verbose(env, "R%d invalid mem access '%s'\n", regno,
4259 reg_type_str[reg->type]);
17a52670
AS
4260 return -EACCES;
4261 }
969bf05e 4262
f1174f77 4263 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4264 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4265 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4266 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4267 }
17a52670
AS
4268 return err;
4269}
4270
91c960b0 4271static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4272{
5ffa2550 4273 int load_reg;
17a52670
AS
4274 int err;
4275
5ca419f2
BJ
4276 switch (insn->imm) {
4277 case BPF_ADD:
4278 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4279 case BPF_AND:
4280 case BPF_AND | BPF_FETCH:
4281 case BPF_OR:
4282 case BPF_OR | BPF_FETCH:
4283 case BPF_XOR:
4284 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4285 case BPF_XCHG:
4286 case BPF_CMPXCHG:
5ca419f2
BJ
4287 break;
4288 default:
91c960b0
BJ
4289 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4290 return -EINVAL;
4291 }
4292
4293 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4294 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4295 return -EINVAL;
4296 }
4297
4298 /* check src1 operand */
dc503a8a 4299 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4300 if (err)
4301 return err;
4302
4303 /* check src2 operand */
dc503a8a 4304 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4305 if (err)
4306 return err;
4307
5ffa2550
BJ
4308 if (insn->imm == BPF_CMPXCHG) {
4309 /* Check comparison of R0 with memory location */
4310 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4311 if (err)
4312 return err;
4313 }
4314
6bdf6abc 4315 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4316 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4317 return -EACCES;
4318 }
4319
ca369602 4320 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4321 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4322 is_flow_key_reg(env, insn->dst_reg) ||
4323 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4324 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f
DB
4325 insn->dst_reg,
4326 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
4327 return -EACCES;
4328 }
4329
37086bfd
BJ
4330 if (insn->imm & BPF_FETCH) {
4331 if (insn->imm == BPF_CMPXCHG)
4332 load_reg = BPF_REG_0;
4333 else
4334 load_reg = insn->src_reg;
4335
4336 /* check and record load of old value */
4337 err = check_reg_arg(env, load_reg, DST_OP);
4338 if (err)
4339 return err;
4340 } else {
4341 /* This instruction accesses a memory location but doesn't
4342 * actually load it into a register.
4343 */
4344 load_reg = -1;
4345 }
4346
91c960b0 4347 /* check whether we can read the memory */
31fd8581 4348 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
37086bfd 4349 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
17a52670
AS
4350 if (err)
4351 return err;
4352
91c960b0 4353 /* check whether we can write into the same memory */
5ca419f2
BJ
4354 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4355 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4356 if (err)
4357 return err;
4358
5ca419f2 4359 return 0;
17a52670
AS
4360}
4361
01f810ac
AM
4362/* When register 'regno' is used to read the stack (either directly or through
4363 * a helper function) make sure that it's within stack boundary and, depending
4364 * on the access type, that all elements of the stack are initialized.
4365 *
4366 * 'off' includes 'regno->off', but not its dynamic part (if any).
4367 *
4368 * All registers that have been spilled on the stack in the slots within the
4369 * read offsets are marked as read.
4370 */
4371static int check_stack_range_initialized(
4372 struct bpf_verifier_env *env, int regno, int off,
4373 int access_size, bool zero_size_allowed,
4374 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4375{
4376 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4377 struct bpf_func_state *state = func(env, reg);
4378 int err, min_off, max_off, i, j, slot, spi;
4379 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4380 enum bpf_access_type bounds_check_type;
4381 /* Some accesses can write anything into the stack, others are
4382 * read-only.
4383 */
4384 bool clobber = false;
2011fccf 4385
01f810ac
AM
4386 if (access_size == 0 && !zero_size_allowed) {
4387 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4388 return -EACCES;
4389 }
2011fccf 4390
01f810ac
AM
4391 if (type == ACCESS_HELPER) {
4392 /* The bounds checks for writes are more permissive than for
4393 * reads. However, if raw_mode is not set, we'll do extra
4394 * checks below.
4395 */
4396 bounds_check_type = BPF_WRITE;
4397 clobber = true;
4398 } else {
4399 bounds_check_type = BPF_READ;
4400 }
4401 err = check_stack_access_within_bounds(env, regno, off, access_size,
4402 type, bounds_check_type);
4403 if (err)
4404 return err;
4405
17a52670 4406
2011fccf 4407 if (tnum_is_const(reg->var_off)) {
01f810ac 4408 min_off = max_off = reg->var_off.value + off;
2011fccf 4409 } else {
088ec26d
AI
4410 /* Variable offset is prohibited for unprivileged mode for
4411 * simplicity since it requires corresponding support in
4412 * Spectre masking for stack ALU.
4413 * See also retrieve_ptr_limit().
4414 */
2c78ee89 4415 if (!env->bypass_spec_v1) {
088ec26d 4416 char tn_buf[48];
f1174f77 4417
088ec26d 4418 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4419 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4420 regno, err_extra, tn_buf);
088ec26d
AI
4421 return -EACCES;
4422 }
f2bcd05e
AI
4423 /* Only initialized buffer on stack is allowed to be accessed
4424 * with variable offset. With uninitialized buffer it's hard to
4425 * guarantee that whole memory is marked as initialized on
4426 * helper return since specific bounds are unknown what may
4427 * cause uninitialized stack leaking.
4428 */
4429 if (meta && meta->raw_mode)
4430 meta = NULL;
4431
01f810ac
AM
4432 min_off = reg->smin_value + off;
4433 max_off = reg->smax_value + off;
17a52670
AS
4434 }
4435
435faee1
DB
4436 if (meta && meta->raw_mode) {
4437 meta->access_size = access_size;
4438 meta->regno = regno;
4439 return 0;
4440 }
4441
2011fccf 4442 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4443 u8 *stype;
4444
2011fccf 4445 slot = -i - 1;
638f5b90 4446 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4447 if (state->allocated_stack <= slot)
4448 goto err;
4449 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4450 if (*stype == STACK_MISC)
4451 goto mark;
4452 if (*stype == STACK_ZERO) {
01f810ac
AM
4453 if (clobber) {
4454 /* helper can write anything into the stack */
4455 *stype = STACK_MISC;
4456 }
cc2b14d5 4457 goto mark;
17a52670 4458 }
1d68f22b
YS
4459
4460 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4461 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4462 goto mark;
4463
f7cf25b2 4464 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4465 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4466 env->allow_ptr_leaks)) {
01f810ac
AM
4467 if (clobber) {
4468 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4469 for (j = 0; j < BPF_REG_SIZE; j++)
4470 state->stack[spi].slot_type[j] = STACK_MISC;
4471 }
f7cf25b2
AS
4472 goto mark;
4473 }
4474
cc2b14d5 4475err:
2011fccf 4476 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4477 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4478 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4479 } else {
4480 char tn_buf[48];
4481
4482 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4483 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4484 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4485 }
cc2b14d5
AS
4486 return -EACCES;
4487mark:
4488 /* reading any byte out of 8-byte 'spill_slot' will cause
4489 * the whole slot to be marked as 'read'
4490 */
679c782d 4491 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4492 state->stack[spi].spilled_ptr.parent,
4493 REG_LIVE_READ64);
17a52670 4494 }
2011fccf 4495 return update_stack_depth(env, state, min_off);
17a52670
AS
4496}
4497
06c1c049
GB
4498static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4499 int access_size, bool zero_size_allowed,
4500 struct bpf_call_arg_meta *meta)
4501{
638f5b90 4502 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4503
f1174f77 4504 switch (reg->type) {
06c1c049 4505 case PTR_TO_PACKET:
de8f3a83 4506 case PTR_TO_PACKET_META:
9fd29c08
YS
4507 return check_packet_access(env, regno, reg->off, access_size,
4508 zero_size_allowed);
69c087ba
YS
4509 case PTR_TO_MAP_KEY:
4510 return check_mem_region_access(env, regno, reg->off, access_size,
4511 reg->map_ptr->key_size, false);
06c1c049 4512 case PTR_TO_MAP_VALUE:
591fe988
DB
4513 if (check_map_access_type(env, regno, reg->off, access_size,
4514 meta && meta->raw_mode ? BPF_WRITE :
4515 BPF_READ))
4516 return -EACCES;
9fd29c08
YS
4517 return check_map_access(env, regno, reg->off, access_size,
4518 zero_size_allowed);
457f4436
AN
4519 case PTR_TO_MEM:
4520 return check_mem_region_access(env, regno, reg->off,
4521 access_size, reg->mem_size,
4522 zero_size_allowed);
afbf21dc
YS
4523 case PTR_TO_RDONLY_BUF:
4524 if (meta && meta->raw_mode)
4525 return -EACCES;
4526 return check_buffer_access(env, reg, regno, reg->off,
4527 access_size, zero_size_allowed,
4528 "rdonly",
4529 &env->prog->aux->max_rdonly_access);
4530 case PTR_TO_RDWR_BUF:
4531 return check_buffer_access(env, reg, regno, reg->off,
4532 access_size, zero_size_allowed,
4533 "rdwr",
4534 &env->prog->aux->max_rdwr_access);
0d004c02 4535 case PTR_TO_STACK:
01f810ac
AM
4536 return check_stack_range_initialized(
4537 env,
4538 regno, reg->off, access_size,
4539 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4540 default: /* scalar_value or invalid ptr */
4541 /* Allow zero-byte read from NULL, regardless of pointer type */
4542 if (zero_size_allowed && access_size == 0 &&
4543 register_is_null(reg))
4544 return 0;
4545
4546 verbose(env, "R%d type=%s expected=%s\n", regno,
4547 reg_type_str[reg->type],
4548 reg_type_str[PTR_TO_STACK]);
4549 return -EACCES;
06c1c049
GB
4550 }
4551}
4552
e5069b9c
DB
4553int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4554 u32 regno, u32 mem_size)
4555{
4556 if (register_is_null(reg))
4557 return 0;
4558
4559 if (reg_type_may_be_null(reg->type)) {
4560 /* Assuming that the register contains a value check if the memory
4561 * access is safe. Temporarily save and restore the register's state as
4562 * the conversion shouldn't be visible to a caller.
4563 */
4564 const struct bpf_reg_state saved_reg = *reg;
4565 int rv;
4566
4567 mark_ptr_not_null_reg(reg);
4568 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4569 *reg = saved_reg;
4570 return rv;
4571 }
4572
4573 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4574}
4575
d83525ca
AS
4576/* Implementation details:
4577 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4578 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4579 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4580 * value_or_null->value transition, since the verifier only cares about
4581 * the range of access to valid map value pointer and doesn't care about actual
4582 * address of the map element.
4583 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4584 * reg->id > 0 after value_or_null->value transition. By doing so
4585 * two bpf_map_lookups will be considered two different pointers that
4586 * point to different bpf_spin_locks.
4587 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4588 * dead-locks.
4589 * Since only one bpf_spin_lock is allowed the checks are simpler than
4590 * reg_is_refcounted() logic. The verifier needs to remember only
4591 * one spin_lock instead of array of acquired_refs.
4592 * cur_state->active_spin_lock remembers which map value element got locked
4593 * and clears it after bpf_spin_unlock.
4594 */
4595static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4596 bool is_lock)
4597{
4598 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4599 struct bpf_verifier_state *cur = env->cur_state;
4600 bool is_const = tnum_is_const(reg->var_off);
4601 struct bpf_map *map = reg->map_ptr;
4602 u64 val = reg->var_off.value;
4603
d83525ca
AS
4604 if (!is_const) {
4605 verbose(env,
4606 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4607 regno);
4608 return -EINVAL;
4609 }
4610 if (!map->btf) {
4611 verbose(env,
4612 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4613 map->name);
4614 return -EINVAL;
4615 }
4616 if (!map_value_has_spin_lock(map)) {
4617 if (map->spin_lock_off == -E2BIG)
4618 verbose(env,
4619 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4620 map->name);
4621 else if (map->spin_lock_off == -ENOENT)
4622 verbose(env,
4623 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4624 map->name);
4625 else
4626 verbose(env,
4627 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4628 map->name);
4629 return -EINVAL;
4630 }
4631 if (map->spin_lock_off != val + reg->off) {
4632 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4633 val + reg->off);
4634 return -EINVAL;
4635 }
4636 if (is_lock) {
4637 if (cur->active_spin_lock) {
4638 verbose(env,
4639 "Locking two bpf_spin_locks are not allowed\n");
4640 return -EINVAL;
4641 }
4642 cur->active_spin_lock = reg->id;
4643 } else {
4644 if (!cur->active_spin_lock) {
4645 verbose(env, "bpf_spin_unlock without taking a lock\n");
4646 return -EINVAL;
4647 }
4648 if (cur->active_spin_lock != reg->id) {
4649 verbose(env, "bpf_spin_unlock of different lock\n");
4650 return -EINVAL;
4651 }
4652 cur->active_spin_lock = 0;
4653 }
4654 return 0;
4655}
4656
90133415
DB
4657static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4658{
4659 return type == ARG_PTR_TO_MEM ||
4660 type == ARG_PTR_TO_MEM_OR_NULL ||
4661 type == ARG_PTR_TO_UNINIT_MEM;
4662}
4663
4664static bool arg_type_is_mem_size(enum bpf_arg_type type)
4665{
4666 return type == ARG_CONST_SIZE ||
4667 type == ARG_CONST_SIZE_OR_ZERO;
4668}
4669
457f4436
AN
4670static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4671{
4672 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4673}
4674
57c3bb72
AI
4675static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4676{
4677 return type == ARG_PTR_TO_INT ||
4678 type == ARG_PTR_TO_LONG;
4679}
4680
4681static int int_ptr_type_to_size(enum bpf_arg_type type)
4682{
4683 if (type == ARG_PTR_TO_INT)
4684 return sizeof(u32);
4685 else if (type == ARG_PTR_TO_LONG)
4686 return sizeof(u64);
4687
4688 return -EINVAL;
4689}
4690
912f442c
LB
4691static int resolve_map_arg_type(struct bpf_verifier_env *env,
4692 const struct bpf_call_arg_meta *meta,
4693 enum bpf_arg_type *arg_type)
4694{
4695 if (!meta->map_ptr) {
4696 /* kernel subsystem misconfigured verifier */
4697 verbose(env, "invalid map_ptr to access map->type\n");
4698 return -EACCES;
4699 }
4700
4701 switch (meta->map_ptr->map_type) {
4702 case BPF_MAP_TYPE_SOCKMAP:
4703 case BPF_MAP_TYPE_SOCKHASH:
4704 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4705 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4706 } else {
4707 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4708 return -EINVAL;
4709 }
4710 break;
4711
4712 default:
4713 break;
4714 }
4715 return 0;
4716}
4717
f79e7ea5
LB
4718struct bpf_reg_types {
4719 const enum bpf_reg_type types[10];
1df8f55a 4720 u32 *btf_id;
f79e7ea5
LB
4721};
4722
4723static const struct bpf_reg_types map_key_value_types = {
4724 .types = {
4725 PTR_TO_STACK,
4726 PTR_TO_PACKET,
4727 PTR_TO_PACKET_META,
69c087ba 4728 PTR_TO_MAP_KEY,
f79e7ea5
LB
4729 PTR_TO_MAP_VALUE,
4730 },
4731};
4732
4733static const struct bpf_reg_types sock_types = {
4734 .types = {
4735 PTR_TO_SOCK_COMMON,
4736 PTR_TO_SOCKET,
4737 PTR_TO_TCP_SOCK,
4738 PTR_TO_XDP_SOCK,
4739 },
4740};
4741
49a2a4d4 4742#ifdef CONFIG_NET
1df8f55a
MKL
4743static const struct bpf_reg_types btf_id_sock_common_types = {
4744 .types = {
4745 PTR_TO_SOCK_COMMON,
4746 PTR_TO_SOCKET,
4747 PTR_TO_TCP_SOCK,
4748 PTR_TO_XDP_SOCK,
4749 PTR_TO_BTF_ID,
4750 },
4751 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4752};
49a2a4d4 4753#endif
1df8f55a 4754
f79e7ea5
LB
4755static const struct bpf_reg_types mem_types = {
4756 .types = {
4757 PTR_TO_STACK,
4758 PTR_TO_PACKET,
4759 PTR_TO_PACKET_META,
69c087ba 4760 PTR_TO_MAP_KEY,
f79e7ea5
LB
4761 PTR_TO_MAP_VALUE,
4762 PTR_TO_MEM,
4763 PTR_TO_RDONLY_BUF,
4764 PTR_TO_RDWR_BUF,
4765 },
4766};
4767
4768static const struct bpf_reg_types int_ptr_types = {
4769 .types = {
4770 PTR_TO_STACK,
4771 PTR_TO_PACKET,
4772 PTR_TO_PACKET_META,
69c087ba 4773 PTR_TO_MAP_KEY,
f79e7ea5
LB
4774 PTR_TO_MAP_VALUE,
4775 },
4776};
4777
4778static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4779static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4780static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4781static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4782static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4783static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4784static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4785static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
69c087ba
YS
4786static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4787static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 4788static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
f79e7ea5 4789
0789e13b 4790static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4791 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4792 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4793 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4794 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4795 [ARG_CONST_SIZE] = &scalar_types,
4796 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4797 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4798 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4799 [ARG_PTR_TO_CTX] = &context_types,
4800 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4801 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4802#ifdef CONFIG_NET
1df8f55a 4803 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4804#endif
f79e7ea5
LB
4805 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4806 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4807 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4808 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4809 [ARG_PTR_TO_MEM] = &mem_types,
4810 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4811 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4812 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4813 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4814 [ARG_PTR_TO_INT] = &int_ptr_types,
4815 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4816 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba
YS
4817 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4818 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
fff13c4b 4819 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
f79e7ea5
LB
4820};
4821
4822static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4823 enum bpf_arg_type arg_type,
4824 const u32 *arg_btf_id)
f79e7ea5
LB
4825{
4826 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4827 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4828 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4829 int i, j;
4830
a968d5e2
MKL
4831 compatible = compatible_reg_types[arg_type];
4832 if (!compatible) {
4833 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4834 return -EFAULT;
4835 }
4836
f79e7ea5
LB
4837 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4838 expected = compatible->types[i];
4839 if (expected == NOT_INIT)
4840 break;
4841
4842 if (type == expected)
a968d5e2 4843 goto found;
f79e7ea5
LB
4844 }
4845
4846 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4847 for (j = 0; j + 1 < i; j++)
4848 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4849 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4850 return -EACCES;
a968d5e2
MKL
4851
4852found:
4853 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4854 if (!arg_btf_id) {
4855 if (!compatible->btf_id) {
4856 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4857 return -EFAULT;
4858 }
4859 arg_btf_id = compatible->btf_id;
4860 }
4861
22dc4a0f
AN
4862 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4863 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4864 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4865 regno, kernel_type_name(reg->btf, reg->btf_id),
4866 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4867 return -EACCES;
4868 }
4869
4870 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4871 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4872 regno);
4873 return -EACCES;
4874 }
4875 }
4876
4877 return 0;
f79e7ea5
LB
4878}
4879
af7ec138
YS
4880static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4881 struct bpf_call_arg_meta *meta,
4882 const struct bpf_func_proto *fn)
17a52670 4883{
af7ec138 4884 u32 regno = BPF_REG_1 + arg;
638f5b90 4885 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4886 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4887 enum bpf_reg_type type = reg->type;
17a52670
AS
4888 int err = 0;
4889
80f1d68c 4890 if (arg_type == ARG_DONTCARE)
17a52670
AS
4891 return 0;
4892
dc503a8a
EC
4893 err = check_reg_arg(env, regno, SRC_OP);
4894 if (err)
4895 return err;
17a52670 4896
1be7f75d
AS
4897 if (arg_type == ARG_ANYTHING) {
4898 if (is_pointer_value(env, regno)) {
61bd5218
JK
4899 verbose(env, "R%d leaks addr into helper function\n",
4900 regno);
1be7f75d
AS
4901 return -EACCES;
4902 }
80f1d68c 4903 return 0;
1be7f75d 4904 }
80f1d68c 4905
de8f3a83 4906 if (type_is_pkt_pointer(type) &&
3a0af8fd 4907 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4908 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4909 return -EACCES;
4910 }
4911
912f442c
LB
4912 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4913 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4914 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4915 err = resolve_map_arg_type(env, meta, &arg_type);
4916 if (err)
4917 return err;
4918 }
4919
fd1b0d60
LB
4920 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4921 /* A NULL register has a SCALAR_VALUE type, so skip
4922 * type checking.
4923 */
4924 goto skip_type_check;
4925
a968d5e2 4926 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4927 if (err)
4928 return err;
4929
a968d5e2 4930 if (type == PTR_TO_CTX) {
feec7040
LB
4931 err = check_ctx_reg(env, reg, regno);
4932 if (err < 0)
4933 return err;
d7b9454a
LB
4934 }
4935
fd1b0d60 4936skip_type_check:
02f7c958 4937 if (reg->ref_obj_id) {
457f4436
AN
4938 if (meta->ref_obj_id) {
4939 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4940 regno, reg->ref_obj_id,
4941 meta->ref_obj_id);
4942 return -EFAULT;
4943 }
4944 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4945 }
4946
17a52670
AS
4947 if (arg_type == ARG_CONST_MAP_PTR) {
4948 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4949 meta->map_ptr = reg->map_ptr;
17a52670
AS
4950 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4951 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4952 * check that [key, key + map->key_size) are within
4953 * stack limits and initialized
4954 */
33ff9823 4955 if (!meta->map_ptr) {
17a52670
AS
4956 /* in function declaration map_ptr must come before
4957 * map_key, so that it's verified and known before
4958 * we have to check map_key here. Otherwise it means
4959 * that kernel subsystem misconfigured verifier
4960 */
61bd5218 4961 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4962 return -EACCES;
4963 }
d71962f3
PC
4964 err = check_helper_mem_access(env, regno,
4965 meta->map_ptr->key_size, false,
4966 NULL);
2ea864c5 4967 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4968 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4969 !register_is_null(reg)) ||
2ea864c5 4970 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4971 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4972 * check [value, value + map->value_size) validity
4973 */
33ff9823 4974 if (!meta->map_ptr) {
17a52670 4975 /* kernel subsystem misconfigured verifier */
61bd5218 4976 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4977 return -EACCES;
4978 }
2ea864c5 4979 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4980 err = check_helper_mem_access(env, regno,
4981 meta->map_ptr->value_size, false,
2ea864c5 4982 meta);
eaa6bcb7
HL
4983 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4984 if (!reg->btf_id) {
4985 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4986 return -EACCES;
4987 }
22dc4a0f 4988 meta->ret_btf = reg->btf;
eaa6bcb7 4989 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4990 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4991 if (meta->func_id == BPF_FUNC_spin_lock) {
4992 if (process_spin_lock(env, regno, true))
4993 return -EACCES;
4994 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4995 if (process_spin_lock(env, regno, false))
4996 return -EACCES;
4997 } else {
4998 verbose(env, "verifier internal error\n");
4999 return -EFAULT;
5000 }
69c087ba
YS
5001 } else if (arg_type == ARG_PTR_TO_FUNC) {
5002 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
5003 } else if (arg_type_is_mem_ptr(arg_type)) {
5004 /* The access to this pointer is only checked when we hit the
5005 * next is_mem_size argument below.
5006 */
5007 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 5008 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 5009 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 5010
10060503
JF
5011 /* This is used to refine r0 return value bounds for helpers
5012 * that enforce this value as an upper bound on return values.
5013 * See do_refine_retval_range() for helpers that can refine
5014 * the return value. C type of helper is u32 so we pull register
5015 * bound from umax_value however, if negative verifier errors
5016 * out. Only upper bounds can be learned because retval is an
5017 * int type and negative retvals are allowed.
849fa506 5018 */
10060503 5019 meta->msize_max_value = reg->umax_value;
849fa506 5020
f1174f77
EC
5021 /* The register is SCALAR_VALUE; the access check
5022 * happens using its boundaries.
06c1c049 5023 */
f1174f77 5024 if (!tnum_is_const(reg->var_off))
06c1c049
GB
5025 /* For unprivileged variable accesses, disable raw
5026 * mode so that the program is required to
5027 * initialize all the memory that the helper could
5028 * just partially fill up.
5029 */
5030 meta = NULL;
5031
b03c9f9f 5032 if (reg->smin_value < 0) {
61bd5218 5033 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
5034 regno);
5035 return -EACCES;
5036 }
06c1c049 5037
b03c9f9f 5038 if (reg->umin_value == 0) {
f1174f77
EC
5039 err = check_helper_mem_access(env, regno - 1, 0,
5040 zero_size_allowed,
5041 meta);
06c1c049
GB
5042 if (err)
5043 return err;
06c1c049 5044 }
f1174f77 5045
b03c9f9f 5046 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 5047 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
5048 regno);
5049 return -EACCES;
5050 }
5051 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 5052 reg->umax_value,
f1174f77 5053 zero_size_allowed, meta);
b5dc0163
AS
5054 if (!err)
5055 err = mark_chain_precision(env, regno);
457f4436
AN
5056 } else if (arg_type_is_alloc_size(arg_type)) {
5057 if (!tnum_is_const(reg->var_off)) {
28a8add6 5058 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
5059 regno);
5060 return -EACCES;
5061 }
5062 meta->mem_size = reg->var_off.value;
57c3bb72
AI
5063 } else if (arg_type_is_int_ptr(arg_type)) {
5064 int size = int_ptr_type_to_size(arg_type);
5065
5066 err = check_helper_mem_access(env, regno, size, false, meta);
5067 if (err)
5068 return err;
5069 err = check_ptr_alignment(env, reg, 0, size, true);
fff13c4b
FR
5070 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5071 struct bpf_map *map = reg->map_ptr;
5072 int map_off;
5073 u64 map_addr;
5074 char *str_ptr;
5075
a8fad73e 5076 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
5077 verbose(env, "R%d does not point to a readonly map'\n", regno);
5078 return -EACCES;
5079 }
5080
5081 if (!tnum_is_const(reg->var_off)) {
5082 verbose(env, "R%d is not a constant address'\n", regno);
5083 return -EACCES;
5084 }
5085
5086 if (!map->ops->map_direct_value_addr) {
5087 verbose(env, "no direct value access support for this map type\n");
5088 return -EACCES;
5089 }
5090
5091 err = check_map_access(env, regno, reg->off,
5092 map->value_size - reg->off, false);
5093 if (err)
5094 return err;
5095
5096 map_off = reg->off + reg->var_off.value;
5097 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5098 if (err) {
5099 verbose(env, "direct value access on string failed\n");
5100 return err;
5101 }
5102
5103 str_ptr = (char *)(long)(map_addr);
5104 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5105 verbose(env, "string is not zero-terminated\n");
5106 return -EINVAL;
5107 }
17a52670
AS
5108 }
5109
5110 return err;
5111}
5112
0126240f
LB
5113static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5114{
5115 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 5116 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
5117
5118 if (func_id != BPF_FUNC_map_update_elem)
5119 return false;
5120
5121 /* It's not possible to get access to a locked struct sock in these
5122 * contexts, so updating is safe.
5123 */
5124 switch (type) {
5125 case BPF_PROG_TYPE_TRACING:
5126 if (eatype == BPF_TRACE_ITER)
5127 return true;
5128 break;
5129 case BPF_PROG_TYPE_SOCKET_FILTER:
5130 case BPF_PROG_TYPE_SCHED_CLS:
5131 case BPF_PROG_TYPE_SCHED_ACT:
5132 case BPF_PROG_TYPE_XDP:
5133 case BPF_PROG_TYPE_SK_REUSEPORT:
5134 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5135 case BPF_PROG_TYPE_SK_LOOKUP:
5136 return true;
5137 default:
5138 break;
5139 }
5140
5141 verbose(env, "cannot update sockmap in this context\n");
5142 return false;
5143}
5144
e411901c
MF
5145static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5146{
5147 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5148}
5149
61bd5218
JK
5150static int check_map_func_compatibility(struct bpf_verifier_env *env,
5151 struct bpf_map *map, int func_id)
35578d79 5152{
35578d79
KX
5153 if (!map)
5154 return 0;
5155
6aff67c8
AS
5156 /* We need a two way check, first is from map perspective ... */
5157 switch (map->map_type) {
5158 case BPF_MAP_TYPE_PROG_ARRAY:
5159 if (func_id != BPF_FUNC_tail_call)
5160 goto error;
5161 break;
5162 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5163 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 5164 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 5165 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
5166 func_id != BPF_FUNC_perf_event_read_value &&
5167 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
5168 goto error;
5169 break;
457f4436
AN
5170 case BPF_MAP_TYPE_RINGBUF:
5171 if (func_id != BPF_FUNC_ringbuf_output &&
5172 func_id != BPF_FUNC_ringbuf_reserve &&
5173 func_id != BPF_FUNC_ringbuf_submit &&
5174 func_id != BPF_FUNC_ringbuf_discard &&
5175 func_id != BPF_FUNC_ringbuf_query)
5176 goto error;
5177 break;
6aff67c8
AS
5178 case BPF_MAP_TYPE_STACK_TRACE:
5179 if (func_id != BPF_FUNC_get_stackid)
5180 goto error;
5181 break;
4ed8ec52 5182 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 5183 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 5184 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
5185 goto error;
5186 break;
cd339431 5187 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 5188 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
5189 if (func_id != BPF_FUNC_get_local_storage)
5190 goto error;
5191 break;
546ac1ff 5192 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 5193 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
5194 if (func_id != BPF_FUNC_redirect_map &&
5195 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
5196 goto error;
5197 break;
fbfc504a
BT
5198 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5199 * appear.
5200 */
6710e112
JDB
5201 case BPF_MAP_TYPE_CPUMAP:
5202 if (func_id != BPF_FUNC_redirect_map)
5203 goto error;
5204 break;
fada7fdc
JL
5205 case BPF_MAP_TYPE_XSKMAP:
5206 if (func_id != BPF_FUNC_redirect_map &&
5207 func_id != BPF_FUNC_map_lookup_elem)
5208 goto error;
5209 break;
56f668df 5210 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 5211 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
5212 if (func_id != BPF_FUNC_map_lookup_elem)
5213 goto error;
16a43625 5214 break;
174a79ff
JF
5215 case BPF_MAP_TYPE_SOCKMAP:
5216 if (func_id != BPF_FUNC_sk_redirect_map &&
5217 func_id != BPF_FUNC_sock_map_update &&
4f738adb 5218 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5219 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 5220 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5221 func_id != BPF_FUNC_map_lookup_elem &&
5222 !may_update_sockmap(env, func_id))
174a79ff
JF
5223 goto error;
5224 break;
81110384
JF
5225 case BPF_MAP_TYPE_SOCKHASH:
5226 if (func_id != BPF_FUNC_sk_redirect_hash &&
5227 func_id != BPF_FUNC_sock_hash_update &&
5228 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5229 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 5230 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5231 func_id != BPF_FUNC_map_lookup_elem &&
5232 !may_update_sockmap(env, func_id))
81110384
JF
5233 goto error;
5234 break;
2dbb9b9e
MKL
5235 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5236 if (func_id != BPF_FUNC_sk_select_reuseport)
5237 goto error;
5238 break;
f1a2e44a
MV
5239 case BPF_MAP_TYPE_QUEUE:
5240 case BPF_MAP_TYPE_STACK:
5241 if (func_id != BPF_FUNC_map_peek_elem &&
5242 func_id != BPF_FUNC_map_pop_elem &&
5243 func_id != BPF_FUNC_map_push_elem)
5244 goto error;
5245 break;
6ac99e8f
MKL
5246 case BPF_MAP_TYPE_SK_STORAGE:
5247 if (func_id != BPF_FUNC_sk_storage_get &&
5248 func_id != BPF_FUNC_sk_storage_delete)
5249 goto error;
5250 break;
8ea63684
KS
5251 case BPF_MAP_TYPE_INODE_STORAGE:
5252 if (func_id != BPF_FUNC_inode_storage_get &&
5253 func_id != BPF_FUNC_inode_storage_delete)
5254 goto error;
5255 break;
4cf1bc1f
KS
5256 case BPF_MAP_TYPE_TASK_STORAGE:
5257 if (func_id != BPF_FUNC_task_storage_get &&
5258 func_id != BPF_FUNC_task_storage_delete)
5259 goto error;
5260 break;
6aff67c8
AS
5261 default:
5262 break;
5263 }
5264
5265 /* ... and second from the function itself. */
5266 switch (func_id) {
5267 case BPF_FUNC_tail_call:
5268 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5269 goto error;
e411901c
MF
5270 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5271 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5272 return -EINVAL;
5273 }
6aff67c8
AS
5274 break;
5275 case BPF_FUNC_perf_event_read:
5276 case BPF_FUNC_perf_event_output:
908432ca 5277 case BPF_FUNC_perf_event_read_value:
a7658e1a 5278 case BPF_FUNC_skb_output:
d831ee84 5279 case BPF_FUNC_xdp_output:
6aff67c8
AS
5280 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5281 goto error;
5282 break;
5283 case BPF_FUNC_get_stackid:
5284 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5285 goto error;
5286 break;
60d20f91 5287 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5288 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5289 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5290 goto error;
5291 break;
97f91a7c 5292 case BPF_FUNC_redirect_map:
9c270af3 5293 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5294 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5295 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5296 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5297 goto error;
5298 break;
174a79ff 5299 case BPF_FUNC_sk_redirect_map:
4f738adb 5300 case BPF_FUNC_msg_redirect_map:
81110384 5301 case BPF_FUNC_sock_map_update:
174a79ff
JF
5302 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5303 goto error;
5304 break;
81110384
JF
5305 case BPF_FUNC_sk_redirect_hash:
5306 case BPF_FUNC_msg_redirect_hash:
5307 case BPF_FUNC_sock_hash_update:
5308 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5309 goto error;
5310 break;
cd339431 5311 case BPF_FUNC_get_local_storage:
b741f163
RG
5312 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5313 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5314 goto error;
5315 break;
2dbb9b9e 5316 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5317 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5318 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5319 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5320 goto error;
5321 break;
f1a2e44a
MV
5322 case BPF_FUNC_map_peek_elem:
5323 case BPF_FUNC_map_pop_elem:
5324 case BPF_FUNC_map_push_elem:
5325 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5326 map->map_type != BPF_MAP_TYPE_STACK)
5327 goto error;
5328 break;
6ac99e8f
MKL
5329 case BPF_FUNC_sk_storage_get:
5330 case BPF_FUNC_sk_storage_delete:
5331 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5332 goto error;
5333 break;
8ea63684
KS
5334 case BPF_FUNC_inode_storage_get:
5335 case BPF_FUNC_inode_storage_delete:
5336 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5337 goto error;
5338 break;
4cf1bc1f
KS
5339 case BPF_FUNC_task_storage_get:
5340 case BPF_FUNC_task_storage_delete:
5341 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5342 goto error;
5343 break;
6aff67c8
AS
5344 default:
5345 break;
35578d79
KX
5346 }
5347
5348 return 0;
6aff67c8 5349error:
61bd5218 5350 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5351 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5352 return -EINVAL;
35578d79
KX
5353}
5354
90133415 5355static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5356{
5357 int count = 0;
5358
39f19ebb 5359 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5360 count++;
39f19ebb 5361 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5362 count++;
39f19ebb 5363 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5364 count++;
39f19ebb 5365 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5366 count++;
39f19ebb 5367 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5368 count++;
5369
90133415
DB
5370 /* We only support one arg being in raw mode at the moment,
5371 * which is sufficient for the helper functions we have
5372 * right now.
5373 */
5374 return count <= 1;
5375}
5376
5377static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5378 enum bpf_arg_type arg_next)
5379{
5380 return (arg_type_is_mem_ptr(arg_curr) &&
5381 !arg_type_is_mem_size(arg_next)) ||
5382 (!arg_type_is_mem_ptr(arg_curr) &&
5383 arg_type_is_mem_size(arg_next));
5384}
5385
5386static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5387{
5388 /* bpf_xxx(..., buf, len) call will access 'len'
5389 * bytes from memory 'buf'. Both arg types need
5390 * to be paired, so make sure there's no buggy
5391 * helper function specification.
5392 */
5393 if (arg_type_is_mem_size(fn->arg1_type) ||
5394 arg_type_is_mem_ptr(fn->arg5_type) ||
5395 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5396 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5397 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5398 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5399 return false;
5400
5401 return true;
5402}
5403
1b986589 5404static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5405{
5406 int count = 0;
5407
1b986589 5408 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5409 count++;
1b986589 5410 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5411 count++;
1b986589 5412 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5413 count++;
1b986589 5414 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5415 count++;
1b986589 5416 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5417 count++;
5418
1b986589
MKL
5419 /* A reference acquiring function cannot acquire
5420 * another refcounted ptr.
5421 */
64d85290 5422 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5423 return false;
5424
fd978bf7
JS
5425 /* We only support one arg being unreferenced at the moment,
5426 * which is sufficient for the helper functions we have right now.
5427 */
5428 return count <= 1;
5429}
5430
9436ef6e
LB
5431static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5432{
5433 int i;
5434
1df8f55a 5435 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5436 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5437 return false;
5438
1df8f55a
MKL
5439 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5440 return false;
5441 }
5442
9436ef6e
LB
5443 return true;
5444}
5445
1b986589 5446static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5447{
5448 return check_raw_mode_ok(fn) &&
fd978bf7 5449 check_arg_pair_ok(fn) &&
9436ef6e 5450 check_btf_id_ok(fn) &&
1b986589 5451 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5452}
5453
de8f3a83
DB
5454/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5455 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5456 */
f4d7e40a
AS
5457static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5458 struct bpf_func_state *state)
969bf05e 5459{
58e2af8b 5460 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5461 int i;
5462
5463 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5464 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5465 mark_reg_unknown(env, regs, i);
969bf05e 5466
f3709f69
JS
5467 bpf_for_each_spilled_reg(i, state, reg) {
5468 if (!reg)
969bf05e 5469 continue;
de8f3a83 5470 if (reg_is_pkt_pointer_any(reg))
f54c7898 5471 __mark_reg_unknown(env, reg);
969bf05e
AS
5472 }
5473}
5474
f4d7e40a
AS
5475static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5476{
5477 struct bpf_verifier_state *vstate = env->cur_state;
5478 int i;
5479
5480 for (i = 0; i <= vstate->curframe; i++)
5481 __clear_all_pkt_pointers(env, vstate->frame[i]);
5482}
5483
6d94e741
AS
5484enum {
5485 AT_PKT_END = -1,
5486 BEYOND_PKT_END = -2,
5487};
5488
5489static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5490{
5491 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5492 struct bpf_reg_state *reg = &state->regs[regn];
5493
5494 if (reg->type != PTR_TO_PACKET)
5495 /* PTR_TO_PACKET_META is not supported yet */
5496 return;
5497
5498 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5499 * How far beyond pkt_end it goes is unknown.
5500 * if (!range_open) it's the case of pkt >= pkt_end
5501 * if (range_open) it's the case of pkt > pkt_end
5502 * hence this pointer is at least 1 byte bigger than pkt_end
5503 */
5504 if (range_open)
5505 reg->range = BEYOND_PKT_END;
5506 else
5507 reg->range = AT_PKT_END;
5508}
5509
fd978bf7 5510static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5511 struct bpf_func_state *state,
5512 int ref_obj_id)
fd978bf7
JS
5513{
5514 struct bpf_reg_state *regs = state->regs, *reg;
5515 int i;
5516
5517 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5518 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5519 mark_reg_unknown(env, regs, i);
5520
5521 bpf_for_each_spilled_reg(i, state, reg) {
5522 if (!reg)
5523 continue;
1b986589 5524 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5525 __mark_reg_unknown(env, reg);
fd978bf7
JS
5526 }
5527}
5528
5529/* The pointer with the specified id has released its reference to kernel
5530 * resources. Identify all copies of the same pointer and clear the reference.
5531 */
5532static int release_reference(struct bpf_verifier_env *env,
1b986589 5533 int ref_obj_id)
fd978bf7
JS
5534{
5535 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5536 int err;
fd978bf7
JS
5537 int i;
5538
1b986589
MKL
5539 err = release_reference_state(cur_func(env), ref_obj_id);
5540 if (err)
5541 return err;
5542
fd978bf7 5543 for (i = 0; i <= vstate->curframe; i++)
1b986589 5544 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5545
1b986589 5546 return 0;
fd978bf7
JS
5547}
5548
51c39bb1
AS
5549static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5550 struct bpf_reg_state *regs)
5551{
5552 int i;
5553
5554 /* after the call registers r0 - r5 were scratched */
5555 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5556 mark_reg_not_init(env, regs, caller_saved[i]);
5557 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5558 }
5559}
5560
14351375
YS
5561typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5562 struct bpf_func_state *caller,
5563 struct bpf_func_state *callee,
5564 int insn_idx);
5565
5566static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5567 int *insn_idx, int subprog,
5568 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
5569{
5570 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5571 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5572 struct bpf_func_state *caller, *callee;
14351375 5573 int err;
51c39bb1 5574 bool is_global = false;
f4d7e40a 5575
aada9ce6 5576 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5577 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5578 state->curframe + 2);
f4d7e40a
AS
5579 return -E2BIG;
5580 }
5581
f4d7e40a
AS
5582 caller = state->frame[state->curframe];
5583 if (state->frame[state->curframe + 1]) {
5584 verbose(env, "verifier bug. Frame %d already allocated\n",
5585 state->curframe + 1);
5586 return -EFAULT;
5587 }
5588
51c39bb1
AS
5589 func_info_aux = env->prog->aux->func_info_aux;
5590 if (func_info_aux)
5591 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
34747c41 5592 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
51c39bb1
AS
5593 if (err == -EFAULT)
5594 return err;
5595 if (is_global) {
5596 if (err) {
5597 verbose(env, "Caller passes invalid args into func#%d\n",
5598 subprog);
5599 return err;
5600 } else {
5601 if (env->log.level & BPF_LOG_LEVEL)
5602 verbose(env,
5603 "Func#%d is global and valid. Skipping.\n",
5604 subprog);
5605 clear_caller_saved_regs(env, caller->regs);
5606
45159b27 5607 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5608 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 5609 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5610
5611 /* continue with next insn after call */
5612 return 0;
5613 }
5614 }
5615
f4d7e40a
AS
5616 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5617 if (!callee)
5618 return -ENOMEM;
5619 state->frame[state->curframe + 1] = callee;
5620
5621 /* callee cannot access r0, r6 - r9 for reading and has to write
5622 * into its own stack before reading from it.
5623 * callee can read/write into caller's stack
5624 */
5625 init_func_state(env, callee,
5626 /* remember the callsite, it will be used by bpf_exit */
5627 *insn_idx /* callsite */,
5628 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5629 subprog /* subprog number within this prog */);
f4d7e40a 5630
fd978bf7
JS
5631 /* Transfer references to the callee */
5632 err = transfer_reference_state(callee, caller);
5633 if (err)
5634 return err;
5635
14351375
YS
5636 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5637 if (err)
5638 return err;
f4d7e40a 5639
51c39bb1 5640 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5641
5642 /* only increment it after check_reg_arg() finished */
5643 state->curframe++;
5644
5645 /* and go analyze first insn of the callee */
14351375 5646 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 5647
06ee7115 5648 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5649 verbose(env, "caller:\n");
5650 print_verifier_state(env, caller);
5651 verbose(env, "callee:\n");
5652 print_verifier_state(env, callee);
5653 }
5654 return 0;
5655}
5656
314ee05e
YS
5657int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5658 struct bpf_func_state *caller,
5659 struct bpf_func_state *callee)
5660{
5661 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5662 * void *callback_ctx, u64 flags);
5663 * callback_fn(struct bpf_map *map, void *key, void *value,
5664 * void *callback_ctx);
5665 */
5666 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5667
5668 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5669 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5670 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5671
5672 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5673 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5674 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5675
5676 /* pointer to stack or null */
5677 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5678
5679 /* unused */
5680 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5681 return 0;
5682}
5683
14351375
YS
5684static int set_callee_state(struct bpf_verifier_env *env,
5685 struct bpf_func_state *caller,
5686 struct bpf_func_state *callee, int insn_idx)
5687{
5688 int i;
5689
5690 /* copy r1 - r5 args that callee can access. The copy includes parent
5691 * pointers, which connects us up to the liveness chain
5692 */
5693 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5694 callee->regs[i] = caller->regs[i];
5695 return 0;
5696}
5697
5698static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5699 int *insn_idx)
5700{
5701 int subprog, target_insn;
5702
5703 target_insn = *insn_idx + insn->imm + 1;
5704 subprog = find_subprog(env, target_insn);
5705 if (subprog < 0) {
5706 verbose(env, "verifier bug. No program starts at insn %d\n",
5707 target_insn);
5708 return -EFAULT;
5709 }
5710
5711 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5712}
5713
69c087ba
YS
5714static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5715 struct bpf_func_state *caller,
5716 struct bpf_func_state *callee,
5717 int insn_idx)
5718{
5719 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5720 struct bpf_map *map;
5721 int err;
5722
5723 if (bpf_map_ptr_poisoned(insn_aux)) {
5724 verbose(env, "tail_call abusing map_ptr\n");
5725 return -EINVAL;
5726 }
5727
5728 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5729 if (!map->ops->map_set_for_each_callback_args ||
5730 !map->ops->map_for_each_callback) {
5731 verbose(env, "callback function not allowed for map\n");
5732 return -ENOTSUPP;
5733 }
5734
5735 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5736 if (err)
5737 return err;
5738
5739 callee->in_callback_fn = true;
5740 return 0;
5741}
5742
f4d7e40a
AS
5743static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5744{
5745 struct bpf_verifier_state *state = env->cur_state;
5746 struct bpf_func_state *caller, *callee;
5747 struct bpf_reg_state *r0;
fd978bf7 5748 int err;
f4d7e40a
AS
5749
5750 callee = state->frame[state->curframe];
5751 r0 = &callee->regs[BPF_REG_0];
5752 if (r0->type == PTR_TO_STACK) {
5753 /* technically it's ok to return caller's stack pointer
5754 * (or caller's caller's pointer) back to the caller,
5755 * since these pointers are valid. Only current stack
5756 * pointer will be invalid as soon as function exits,
5757 * but let's be conservative
5758 */
5759 verbose(env, "cannot return stack pointer to the caller\n");
5760 return -EINVAL;
5761 }
5762
5763 state->curframe--;
5764 caller = state->frame[state->curframe];
69c087ba
YS
5765 if (callee->in_callback_fn) {
5766 /* enforce R0 return value range [0, 1]. */
5767 struct tnum range = tnum_range(0, 1);
5768
5769 if (r0->type != SCALAR_VALUE) {
5770 verbose(env, "R0 not a scalar value\n");
5771 return -EACCES;
5772 }
5773 if (!tnum_in(range, r0->var_off)) {
5774 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5775 return -EINVAL;
5776 }
5777 } else {
5778 /* return to the caller whatever r0 had in the callee */
5779 caller->regs[BPF_REG_0] = *r0;
5780 }
f4d7e40a 5781
fd978bf7
JS
5782 /* Transfer references to the caller */
5783 err = transfer_reference_state(caller, callee);
5784 if (err)
5785 return err;
5786
f4d7e40a 5787 *insn_idx = callee->callsite + 1;
06ee7115 5788 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5789 verbose(env, "returning from callee:\n");
5790 print_verifier_state(env, callee);
5791 verbose(env, "to caller at %d:\n", *insn_idx);
5792 print_verifier_state(env, caller);
5793 }
5794 /* clear everything in the callee */
5795 free_func_state(callee);
5796 state->frame[state->curframe + 1] = NULL;
5797 return 0;
5798}
5799
849fa506
YS
5800static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5801 int func_id,
5802 struct bpf_call_arg_meta *meta)
5803{
5804 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5805
5806 if (ret_type != RET_INTEGER ||
5807 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 5808 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
5809 func_id != BPF_FUNC_probe_read_str &&
5810 func_id != BPF_FUNC_probe_read_kernel_str &&
5811 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5812 return;
5813
10060503 5814 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5815 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5816 ret_reg->smin_value = -MAX_ERRNO;
5817 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5818 __reg_deduce_bounds(ret_reg);
5819 __reg_bound_offset(ret_reg);
10060503 5820 __update_reg_bounds(ret_reg);
849fa506
YS
5821}
5822
c93552c4
DB
5823static int
5824record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5825 int func_id, int insn_idx)
5826{
5827 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5828 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5829
5830 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5831 func_id != BPF_FUNC_map_lookup_elem &&
5832 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5833 func_id != BPF_FUNC_map_delete_elem &&
5834 func_id != BPF_FUNC_map_push_elem &&
5835 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 5836 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f
BT
5837 func_id != BPF_FUNC_for_each_map_elem &&
5838 func_id != BPF_FUNC_redirect_map)
c93552c4 5839 return 0;
09772d92 5840
591fe988 5841 if (map == NULL) {
c93552c4
DB
5842 verbose(env, "kernel subsystem misconfigured verifier\n");
5843 return -EINVAL;
5844 }
5845
591fe988
DB
5846 /* In case of read-only, some additional restrictions
5847 * need to be applied in order to prevent altering the
5848 * state of the map from program side.
5849 */
5850 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5851 (func_id == BPF_FUNC_map_delete_elem ||
5852 func_id == BPF_FUNC_map_update_elem ||
5853 func_id == BPF_FUNC_map_push_elem ||
5854 func_id == BPF_FUNC_map_pop_elem)) {
5855 verbose(env, "write into map forbidden\n");
5856 return -EACCES;
5857 }
5858
d2e4c1e6 5859 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5860 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5861 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5862 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5863 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5864 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5865 return 0;
5866}
5867
d2e4c1e6
DB
5868static int
5869record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5870 int func_id, int insn_idx)
5871{
5872 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5873 struct bpf_reg_state *regs = cur_regs(env), *reg;
5874 struct bpf_map *map = meta->map_ptr;
5875 struct tnum range;
5876 u64 val;
cc52d914 5877 int err;
d2e4c1e6
DB
5878
5879 if (func_id != BPF_FUNC_tail_call)
5880 return 0;
5881 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5882 verbose(env, "kernel subsystem misconfigured verifier\n");
5883 return -EINVAL;
5884 }
5885
5886 range = tnum_range(0, map->max_entries - 1);
5887 reg = &regs[BPF_REG_3];
5888
5889 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5890 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5891 return 0;
5892 }
5893
cc52d914
DB
5894 err = mark_chain_precision(env, BPF_REG_3);
5895 if (err)
5896 return err;
5897
d2e4c1e6
DB
5898 val = reg->var_off.value;
5899 if (bpf_map_key_unseen(aux))
5900 bpf_map_key_store(aux, val);
5901 else if (!bpf_map_key_poisoned(aux) &&
5902 bpf_map_key_immediate(aux) != val)
5903 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5904 return 0;
5905}
5906
fd978bf7
JS
5907static int check_reference_leak(struct bpf_verifier_env *env)
5908{
5909 struct bpf_func_state *state = cur_func(env);
5910 int i;
5911
5912 for (i = 0; i < state->acquired_refs; i++) {
5913 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5914 state->refs[i].id, state->refs[i].insn_idx);
5915 }
5916 return state->acquired_refs ? -EINVAL : 0;
5917}
5918
7b15523a
FR
5919static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5920 struct bpf_reg_state *regs)
5921{
5922 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5923 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5924 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5925 int err, fmt_map_off, num_args;
5926 u64 fmt_addr;
5927 char *fmt;
5928
5929 /* data must be an array of u64 */
5930 if (data_len_reg->var_off.value % 8)
5931 return -EINVAL;
5932 num_args = data_len_reg->var_off.value / 8;
5933
5934 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5935 * and map_direct_value_addr is set.
5936 */
5937 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5938 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5939 fmt_map_off);
8e8ee109
FR
5940 if (err) {
5941 verbose(env, "verifier bug\n");
5942 return -EFAULT;
5943 }
7b15523a
FR
5944 fmt = (char *)(long)fmt_addr + fmt_map_off;
5945
5946 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5947 * can focus on validating the format specifiers.
5948 */
48cac3f4 5949 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7b15523a
FR
5950 if (err < 0)
5951 verbose(env, "Invalid format string\n");
5952
5953 return err;
5954}
5955
69c087ba
YS
5956static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5957 int *insn_idx_p)
17a52670 5958{
17a52670 5959 const struct bpf_func_proto *fn = NULL;
638f5b90 5960 struct bpf_reg_state *regs;
33ff9823 5961 struct bpf_call_arg_meta meta;
69c087ba 5962 int insn_idx = *insn_idx_p;
969bf05e 5963 bool changes_data;
69c087ba 5964 int i, err, func_id;
17a52670
AS
5965
5966 /* find function prototype */
69c087ba 5967 func_id = insn->imm;
17a52670 5968 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5969 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5970 func_id);
17a52670
AS
5971 return -EINVAL;
5972 }
5973
00176a34 5974 if (env->ops->get_func_proto)
5e43f899 5975 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5976 if (!fn) {
61bd5218
JK
5977 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5978 func_id);
17a52670
AS
5979 return -EINVAL;
5980 }
5981
5982 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5983 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5984 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5985 return -EINVAL;
5986 }
5987
eae2e83e
JO
5988 if (fn->allowed && !fn->allowed(env->prog)) {
5989 verbose(env, "helper call is not allowed in probe\n");
5990 return -EINVAL;
5991 }
5992
04514d13 5993 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5994 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5995 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5996 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5997 func_id_name(func_id), func_id);
5998 return -EINVAL;
5999 }
969bf05e 6000
33ff9823 6001 memset(&meta, 0, sizeof(meta));
36bbef52 6002 meta.pkt_access = fn->pkt_access;
33ff9823 6003
1b986589 6004 err = check_func_proto(fn, func_id);
435faee1 6005 if (err) {
61bd5218 6006 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 6007 func_id_name(func_id), func_id);
435faee1
DB
6008 return err;
6009 }
6010
d83525ca 6011 meta.func_id = func_id;
17a52670 6012 /* check args */
523a4cf4 6013 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 6014 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
6015 if (err)
6016 return err;
6017 }
17a52670 6018
c93552c4
DB
6019 err = record_func_map(env, &meta, func_id, insn_idx);
6020 if (err)
6021 return err;
6022
d2e4c1e6
DB
6023 err = record_func_key(env, &meta, func_id, insn_idx);
6024 if (err)
6025 return err;
6026
435faee1
DB
6027 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6028 * is inferred from register state.
6029 */
6030 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
6031 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6032 BPF_WRITE, -1, false);
435faee1
DB
6033 if (err)
6034 return err;
6035 }
6036
fd978bf7
JS
6037 if (func_id == BPF_FUNC_tail_call) {
6038 err = check_reference_leak(env);
6039 if (err) {
6040 verbose(env, "tail_call would lead to reference leak\n");
6041 return err;
6042 }
6043 } else if (is_release_function(func_id)) {
1b986589 6044 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
6045 if (err) {
6046 verbose(env, "func %s#%d reference has not been acquired before\n",
6047 func_id_name(func_id), func_id);
fd978bf7 6048 return err;
46f8bc92 6049 }
fd978bf7
JS
6050 }
6051
638f5b90 6052 regs = cur_regs(env);
cd339431
RG
6053
6054 /* check that flags argument in get_local_storage(map, flags) is 0,
6055 * this is required because get_local_storage() can't return an error.
6056 */
6057 if (func_id == BPF_FUNC_get_local_storage &&
6058 !register_is_null(&regs[BPF_REG_2])) {
6059 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6060 return -EINVAL;
6061 }
6062
69c087ba
YS
6063 if (func_id == BPF_FUNC_for_each_map_elem) {
6064 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6065 set_map_elem_callback_state);
6066 if (err < 0)
6067 return -EINVAL;
6068 }
6069
7b15523a
FR
6070 if (func_id == BPF_FUNC_snprintf) {
6071 err = check_bpf_snprintf_call(env, regs);
6072 if (err < 0)
6073 return err;
6074 }
6075
17a52670 6076 /* reset caller saved regs */
dc503a8a 6077 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 6078 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
6079 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6080 }
17a52670 6081
5327ed3d
JW
6082 /* helper call returns 64-bit value. */
6083 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6084
dc503a8a 6085 /* update return register (already marked as written above) */
17a52670 6086 if (fn->ret_type == RET_INTEGER) {
f1174f77 6087 /* sets type to SCALAR_VALUE */
61bd5218 6088 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
6089 } else if (fn->ret_type == RET_VOID) {
6090 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
6091 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6092 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 6093 /* There is no offset yet applied, variable or fixed */
61bd5218 6094 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
6095 /* remember map_ptr, so that check_map_access()
6096 * can check 'value_size' boundary of memory access
6097 * to map element returned from bpf_map_lookup_elem()
6098 */
33ff9823 6099 if (meta.map_ptr == NULL) {
61bd5218
JK
6100 verbose(env,
6101 "kernel subsystem misconfigured verifier\n");
17a52670
AS
6102 return -EINVAL;
6103 }
33ff9823 6104 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
6105 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6106 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
6107 if (map_value_has_spin_lock(meta.map_ptr))
6108 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
6109 } else {
6110 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 6111 }
c64b7983
JS
6112 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6113 mark_reg_known_zero(env, regs, BPF_REG_0);
6114 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
6115 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6116 mark_reg_known_zero(env, regs, BPF_REG_0);
6117 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
6118 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6119 mark_reg_known_zero(env, regs, BPF_REG_0);
6120 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
6121 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6122 mark_reg_known_zero(env, regs, BPF_REG_0);
6123 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 6124 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
6125 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6126 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
6127 const struct btf_type *t;
6128
6129 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 6130 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
6131 if (!btf_type_is_struct(t)) {
6132 u32 tsize;
6133 const struct btf_type *ret;
6134 const char *tname;
6135
6136 /* resolve the type size of ksym. */
22dc4a0f 6137 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 6138 if (IS_ERR(ret)) {
22dc4a0f 6139 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
6140 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6141 tname, PTR_ERR(ret));
6142 return -EINVAL;
6143 }
63d9b80d
HL
6144 regs[BPF_REG_0].type =
6145 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6146 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
6147 regs[BPF_REG_0].mem_size = tsize;
6148 } else {
63d9b80d
HL
6149 regs[BPF_REG_0].type =
6150 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6151 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 6152 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
6153 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6154 }
3ca1032a
KS
6155 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6156 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
6157 int ret_btf_id;
6158
6159 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
6160 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6161 PTR_TO_BTF_ID :
6162 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
6163 ret_btf_id = *fn->ret_btf_id;
6164 if (ret_btf_id == 0) {
6165 verbose(env, "invalid return type %d of func %s#%d\n",
6166 fn->ret_type, func_id_name(func_id), func_id);
6167 return -EINVAL;
6168 }
22dc4a0f
AN
6169 /* current BPF helper definitions are only coming from
6170 * built-in code with type IDs from vmlinux BTF
6171 */
6172 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 6173 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 6174 } else {
61bd5218 6175 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 6176 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
6177 return -EINVAL;
6178 }
04fd61ab 6179
93c230e3
MKL
6180 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6181 regs[BPF_REG_0].id = ++env->id_gen;
6182
0f3adc28 6183 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
6184 /* For release_reference() */
6185 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 6186 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
6187 int id = acquire_reference_state(env, insn_idx);
6188
6189 if (id < 0)
6190 return id;
6191 /* For mark_ptr_or_null_reg() */
6192 regs[BPF_REG_0].id = id;
6193 /* For release_reference() */
6194 regs[BPF_REG_0].ref_obj_id = id;
6195 }
1b986589 6196
849fa506
YS
6197 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6198
61bd5218 6199 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
6200 if (err)
6201 return err;
04fd61ab 6202
fa28dcb8
SL
6203 if ((func_id == BPF_FUNC_get_stack ||
6204 func_id == BPF_FUNC_get_task_stack) &&
6205 !env->prog->has_callchain_buf) {
c195651e
YS
6206 const char *err_str;
6207
6208#ifdef CONFIG_PERF_EVENTS
6209 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6210 err_str = "cannot get callchain buffer for func %s#%d\n";
6211#else
6212 err = -ENOTSUPP;
6213 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6214#endif
6215 if (err) {
6216 verbose(env, err_str, func_id_name(func_id), func_id);
6217 return err;
6218 }
6219
6220 env->prog->has_callchain_buf = true;
6221 }
6222
5d99cb2c
SL
6223 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6224 env->prog->call_get_stack = true;
6225
969bf05e
AS
6226 if (changes_data)
6227 clear_all_pkt_pointers(env);
6228 return 0;
6229}
6230
e6ac2450
MKL
6231/* mark_btf_func_reg_size() is used when the reg size is determined by
6232 * the BTF func_proto's return value size and argument.
6233 */
6234static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6235 size_t reg_size)
6236{
6237 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6238
6239 if (regno == BPF_REG_0) {
6240 /* Function return value */
6241 reg->live |= REG_LIVE_WRITTEN;
6242 reg->subreg_def = reg_size == sizeof(u64) ?
6243 DEF_NOT_SUBREG : env->insn_idx + 1;
6244 } else {
6245 /* Function argument */
6246 if (reg_size == sizeof(u64)) {
6247 mark_insn_zext(env, reg);
6248 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6249 } else {
6250 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6251 }
6252 }
6253}
6254
6255static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6256{
6257 const struct btf_type *t, *func, *func_proto, *ptr_type;
6258 struct bpf_reg_state *regs = cur_regs(env);
6259 const char *func_name, *ptr_type_name;
6260 u32 i, nargs, func_id, ptr_type_id;
6261 const struct btf_param *args;
6262 int err;
6263
6264 func_id = insn->imm;
6265 func = btf_type_by_id(btf_vmlinux, func_id);
6266 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6267 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6268
6269 if (!env->ops->check_kfunc_call ||
6270 !env->ops->check_kfunc_call(func_id)) {
6271 verbose(env, "calling kernel function %s is not allowed\n",
6272 func_name);
6273 return -EACCES;
6274 }
6275
6276 /* Check the arguments */
6277 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6278 if (err)
6279 return err;
6280
6281 for (i = 0; i < CALLER_SAVED_REGS; i++)
6282 mark_reg_not_init(env, regs, caller_saved[i]);
6283
6284 /* Check return type */
6285 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6286 if (btf_type_is_scalar(t)) {
6287 mark_reg_unknown(env, regs, BPF_REG_0);
6288 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6289 } else if (btf_type_is_ptr(t)) {
6290 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6291 &ptr_type_id);
6292 if (!btf_type_is_struct(ptr_type)) {
6293 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6294 ptr_type->name_off);
6295 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6296 func_name, btf_type_str(ptr_type),
6297 ptr_type_name);
6298 return -EINVAL;
6299 }
6300 mark_reg_known_zero(env, regs, BPF_REG_0);
6301 regs[BPF_REG_0].btf = btf_vmlinux;
6302 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6303 regs[BPF_REG_0].btf_id = ptr_type_id;
6304 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6305 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6306
6307 nargs = btf_type_vlen(func_proto);
6308 args = (const struct btf_param *)(func_proto + 1);
6309 for (i = 0; i < nargs; i++) {
6310 u32 regno = i + 1;
6311
6312 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6313 if (btf_type_is_ptr(t))
6314 mark_btf_func_reg_size(env, regno, sizeof(void *));
6315 else
6316 /* scalar. ensured by btf_check_kfunc_arg_match() */
6317 mark_btf_func_reg_size(env, regno, t->size);
6318 }
6319
6320 return 0;
6321}
6322
b03c9f9f
EC
6323static bool signed_add_overflows(s64 a, s64 b)
6324{
6325 /* Do the add in u64, where overflow is well-defined */
6326 s64 res = (s64)((u64)a + (u64)b);
6327
6328 if (b < 0)
6329 return res > a;
6330 return res < a;
6331}
6332
bc895e8b 6333static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
6334{
6335 /* Do the add in u32, where overflow is well-defined */
6336 s32 res = (s32)((u32)a + (u32)b);
6337
6338 if (b < 0)
6339 return res > a;
6340 return res < a;
6341}
6342
bc895e8b 6343static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
6344{
6345 /* Do the sub in u64, where overflow is well-defined */
6346 s64 res = (s64)((u64)a - (u64)b);
6347
6348 if (b < 0)
6349 return res < a;
6350 return res > a;
969bf05e
AS
6351}
6352
3f50f132
JF
6353static bool signed_sub32_overflows(s32 a, s32 b)
6354{
bc895e8b 6355 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
6356 s32 res = (s32)((u32)a - (u32)b);
6357
6358 if (b < 0)
6359 return res < a;
6360 return res > a;
6361}
6362
bb7f0f98
AS
6363static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6364 const struct bpf_reg_state *reg,
6365 enum bpf_reg_type type)
6366{
6367 bool known = tnum_is_const(reg->var_off);
6368 s64 val = reg->var_off.value;
6369 s64 smin = reg->smin_value;
6370
6371 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6372 verbose(env, "math between %s pointer and %lld is not allowed\n",
6373 reg_type_str[type], val);
6374 return false;
6375 }
6376
6377 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6378 verbose(env, "%s pointer offset %d is not allowed\n",
6379 reg_type_str[type], reg->off);
6380 return false;
6381 }
6382
6383 if (smin == S64_MIN) {
6384 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6385 reg_type_str[type]);
6386 return false;
6387 }
6388
6389 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6390 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6391 smin, reg_type_str[type]);
6392 return false;
6393 }
6394
6395 return true;
6396}
6397
979d63d5
DB
6398static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6399{
6400 return &env->insn_aux_data[env->insn_idx];
6401}
6402
a6aaece0
DB
6403enum {
6404 REASON_BOUNDS = -1,
6405 REASON_TYPE = -2,
6406 REASON_PATHS = -3,
6407 REASON_LIMIT = -4,
6408 REASON_STACK = -5,
6409};
6410
979d63d5 6411static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 6412 u32 *alu_limit, bool mask_to_left)
979d63d5 6413{
7fedb63a 6414 u32 max = 0, ptr_limit = 0;
979d63d5
DB
6415
6416 switch (ptr_reg->type) {
6417 case PTR_TO_STACK:
1b1597e6 6418 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
6419 * left direction, see BPF_REG_FP. Also, unknown scalar
6420 * offset where we would need to deal with min/max bounds is
6421 * currently prohibited for unprivileged.
1b1597e6
PK
6422 */
6423 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 6424 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 6425 break;
979d63d5 6426 case PTR_TO_MAP_VALUE:
1b1597e6 6427 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
6428 ptr_limit = (mask_to_left ?
6429 ptr_reg->smin_value :
6430 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 6431 break;
979d63d5 6432 default:
a6aaece0 6433 return REASON_TYPE;
979d63d5 6434 }
b658bbb8
DB
6435
6436 if (ptr_limit >= max)
a6aaece0 6437 return REASON_LIMIT;
b658bbb8
DB
6438 *alu_limit = ptr_limit;
6439 return 0;
979d63d5
DB
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))
a6aaece0 6457 return REASON_PATHS;
d3bd7413 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
f5288193
DB
6476static bool sanitize_needed(u8 opcode)
6477{
6478 return opcode == BPF_ADD || opcode == BPF_SUB;
6479}
6480
3d0220f6
DB
6481struct bpf_sanitize_info {
6482 struct bpf_insn_aux_data aux;
bb01a1bb 6483 bool mask_to_left;
3d0220f6
DB
6484};
6485
979d63d5
DB
6486static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6487 struct bpf_insn *insn,
6488 const struct bpf_reg_state *ptr_reg,
6f55b2f2 6489 const struct bpf_reg_state *off_reg,
979d63d5 6490 struct bpf_reg_state *dst_reg,
3d0220f6 6491 struct bpf_sanitize_info *info,
7fedb63a 6492 const bool commit_window)
979d63d5 6493{
3d0220f6 6494 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 6495 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 6496 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 6497 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
6498 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6499 u8 opcode = BPF_OP(insn->code);
6500 u32 alu_state, alu_limit;
6501 struct bpf_reg_state tmp;
6502 bool ret;
f232326f 6503 int err;
979d63d5 6504
d3bd7413 6505 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
6506 return 0;
6507
6508 /* We already marked aux for masking from non-speculative
6509 * paths, thus we got here in the first place. We only care
6510 * to explore bad access from here.
6511 */
6512 if (vstate->speculative)
6513 goto do_sim;
6514
bb01a1bb
DB
6515 if (!commit_window) {
6516 if (!tnum_is_const(off_reg->var_off) &&
6517 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6518 return REASON_BOUNDS;
6519
6520 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6521 (opcode == BPF_SUB && !off_is_neg);
6522 }
6523
6524 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
6525 if (err < 0)
6526 return err;
6527
7fedb63a
DB
6528 if (commit_window) {
6529 /* In commit phase we narrow the masking window based on
6530 * the observed pointer move after the simulated operation.
6531 */
3d0220f6
DB
6532 alu_state = info->aux.alu_state;
6533 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
6534 } else {
6535 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 6536 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
6537 alu_state |= ptr_is_dst_reg ?
6538 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6539 }
6540
f232326f
PK
6541 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6542 if (err < 0)
6543 return err;
979d63d5 6544do_sim:
7fedb63a
DB
6545 /* If we're in commit phase, we're done here given we already
6546 * pushed the truncated dst_reg into the speculative verification
6547 * stack.
a7036191
DB
6548 *
6549 * Also, when register is a known constant, we rewrite register-based
6550 * operation to immediate-based, and thus do not need masking (and as
6551 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 6552 */
a7036191 6553 if (commit_window || off_is_imm)
7fedb63a
DB
6554 return 0;
6555
979d63d5
DB
6556 /* Simulate and find potential out-of-bounds access under
6557 * speculative execution from truncation as a result of
6558 * masking when off was not within expected range. If off
6559 * sits in dst, then we temporarily need to move ptr there
6560 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6561 * for cases where we use K-based arithmetic in one direction
6562 * and truncated reg-based in the other in order to explore
6563 * bad access.
6564 */
6565 if (!ptr_is_dst_reg) {
6566 tmp = *dst_reg;
6567 *dst_reg = *ptr_reg;
6568 }
6569 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 6570 if (!ptr_is_dst_reg && ret)
979d63d5 6571 *dst_reg = tmp;
a6aaece0
DB
6572 return !ret ? REASON_STACK : 0;
6573}
6574
6575static int sanitize_err(struct bpf_verifier_env *env,
6576 const struct bpf_insn *insn, int reason,
6577 const struct bpf_reg_state *off_reg,
6578 const struct bpf_reg_state *dst_reg)
6579{
6580 static const char *err = "pointer arithmetic with it prohibited for !root";
6581 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6582 u32 dst = insn->dst_reg, src = insn->src_reg;
6583
6584 switch (reason) {
6585 case REASON_BOUNDS:
6586 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6587 off_reg == dst_reg ? dst : src, err);
6588 break;
6589 case REASON_TYPE:
6590 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6591 off_reg == dst_reg ? src : dst, err);
6592 break;
6593 case REASON_PATHS:
6594 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6595 dst, op, err);
6596 break;
6597 case REASON_LIMIT:
6598 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6599 dst, op, err);
6600 break;
6601 case REASON_STACK:
6602 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6603 dst, err);
6604 break;
6605 default:
6606 verbose(env, "verifier internal error: unknown reason (%d)\n",
6607 reason);
6608 break;
6609 }
6610
6611 return -EACCES;
979d63d5
DB
6612}
6613
01f810ac
AM
6614/* check that stack access falls within stack limits and that 'reg' doesn't
6615 * have a variable offset.
6616 *
6617 * Variable offset is prohibited for unprivileged mode for simplicity since it
6618 * requires corresponding support in Spectre masking for stack ALU. See also
6619 * retrieve_ptr_limit().
6620 *
6621 *
6622 * 'off' includes 'reg->off'.
6623 */
6624static int check_stack_access_for_ptr_arithmetic(
6625 struct bpf_verifier_env *env,
6626 int regno,
6627 const struct bpf_reg_state *reg,
6628 int off)
6629{
6630 if (!tnum_is_const(reg->var_off)) {
6631 char tn_buf[48];
6632
6633 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6634 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6635 regno, tn_buf, off);
6636 return -EACCES;
6637 }
6638
6639 if (off >= 0 || off < -MAX_BPF_STACK) {
6640 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6641 "prohibited for !root; off=%d\n", regno, off);
6642 return -EACCES;
6643 }
6644
6645 return 0;
6646}
6647
073815b7
DB
6648static int sanitize_check_bounds(struct bpf_verifier_env *env,
6649 const struct bpf_insn *insn,
6650 const struct bpf_reg_state *dst_reg)
6651{
6652 u32 dst = insn->dst_reg;
6653
6654 /* For unprivileged we require that resulting offset must be in bounds
6655 * in order to be able to sanitize access later on.
6656 */
6657 if (env->bypass_spec_v1)
6658 return 0;
6659
6660 switch (dst_reg->type) {
6661 case PTR_TO_STACK:
6662 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6663 dst_reg->off + dst_reg->var_off.value))
6664 return -EACCES;
6665 break;
6666 case PTR_TO_MAP_VALUE:
6667 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6668 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6669 "prohibited for !root\n", dst);
6670 return -EACCES;
6671 }
6672 break;
6673 default:
6674 break;
6675 }
6676
6677 return 0;
6678}
01f810ac 6679
f1174f77 6680/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
6681 * Caller should also handle BPF_MOV case separately.
6682 * If we return -EACCES, caller may want to try again treating pointer as a
6683 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6684 */
6685static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6686 struct bpf_insn *insn,
6687 const struct bpf_reg_state *ptr_reg,
6688 const struct bpf_reg_state *off_reg)
969bf05e 6689{
f4d7e40a
AS
6690 struct bpf_verifier_state *vstate = env->cur_state;
6691 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6692 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 6693 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
6694 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6695 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6696 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6697 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 6698 struct bpf_sanitize_info info = {};
969bf05e 6699 u8 opcode = BPF_OP(insn->code);
24c109bb 6700 u32 dst = insn->dst_reg;
979d63d5 6701 int ret;
969bf05e 6702
f1174f77 6703 dst_reg = &regs[dst];
969bf05e 6704
6f16101e
DB
6705 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6706 smin_val > smax_val || umin_val > umax_val) {
6707 /* Taint dst register if offset had invalid bounds derived from
6708 * e.g. dead branches.
6709 */
f54c7898 6710 __mark_reg_unknown(env, dst_reg);
6f16101e 6711 return 0;
f1174f77
EC
6712 }
6713
6714 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6715 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6716 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6717 __mark_reg_unknown(env, dst_reg);
6718 return 0;
6719 }
6720
82abbf8d
AS
6721 verbose(env,
6722 "R%d 32-bit pointer arithmetic prohibited\n",
6723 dst);
f1174f77 6724 return -EACCES;
969bf05e
AS
6725 }
6726
aad2eeaf
JS
6727 switch (ptr_reg->type) {
6728 case PTR_TO_MAP_VALUE_OR_NULL:
6729 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6730 dst, reg_type_str[ptr_reg->type]);
f1174f77 6731 return -EACCES;
aad2eeaf 6732 case CONST_PTR_TO_MAP:
7c696732
YS
6733 /* smin_val represents the known value */
6734 if (known && smin_val == 0 && opcode == BPF_ADD)
6735 break;
8731745e 6736 fallthrough;
aad2eeaf 6737 case PTR_TO_PACKET_END:
c64b7983
JS
6738 case PTR_TO_SOCKET:
6739 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6740 case PTR_TO_SOCK_COMMON:
6741 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6742 case PTR_TO_TCP_SOCK:
6743 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6744 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6745 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6746 dst, reg_type_str[ptr_reg->type]);
f1174f77 6747 return -EACCES;
aad2eeaf
JS
6748 default:
6749 break;
f1174f77
EC
6750 }
6751
6752 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6753 * The id may be overwritten later if we create a new variable offset.
969bf05e 6754 */
f1174f77
EC
6755 dst_reg->type = ptr_reg->type;
6756 dst_reg->id = ptr_reg->id;
969bf05e 6757
bb7f0f98
AS
6758 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6759 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6760 return -EINVAL;
6761
3f50f132
JF
6762 /* pointer types do not carry 32-bit bounds at the moment. */
6763 __mark_reg32_unbounded(dst_reg);
6764
7fedb63a
DB
6765 if (sanitize_needed(opcode)) {
6766 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 6767 &info, false);
a6aaece0
DB
6768 if (ret < 0)
6769 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 6770 }
a6aaece0 6771
f1174f77
EC
6772 switch (opcode) {
6773 case BPF_ADD:
6774 /* We can take a fixed offset as long as it doesn't overflow
6775 * the s32 'off' field
969bf05e 6776 */
b03c9f9f
EC
6777 if (known && (ptr_reg->off + smin_val ==
6778 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6779 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6780 dst_reg->smin_value = smin_ptr;
6781 dst_reg->smax_value = smax_ptr;
6782 dst_reg->umin_value = umin_ptr;
6783 dst_reg->umax_value = umax_ptr;
f1174f77 6784 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6785 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6786 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6787 break;
6788 }
f1174f77
EC
6789 /* A new variable offset is created. Note that off_reg->off
6790 * == 0, since it's a scalar.
6791 * dst_reg gets the pointer type and since some positive
6792 * integer value was added to the pointer, give it a new 'id'
6793 * if it's a PTR_TO_PACKET.
6794 * this creates a new 'base' pointer, off_reg (variable) gets
6795 * added into the variable offset, and we copy the fixed offset
6796 * from ptr_reg.
969bf05e 6797 */
b03c9f9f
EC
6798 if (signed_add_overflows(smin_ptr, smin_val) ||
6799 signed_add_overflows(smax_ptr, smax_val)) {
6800 dst_reg->smin_value = S64_MIN;
6801 dst_reg->smax_value = S64_MAX;
6802 } else {
6803 dst_reg->smin_value = smin_ptr + smin_val;
6804 dst_reg->smax_value = smax_ptr + smax_val;
6805 }
6806 if (umin_ptr + umin_val < umin_ptr ||
6807 umax_ptr + umax_val < umax_ptr) {
6808 dst_reg->umin_value = 0;
6809 dst_reg->umax_value = U64_MAX;
6810 } else {
6811 dst_reg->umin_value = umin_ptr + umin_val;
6812 dst_reg->umax_value = umax_ptr + umax_val;
6813 }
f1174f77
EC
6814 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6815 dst_reg->off = ptr_reg->off;
0962590e 6816 dst_reg->raw = ptr_reg->raw;
de8f3a83 6817 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6818 dst_reg->id = ++env->id_gen;
6819 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6820 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6821 }
6822 break;
6823 case BPF_SUB:
6824 if (dst_reg == off_reg) {
6825 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6826 verbose(env, "R%d tried to subtract pointer from scalar\n",
6827 dst);
f1174f77
EC
6828 return -EACCES;
6829 }
6830 /* We don't allow subtraction from FP, because (according to
6831 * test_verifier.c test "invalid fp arithmetic", JITs might not
6832 * be able to deal with it.
969bf05e 6833 */
f1174f77 6834 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6835 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6836 dst);
f1174f77
EC
6837 return -EACCES;
6838 }
b03c9f9f
EC
6839 if (known && (ptr_reg->off - smin_val ==
6840 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6841 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6842 dst_reg->smin_value = smin_ptr;
6843 dst_reg->smax_value = smax_ptr;
6844 dst_reg->umin_value = umin_ptr;
6845 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6846 dst_reg->var_off = ptr_reg->var_off;
6847 dst_reg->id = ptr_reg->id;
b03c9f9f 6848 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6849 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6850 break;
6851 }
f1174f77
EC
6852 /* A new variable offset is created. If the subtrahend is known
6853 * nonnegative, then any reg->range we had before is still good.
969bf05e 6854 */
b03c9f9f
EC
6855 if (signed_sub_overflows(smin_ptr, smax_val) ||
6856 signed_sub_overflows(smax_ptr, smin_val)) {
6857 /* Overflow possible, we know nothing */
6858 dst_reg->smin_value = S64_MIN;
6859 dst_reg->smax_value = S64_MAX;
6860 } else {
6861 dst_reg->smin_value = smin_ptr - smax_val;
6862 dst_reg->smax_value = smax_ptr - smin_val;
6863 }
6864 if (umin_ptr < umax_val) {
6865 /* Overflow possible, we know nothing */
6866 dst_reg->umin_value = 0;
6867 dst_reg->umax_value = U64_MAX;
6868 } else {
6869 /* Cannot overflow (as long as bounds are consistent) */
6870 dst_reg->umin_value = umin_ptr - umax_val;
6871 dst_reg->umax_value = umax_ptr - umin_val;
6872 }
f1174f77
EC
6873 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6874 dst_reg->off = ptr_reg->off;
0962590e 6875 dst_reg->raw = ptr_reg->raw;
de8f3a83 6876 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6877 dst_reg->id = ++env->id_gen;
6878 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6879 if (smin_val < 0)
22dc4a0f 6880 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6881 }
f1174f77
EC
6882 break;
6883 case BPF_AND:
6884 case BPF_OR:
6885 case BPF_XOR:
82abbf8d
AS
6886 /* bitwise ops on pointers are troublesome, prohibit. */
6887 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6888 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6889 return -EACCES;
6890 default:
6891 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6892 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6893 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6894 return -EACCES;
43188702
JF
6895 }
6896
bb7f0f98
AS
6897 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6898 return -EINVAL;
6899
b03c9f9f
EC
6900 __update_reg_bounds(dst_reg);
6901 __reg_deduce_bounds(dst_reg);
6902 __reg_bound_offset(dst_reg);
0d6303db 6903
073815b7
DB
6904 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6905 return -EACCES;
7fedb63a
DB
6906 if (sanitize_needed(opcode)) {
6907 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 6908 &info, true);
7fedb63a
DB
6909 if (ret < 0)
6910 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
6911 }
6912
43188702
JF
6913 return 0;
6914}
6915
3f50f132
JF
6916static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6917 struct bpf_reg_state *src_reg)
6918{
6919 s32 smin_val = src_reg->s32_min_value;
6920 s32 smax_val = src_reg->s32_max_value;
6921 u32 umin_val = src_reg->u32_min_value;
6922 u32 umax_val = src_reg->u32_max_value;
6923
6924 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6925 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6926 dst_reg->s32_min_value = S32_MIN;
6927 dst_reg->s32_max_value = S32_MAX;
6928 } else {
6929 dst_reg->s32_min_value += smin_val;
6930 dst_reg->s32_max_value += smax_val;
6931 }
6932 if (dst_reg->u32_min_value + umin_val < umin_val ||
6933 dst_reg->u32_max_value + umax_val < umax_val) {
6934 dst_reg->u32_min_value = 0;
6935 dst_reg->u32_max_value = U32_MAX;
6936 } else {
6937 dst_reg->u32_min_value += umin_val;
6938 dst_reg->u32_max_value += umax_val;
6939 }
6940}
6941
07cd2631
JF
6942static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6943 struct bpf_reg_state *src_reg)
6944{
6945 s64 smin_val = src_reg->smin_value;
6946 s64 smax_val = src_reg->smax_value;
6947 u64 umin_val = src_reg->umin_value;
6948 u64 umax_val = src_reg->umax_value;
6949
6950 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6951 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6952 dst_reg->smin_value = S64_MIN;
6953 dst_reg->smax_value = S64_MAX;
6954 } else {
6955 dst_reg->smin_value += smin_val;
6956 dst_reg->smax_value += smax_val;
6957 }
6958 if (dst_reg->umin_value + umin_val < umin_val ||
6959 dst_reg->umax_value + umax_val < umax_val) {
6960 dst_reg->umin_value = 0;
6961 dst_reg->umax_value = U64_MAX;
6962 } else {
6963 dst_reg->umin_value += umin_val;
6964 dst_reg->umax_value += umax_val;
6965 }
3f50f132
JF
6966}
6967
6968static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6969 struct bpf_reg_state *src_reg)
6970{
6971 s32 smin_val = src_reg->s32_min_value;
6972 s32 smax_val = src_reg->s32_max_value;
6973 u32 umin_val = src_reg->u32_min_value;
6974 u32 umax_val = src_reg->u32_max_value;
6975
6976 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6977 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6978 /* Overflow possible, we know nothing */
6979 dst_reg->s32_min_value = S32_MIN;
6980 dst_reg->s32_max_value = S32_MAX;
6981 } else {
6982 dst_reg->s32_min_value -= smax_val;
6983 dst_reg->s32_max_value -= smin_val;
6984 }
6985 if (dst_reg->u32_min_value < umax_val) {
6986 /* Overflow possible, we know nothing */
6987 dst_reg->u32_min_value = 0;
6988 dst_reg->u32_max_value = U32_MAX;
6989 } else {
6990 /* Cannot overflow (as long as bounds are consistent) */
6991 dst_reg->u32_min_value -= umax_val;
6992 dst_reg->u32_max_value -= umin_val;
6993 }
07cd2631
JF
6994}
6995
6996static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6997 struct bpf_reg_state *src_reg)
6998{
6999 s64 smin_val = src_reg->smin_value;
7000 s64 smax_val = src_reg->smax_value;
7001 u64 umin_val = src_reg->umin_value;
7002 u64 umax_val = src_reg->umax_value;
7003
7004 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7005 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7006 /* Overflow possible, we know nothing */
7007 dst_reg->smin_value = S64_MIN;
7008 dst_reg->smax_value = S64_MAX;
7009 } else {
7010 dst_reg->smin_value -= smax_val;
7011 dst_reg->smax_value -= smin_val;
7012 }
7013 if (dst_reg->umin_value < umax_val) {
7014 /* Overflow possible, we know nothing */
7015 dst_reg->umin_value = 0;
7016 dst_reg->umax_value = U64_MAX;
7017 } else {
7018 /* Cannot overflow (as long as bounds are consistent) */
7019 dst_reg->umin_value -= umax_val;
7020 dst_reg->umax_value -= umin_val;
7021 }
3f50f132
JF
7022}
7023
7024static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7025 struct bpf_reg_state *src_reg)
7026{
7027 s32 smin_val = src_reg->s32_min_value;
7028 u32 umin_val = src_reg->u32_min_value;
7029 u32 umax_val = src_reg->u32_max_value;
7030
7031 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7032 /* Ain't nobody got time to multiply that sign */
7033 __mark_reg32_unbounded(dst_reg);
7034 return;
7035 }
7036 /* Both values are positive, so we can work with unsigned and
7037 * copy the result to signed (unless it exceeds S32_MAX).
7038 */
7039 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7040 /* Potential overflow, we know nothing */
7041 __mark_reg32_unbounded(dst_reg);
7042 return;
7043 }
7044 dst_reg->u32_min_value *= umin_val;
7045 dst_reg->u32_max_value *= umax_val;
7046 if (dst_reg->u32_max_value > S32_MAX) {
7047 /* Overflow possible, we know nothing */
7048 dst_reg->s32_min_value = S32_MIN;
7049 dst_reg->s32_max_value = S32_MAX;
7050 } else {
7051 dst_reg->s32_min_value = dst_reg->u32_min_value;
7052 dst_reg->s32_max_value = dst_reg->u32_max_value;
7053 }
07cd2631
JF
7054}
7055
7056static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7057 struct bpf_reg_state *src_reg)
7058{
7059 s64 smin_val = src_reg->smin_value;
7060 u64 umin_val = src_reg->umin_value;
7061 u64 umax_val = src_reg->umax_value;
7062
07cd2631
JF
7063 if (smin_val < 0 || dst_reg->smin_value < 0) {
7064 /* Ain't nobody got time to multiply that sign */
3f50f132 7065 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7066 return;
7067 }
7068 /* Both values are positive, so we can work with unsigned and
7069 * copy the result to signed (unless it exceeds S64_MAX).
7070 */
7071 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7072 /* Potential overflow, we know nothing */
3f50f132 7073 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7074 return;
7075 }
7076 dst_reg->umin_value *= umin_val;
7077 dst_reg->umax_value *= umax_val;
7078 if (dst_reg->umax_value > S64_MAX) {
7079 /* Overflow possible, we know nothing */
7080 dst_reg->smin_value = S64_MIN;
7081 dst_reg->smax_value = S64_MAX;
7082 } else {
7083 dst_reg->smin_value = dst_reg->umin_value;
7084 dst_reg->smax_value = dst_reg->umax_value;
7085 }
7086}
7087
3f50f132
JF
7088static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7089 struct bpf_reg_state *src_reg)
7090{
7091 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7092 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7093 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7094 s32 smin_val = src_reg->s32_min_value;
7095 u32 umax_val = src_reg->u32_max_value;
7096
049c4e13
DB
7097 if (src_known && dst_known) {
7098 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 7099 return;
049c4e13 7100 }
3f50f132
JF
7101
7102 /* We get our minimum from the var_off, since that's inherently
7103 * bitwise. Our maximum is the minimum of the operands' maxima.
7104 */
7105 dst_reg->u32_min_value = var32_off.value;
7106 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7107 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7108 /* Lose signed bounds when ANDing negative numbers,
7109 * ain't nobody got time for that.
7110 */
7111 dst_reg->s32_min_value = S32_MIN;
7112 dst_reg->s32_max_value = S32_MAX;
7113 } else {
7114 /* ANDing two positives gives a positive, so safe to
7115 * cast result into s64.
7116 */
7117 dst_reg->s32_min_value = dst_reg->u32_min_value;
7118 dst_reg->s32_max_value = dst_reg->u32_max_value;
7119 }
3f50f132
JF
7120}
7121
07cd2631
JF
7122static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7123 struct bpf_reg_state *src_reg)
7124{
3f50f132
JF
7125 bool src_known = tnum_is_const(src_reg->var_off);
7126 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7127 s64 smin_val = src_reg->smin_value;
7128 u64 umax_val = src_reg->umax_value;
7129
3f50f132 7130 if (src_known && dst_known) {
4fbb38a3 7131 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7132 return;
7133 }
7134
07cd2631
JF
7135 /* We get our minimum from the var_off, since that's inherently
7136 * bitwise. Our maximum is the minimum of the operands' maxima.
7137 */
07cd2631
JF
7138 dst_reg->umin_value = dst_reg->var_off.value;
7139 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7140 if (dst_reg->smin_value < 0 || smin_val < 0) {
7141 /* Lose signed bounds when ANDing negative numbers,
7142 * ain't nobody got time for that.
7143 */
7144 dst_reg->smin_value = S64_MIN;
7145 dst_reg->smax_value = S64_MAX;
7146 } else {
7147 /* ANDing two positives gives a positive, so safe to
7148 * cast result into s64.
7149 */
7150 dst_reg->smin_value = dst_reg->umin_value;
7151 dst_reg->smax_value = dst_reg->umax_value;
7152 }
7153 /* We may learn something more from the var_off */
7154 __update_reg_bounds(dst_reg);
7155}
7156
3f50f132
JF
7157static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7158 struct bpf_reg_state *src_reg)
7159{
7160 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7161 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7162 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
7163 s32 smin_val = src_reg->s32_min_value;
7164 u32 umin_val = src_reg->u32_min_value;
3f50f132 7165
049c4e13
DB
7166 if (src_known && dst_known) {
7167 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 7168 return;
049c4e13 7169 }
3f50f132
JF
7170
7171 /* We get our maximum from the var_off, and our minimum is the
7172 * maximum of the operands' minima
7173 */
7174 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7175 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7176 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7177 /* Lose signed bounds when ORing negative numbers,
7178 * ain't nobody got time for that.
7179 */
7180 dst_reg->s32_min_value = S32_MIN;
7181 dst_reg->s32_max_value = S32_MAX;
7182 } else {
7183 /* ORing two positives gives a positive, so safe to
7184 * cast result into s64.
7185 */
5b9fbeb7
DB
7186 dst_reg->s32_min_value = dst_reg->u32_min_value;
7187 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
7188 }
7189}
7190
07cd2631
JF
7191static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7192 struct bpf_reg_state *src_reg)
7193{
3f50f132
JF
7194 bool src_known = tnum_is_const(src_reg->var_off);
7195 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7196 s64 smin_val = src_reg->smin_value;
7197 u64 umin_val = src_reg->umin_value;
7198
3f50f132 7199 if (src_known && dst_known) {
4fbb38a3 7200 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7201 return;
7202 }
7203
07cd2631
JF
7204 /* We get our maximum from the var_off, and our minimum is the
7205 * maximum of the operands' minima
7206 */
07cd2631
JF
7207 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7208 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7209 if (dst_reg->smin_value < 0 || smin_val < 0) {
7210 /* Lose signed bounds when ORing negative numbers,
7211 * ain't nobody got time for that.
7212 */
7213 dst_reg->smin_value = S64_MIN;
7214 dst_reg->smax_value = S64_MAX;
7215 } else {
7216 /* ORing two positives gives a positive, so safe to
7217 * cast result into s64.
7218 */
7219 dst_reg->smin_value = dst_reg->umin_value;
7220 dst_reg->smax_value = dst_reg->umax_value;
7221 }
7222 /* We may learn something more from the var_off */
7223 __update_reg_bounds(dst_reg);
7224}
7225
2921c90d
YS
7226static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7227 struct bpf_reg_state *src_reg)
7228{
7229 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7230 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7231 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7232 s32 smin_val = src_reg->s32_min_value;
7233
049c4e13
DB
7234 if (src_known && dst_known) {
7235 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 7236 return;
049c4e13 7237 }
2921c90d
YS
7238
7239 /* We get both minimum and maximum from the var32_off. */
7240 dst_reg->u32_min_value = var32_off.value;
7241 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7242
7243 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7244 /* XORing two positive sign numbers gives a positive,
7245 * so safe to cast u32 result into s32.
7246 */
7247 dst_reg->s32_min_value = dst_reg->u32_min_value;
7248 dst_reg->s32_max_value = dst_reg->u32_max_value;
7249 } else {
7250 dst_reg->s32_min_value = S32_MIN;
7251 dst_reg->s32_max_value = S32_MAX;
7252 }
7253}
7254
7255static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7256 struct bpf_reg_state *src_reg)
7257{
7258 bool src_known = tnum_is_const(src_reg->var_off);
7259 bool dst_known = tnum_is_const(dst_reg->var_off);
7260 s64 smin_val = src_reg->smin_value;
7261
7262 if (src_known && dst_known) {
7263 /* dst_reg->var_off.value has been updated earlier */
7264 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7265 return;
7266 }
7267
7268 /* We get both minimum and maximum from the var_off. */
7269 dst_reg->umin_value = dst_reg->var_off.value;
7270 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7271
7272 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7273 /* XORing two positive sign numbers gives a positive,
7274 * so safe to cast u64 result into s64.
7275 */
7276 dst_reg->smin_value = dst_reg->umin_value;
7277 dst_reg->smax_value = dst_reg->umax_value;
7278 } else {
7279 dst_reg->smin_value = S64_MIN;
7280 dst_reg->smax_value = S64_MAX;
7281 }
7282
7283 __update_reg_bounds(dst_reg);
7284}
7285
3f50f132
JF
7286static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7287 u64 umin_val, u64 umax_val)
07cd2631 7288{
07cd2631
JF
7289 /* We lose all sign bit information (except what we can pick
7290 * up from var_off)
7291 */
3f50f132
JF
7292 dst_reg->s32_min_value = S32_MIN;
7293 dst_reg->s32_max_value = S32_MAX;
7294 /* If we might shift our top bit out, then we know nothing */
7295 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7296 dst_reg->u32_min_value = 0;
7297 dst_reg->u32_max_value = U32_MAX;
7298 } else {
7299 dst_reg->u32_min_value <<= umin_val;
7300 dst_reg->u32_max_value <<= umax_val;
7301 }
7302}
7303
7304static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7305 struct bpf_reg_state *src_reg)
7306{
7307 u32 umax_val = src_reg->u32_max_value;
7308 u32 umin_val = src_reg->u32_min_value;
7309 /* u32 alu operation will zext upper bits */
7310 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7311
7312 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7313 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7314 /* Not required but being careful mark reg64 bounds as unknown so
7315 * that we are forced to pick them up from tnum and zext later and
7316 * if some path skips this step we are still safe.
7317 */
7318 __mark_reg64_unbounded(dst_reg);
7319 __update_reg32_bounds(dst_reg);
7320}
7321
7322static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7323 u64 umin_val, u64 umax_val)
7324{
7325 /* Special case <<32 because it is a common compiler pattern to sign
7326 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7327 * positive we know this shift will also be positive so we can track
7328 * bounds correctly. Otherwise we lose all sign bit information except
7329 * what we can pick up from var_off. Perhaps we can generalize this
7330 * later to shifts of any length.
7331 */
7332 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7333 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7334 else
7335 dst_reg->smax_value = S64_MAX;
7336
7337 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7338 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7339 else
7340 dst_reg->smin_value = S64_MIN;
7341
07cd2631
JF
7342 /* If we might shift our top bit out, then we know nothing */
7343 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7344 dst_reg->umin_value = 0;
7345 dst_reg->umax_value = U64_MAX;
7346 } else {
7347 dst_reg->umin_value <<= umin_val;
7348 dst_reg->umax_value <<= umax_val;
7349 }
3f50f132
JF
7350}
7351
7352static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7353 struct bpf_reg_state *src_reg)
7354{
7355 u64 umax_val = src_reg->umax_value;
7356 u64 umin_val = src_reg->umin_value;
7357
7358 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7359 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7360 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7361
07cd2631
JF
7362 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7363 /* We may learn something more from the var_off */
7364 __update_reg_bounds(dst_reg);
7365}
7366
3f50f132
JF
7367static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7368 struct bpf_reg_state *src_reg)
7369{
7370 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7371 u32 umax_val = src_reg->u32_max_value;
7372 u32 umin_val = src_reg->u32_min_value;
7373
7374 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7375 * be negative, then either:
7376 * 1) src_reg might be zero, so the sign bit of the result is
7377 * unknown, so we lose our signed bounds
7378 * 2) it's known negative, thus the unsigned bounds capture the
7379 * signed bounds
7380 * 3) the signed bounds cross zero, so they tell us nothing
7381 * about the result
7382 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7383 * unsigned bounds capture the signed bounds.
3f50f132
JF
7384 * Thus, in all cases it suffices to blow away our signed bounds
7385 * and rely on inferring new ones from the unsigned bounds and
7386 * var_off of the result.
7387 */
7388 dst_reg->s32_min_value = S32_MIN;
7389 dst_reg->s32_max_value = S32_MAX;
7390
7391 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7392 dst_reg->u32_min_value >>= umax_val;
7393 dst_reg->u32_max_value >>= umin_val;
7394
7395 __mark_reg64_unbounded(dst_reg);
7396 __update_reg32_bounds(dst_reg);
7397}
7398
07cd2631
JF
7399static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7400 struct bpf_reg_state *src_reg)
7401{
7402 u64 umax_val = src_reg->umax_value;
7403 u64 umin_val = src_reg->umin_value;
7404
7405 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7406 * be negative, then either:
7407 * 1) src_reg might be zero, so the sign bit of the result is
7408 * unknown, so we lose our signed bounds
7409 * 2) it's known negative, thus the unsigned bounds capture the
7410 * signed bounds
7411 * 3) the signed bounds cross zero, so they tell us nothing
7412 * about the result
7413 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7414 * unsigned bounds capture the signed bounds.
07cd2631
JF
7415 * Thus, in all cases it suffices to blow away our signed bounds
7416 * and rely on inferring new ones from the unsigned bounds and
7417 * var_off of the result.
7418 */
7419 dst_reg->smin_value = S64_MIN;
7420 dst_reg->smax_value = S64_MAX;
7421 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7422 dst_reg->umin_value >>= umax_val;
7423 dst_reg->umax_value >>= umin_val;
3f50f132
JF
7424
7425 /* Its not easy to operate on alu32 bounds here because it depends
7426 * on bits being shifted in. Take easy way out and mark unbounded
7427 * so we can recalculate later from tnum.
7428 */
7429 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7430 __update_reg_bounds(dst_reg);
7431}
7432
3f50f132
JF
7433static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7434 struct bpf_reg_state *src_reg)
07cd2631 7435{
3f50f132 7436 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
7437
7438 /* Upon reaching here, src_known is true and
7439 * umax_val is equal to umin_val.
7440 */
3f50f132
JF
7441 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7442 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 7443
3f50f132
JF
7444 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7445
7446 /* blow away the dst_reg umin_value/umax_value and rely on
7447 * dst_reg var_off to refine the result.
7448 */
7449 dst_reg->u32_min_value = 0;
7450 dst_reg->u32_max_value = U32_MAX;
7451
7452 __mark_reg64_unbounded(dst_reg);
7453 __update_reg32_bounds(dst_reg);
7454}
7455
7456static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7457 struct bpf_reg_state *src_reg)
7458{
7459 u64 umin_val = src_reg->umin_value;
7460
7461 /* Upon reaching here, src_known is true and umax_val is equal
7462 * to umin_val.
7463 */
7464 dst_reg->smin_value >>= umin_val;
7465 dst_reg->smax_value >>= umin_val;
7466
7467 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
7468
7469 /* blow away the dst_reg umin_value/umax_value and rely on
7470 * dst_reg var_off to refine the result.
7471 */
7472 dst_reg->umin_value = 0;
7473 dst_reg->umax_value = U64_MAX;
3f50f132
JF
7474
7475 /* Its not easy to operate on alu32 bounds here because it depends
7476 * on bits being shifted in from upper 32-bits. Take easy way out
7477 * and mark unbounded so we can recalculate later from tnum.
7478 */
7479 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7480 __update_reg_bounds(dst_reg);
7481}
7482
468f6eaf
JH
7483/* WARNING: This function does calculations on 64-bit values, but the actual
7484 * execution may occur on 32-bit values. Therefore, things like bitshifts
7485 * need extra checks in the 32-bit case.
7486 */
f1174f77
EC
7487static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7488 struct bpf_insn *insn,
7489 struct bpf_reg_state *dst_reg,
7490 struct bpf_reg_state src_reg)
969bf05e 7491{
638f5b90 7492 struct bpf_reg_state *regs = cur_regs(env);
48461135 7493 u8 opcode = BPF_OP(insn->code);
b0b3fb67 7494 bool src_known;
b03c9f9f
EC
7495 s64 smin_val, smax_val;
7496 u64 umin_val, umax_val;
3f50f132
JF
7497 s32 s32_min_val, s32_max_val;
7498 u32 u32_min_val, u32_max_val;
468f6eaf 7499 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 7500 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 7501 int ret;
b799207e 7502
b03c9f9f
EC
7503 smin_val = src_reg.smin_value;
7504 smax_val = src_reg.smax_value;
7505 umin_val = src_reg.umin_value;
7506 umax_val = src_reg.umax_value;
f23cc643 7507
3f50f132
JF
7508 s32_min_val = src_reg.s32_min_value;
7509 s32_max_val = src_reg.s32_max_value;
7510 u32_min_val = src_reg.u32_min_value;
7511 u32_max_val = src_reg.u32_max_value;
7512
7513 if (alu32) {
7514 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
7515 if ((src_known &&
7516 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7517 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7518 /* Taint dst register if offset had invalid bounds
7519 * derived from e.g. dead branches.
7520 */
7521 __mark_reg_unknown(env, dst_reg);
7522 return 0;
7523 }
7524 } else {
7525 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
7526 if ((src_known &&
7527 (smin_val != smax_val || umin_val != umax_val)) ||
7528 smin_val > smax_val || umin_val > umax_val) {
7529 /* Taint dst register if offset had invalid bounds
7530 * derived from e.g. dead branches.
7531 */
7532 __mark_reg_unknown(env, dst_reg);
7533 return 0;
7534 }
6f16101e
DB
7535 }
7536
bb7f0f98
AS
7537 if (!src_known &&
7538 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 7539 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
7540 return 0;
7541 }
7542
f5288193
DB
7543 if (sanitize_needed(opcode)) {
7544 ret = sanitize_val_alu(env, insn);
7545 if (ret < 0)
7546 return sanitize_err(env, insn, ret, NULL, NULL);
7547 }
7548
3f50f132
JF
7549 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7550 * There are two classes of instructions: The first class we track both
7551 * alu32 and alu64 sign/unsigned bounds independently this provides the
7552 * greatest amount of precision when alu operations are mixed with jmp32
7553 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7554 * and BPF_OR. This is possible because these ops have fairly easy to
7555 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7556 * See alu32 verifier tests for examples. The second class of
7557 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7558 * with regards to tracking sign/unsigned bounds because the bits may
7559 * cross subreg boundaries in the alu64 case. When this happens we mark
7560 * the reg unbounded in the subreg bound space and use the resulting
7561 * tnum to calculate an approximation of the sign/unsigned bounds.
7562 */
48461135
JB
7563 switch (opcode) {
7564 case BPF_ADD:
3f50f132 7565 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 7566 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 7567 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
7568 break;
7569 case BPF_SUB:
3f50f132 7570 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 7571 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 7572 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
7573 break;
7574 case BPF_MUL:
3f50f132
JF
7575 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7576 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 7577 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
7578 break;
7579 case BPF_AND:
3f50f132
JF
7580 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7581 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 7582 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
7583 break;
7584 case BPF_OR:
3f50f132
JF
7585 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7586 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 7587 scalar_min_max_or(dst_reg, &src_reg);
48461135 7588 break;
2921c90d
YS
7589 case BPF_XOR:
7590 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7591 scalar32_min_max_xor(dst_reg, &src_reg);
7592 scalar_min_max_xor(dst_reg, &src_reg);
7593 break;
48461135 7594 case BPF_LSH:
468f6eaf
JH
7595 if (umax_val >= insn_bitness) {
7596 /* Shifts greater than 31 or 63 are undefined.
7597 * This includes shifts by a negative number.
b03c9f9f 7598 */
61bd5218 7599 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7600 break;
7601 }
3f50f132
JF
7602 if (alu32)
7603 scalar32_min_max_lsh(dst_reg, &src_reg);
7604 else
7605 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
7606 break;
7607 case BPF_RSH:
468f6eaf
JH
7608 if (umax_val >= insn_bitness) {
7609 /* Shifts greater than 31 or 63 are undefined.
7610 * This includes shifts by a negative number.
b03c9f9f 7611 */
61bd5218 7612 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7613 break;
7614 }
3f50f132
JF
7615 if (alu32)
7616 scalar32_min_max_rsh(dst_reg, &src_reg);
7617 else
7618 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 7619 break;
9cbe1f5a
YS
7620 case BPF_ARSH:
7621 if (umax_val >= insn_bitness) {
7622 /* Shifts greater than 31 or 63 are undefined.
7623 * This includes shifts by a negative number.
7624 */
7625 mark_reg_unknown(env, regs, insn->dst_reg);
7626 break;
7627 }
3f50f132
JF
7628 if (alu32)
7629 scalar32_min_max_arsh(dst_reg, &src_reg);
7630 else
7631 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 7632 break;
48461135 7633 default:
61bd5218 7634 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
7635 break;
7636 }
7637
3f50f132
JF
7638 /* ALU32 ops are zero extended into 64bit register */
7639 if (alu32)
7640 zext_32_to_64(dst_reg);
468f6eaf 7641
294f2fc6 7642 __update_reg_bounds(dst_reg);
b03c9f9f
EC
7643 __reg_deduce_bounds(dst_reg);
7644 __reg_bound_offset(dst_reg);
f1174f77
EC
7645 return 0;
7646}
7647
7648/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7649 * and var_off.
7650 */
7651static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7652 struct bpf_insn *insn)
7653{
f4d7e40a
AS
7654 struct bpf_verifier_state *vstate = env->cur_state;
7655 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7656 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
7657 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7658 u8 opcode = BPF_OP(insn->code);
b5dc0163 7659 int err;
f1174f77
EC
7660
7661 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
7662 src_reg = NULL;
7663 if (dst_reg->type != SCALAR_VALUE)
7664 ptr_reg = dst_reg;
75748837
AS
7665 else
7666 /* Make sure ID is cleared otherwise dst_reg min/max could be
7667 * incorrectly propagated into other registers by find_equal_scalars()
7668 */
7669 dst_reg->id = 0;
f1174f77
EC
7670 if (BPF_SRC(insn->code) == BPF_X) {
7671 src_reg = &regs[insn->src_reg];
f1174f77
EC
7672 if (src_reg->type != SCALAR_VALUE) {
7673 if (dst_reg->type != SCALAR_VALUE) {
7674 /* Combining two pointers by any ALU op yields
82abbf8d
AS
7675 * an arbitrary scalar. Disallow all math except
7676 * pointer subtraction
f1174f77 7677 */
dd066823 7678 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
7679 mark_reg_unknown(env, regs, insn->dst_reg);
7680 return 0;
f1174f77 7681 }
82abbf8d
AS
7682 verbose(env, "R%d pointer %s pointer prohibited\n",
7683 insn->dst_reg,
7684 bpf_alu_string[opcode >> 4]);
7685 return -EACCES;
f1174f77
EC
7686 } else {
7687 /* scalar += pointer
7688 * This is legal, but we have to reverse our
7689 * src/dest handling in computing the range
7690 */
b5dc0163
AS
7691 err = mark_chain_precision(env, insn->dst_reg);
7692 if (err)
7693 return err;
82abbf8d
AS
7694 return adjust_ptr_min_max_vals(env, insn,
7695 src_reg, dst_reg);
f1174f77
EC
7696 }
7697 } else if (ptr_reg) {
7698 /* pointer += scalar */
b5dc0163
AS
7699 err = mark_chain_precision(env, insn->src_reg);
7700 if (err)
7701 return err;
82abbf8d
AS
7702 return adjust_ptr_min_max_vals(env, insn,
7703 dst_reg, src_reg);
f1174f77
EC
7704 }
7705 } else {
7706 /* Pretend the src is a reg with a known value, since we only
7707 * need to be able to read from this state.
7708 */
7709 off_reg.type = SCALAR_VALUE;
b03c9f9f 7710 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7711 src_reg = &off_reg;
82abbf8d
AS
7712 if (ptr_reg) /* pointer += K */
7713 return adjust_ptr_min_max_vals(env, insn,
7714 ptr_reg, src_reg);
f1174f77
EC
7715 }
7716
7717 /* Got here implies adding two SCALAR_VALUEs */
7718 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7719 print_verifier_state(env, state);
61bd5218 7720 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7721 return -EINVAL;
7722 }
7723 if (WARN_ON(!src_reg)) {
f4d7e40a 7724 print_verifier_state(env, state);
61bd5218 7725 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7726 return -EINVAL;
7727 }
7728 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7729}
7730
17a52670 7731/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7732static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7733{
638f5b90 7734 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7735 u8 opcode = BPF_OP(insn->code);
7736 int err;
7737
7738 if (opcode == BPF_END || opcode == BPF_NEG) {
7739 if (opcode == BPF_NEG) {
7740 if (BPF_SRC(insn->code) != 0 ||
7741 insn->src_reg != BPF_REG_0 ||
7742 insn->off != 0 || insn->imm != 0) {
61bd5218 7743 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7744 return -EINVAL;
7745 }
7746 } else {
7747 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7748 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7749 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7750 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7751 return -EINVAL;
7752 }
7753 }
7754
7755 /* check src operand */
dc503a8a 7756 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7757 if (err)
7758 return err;
7759
1be7f75d 7760 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7761 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7762 insn->dst_reg);
7763 return -EACCES;
7764 }
7765
17a52670 7766 /* check dest operand */
dc503a8a 7767 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7768 if (err)
7769 return err;
7770
7771 } else if (opcode == BPF_MOV) {
7772
7773 if (BPF_SRC(insn->code) == BPF_X) {
7774 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7775 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7776 return -EINVAL;
7777 }
7778
7779 /* check src operand */
dc503a8a 7780 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7781 if (err)
7782 return err;
7783 } else {
7784 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7785 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7786 return -EINVAL;
7787 }
7788 }
7789
fbeb1603
AF
7790 /* check dest operand, mark as required later */
7791 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7792 if (err)
7793 return err;
7794
7795 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7796 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7797 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7798
17a52670
AS
7799 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7800 /* case: R1 = R2
7801 * copy register state to dest reg
7802 */
75748837
AS
7803 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7804 /* Assign src and dst registers the same ID
7805 * that will be used by find_equal_scalars()
7806 * to propagate min/max range.
7807 */
7808 src_reg->id = ++env->id_gen;
e434b8cd
JW
7809 *dst_reg = *src_reg;
7810 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7811 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7812 } else {
f1174f77 7813 /* R1 = (u32) R2 */
1be7f75d 7814 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7815 verbose(env,
7816 "R%d partial copy of pointer\n",
1be7f75d
AS
7817 insn->src_reg);
7818 return -EACCES;
e434b8cd
JW
7819 } else if (src_reg->type == SCALAR_VALUE) {
7820 *dst_reg = *src_reg;
75748837
AS
7821 /* Make sure ID is cleared otherwise
7822 * dst_reg min/max could be incorrectly
7823 * propagated into src_reg by find_equal_scalars()
7824 */
7825 dst_reg->id = 0;
e434b8cd 7826 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7827 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7828 } else {
7829 mark_reg_unknown(env, regs,
7830 insn->dst_reg);
1be7f75d 7831 }
3f50f132 7832 zext_32_to_64(dst_reg);
17a52670
AS
7833 }
7834 } else {
7835 /* case: R = imm
7836 * remember the value we stored into this reg
7837 */
fbeb1603
AF
7838 /* clear any state __mark_reg_known doesn't set */
7839 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7840 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7841 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7842 __mark_reg_known(regs + insn->dst_reg,
7843 insn->imm);
7844 } else {
7845 __mark_reg_known(regs + insn->dst_reg,
7846 (u32)insn->imm);
7847 }
17a52670
AS
7848 }
7849
7850 } else if (opcode > BPF_END) {
61bd5218 7851 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7852 return -EINVAL;
7853
7854 } else { /* all other ALU ops: and, sub, xor, add, ... */
7855
17a52670
AS
7856 if (BPF_SRC(insn->code) == BPF_X) {
7857 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7858 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7859 return -EINVAL;
7860 }
7861 /* check src1 operand */
dc503a8a 7862 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7863 if (err)
7864 return err;
7865 } else {
7866 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7867 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7868 return -EINVAL;
7869 }
7870 }
7871
7872 /* check src2 operand */
dc503a8a 7873 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7874 if (err)
7875 return err;
7876
7877 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7878 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7879 verbose(env, "div by zero\n");
17a52670
AS
7880 return -EINVAL;
7881 }
7882
229394e8
RV
7883 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7884 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7885 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7886
7887 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7888 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7889 return -EINVAL;
7890 }
7891 }
7892
1a0dc1ac 7893 /* check dest operand */
dc503a8a 7894 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7895 if (err)
7896 return err;
7897
f1174f77 7898 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7899 }
7900
7901 return 0;
7902}
7903
c6a9efa1
PC
7904static void __find_good_pkt_pointers(struct bpf_func_state *state,
7905 struct bpf_reg_state *dst_reg,
6d94e741 7906 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7907{
7908 struct bpf_reg_state *reg;
7909 int i;
7910
7911 for (i = 0; i < MAX_BPF_REG; i++) {
7912 reg = &state->regs[i];
7913 if (reg->type == type && reg->id == dst_reg->id)
7914 /* keep the maximum range already checked */
7915 reg->range = max(reg->range, new_range);
7916 }
7917
7918 bpf_for_each_spilled_reg(i, state, reg) {
7919 if (!reg)
7920 continue;
7921 if (reg->type == type && reg->id == dst_reg->id)
7922 reg->range = max(reg->range, new_range);
7923 }
7924}
7925
f4d7e40a 7926static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7927 struct bpf_reg_state *dst_reg,
f8ddadc4 7928 enum bpf_reg_type type,
fb2a311a 7929 bool range_right_open)
969bf05e 7930{
6d94e741 7931 int new_range, i;
2d2be8ca 7932
fb2a311a
DB
7933 if (dst_reg->off < 0 ||
7934 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7935 /* This doesn't give us any range */
7936 return;
7937
b03c9f9f
EC
7938 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7939 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7940 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7941 * than pkt_end, but that's because it's also less than pkt.
7942 */
7943 return;
7944
fb2a311a
DB
7945 new_range = dst_reg->off;
7946 if (range_right_open)
7947 new_range--;
7948
7949 /* Examples for register markings:
2d2be8ca 7950 *
fb2a311a 7951 * pkt_data in dst register:
2d2be8ca
DB
7952 *
7953 * r2 = r3;
7954 * r2 += 8;
7955 * if (r2 > pkt_end) goto <handle exception>
7956 * <access okay>
7957 *
b4e432f1
DB
7958 * r2 = r3;
7959 * r2 += 8;
7960 * if (r2 < pkt_end) goto <access okay>
7961 * <handle exception>
7962 *
2d2be8ca
DB
7963 * Where:
7964 * r2 == dst_reg, pkt_end == src_reg
7965 * r2=pkt(id=n,off=8,r=0)
7966 * r3=pkt(id=n,off=0,r=0)
7967 *
fb2a311a 7968 * pkt_data in src register:
2d2be8ca
DB
7969 *
7970 * r2 = r3;
7971 * r2 += 8;
7972 * if (pkt_end >= r2) goto <access okay>
7973 * <handle exception>
7974 *
b4e432f1
DB
7975 * r2 = r3;
7976 * r2 += 8;
7977 * if (pkt_end <= r2) goto <handle exception>
7978 * <access okay>
7979 *
2d2be8ca
DB
7980 * Where:
7981 * pkt_end == dst_reg, r2 == src_reg
7982 * r2=pkt(id=n,off=8,r=0)
7983 * r3=pkt(id=n,off=0,r=0)
7984 *
7985 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
7986 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7987 * and [r3, r3 + 8-1) respectively is safe to access depending on
7988 * the check.
969bf05e 7989 */
2d2be8ca 7990
f1174f77
EC
7991 /* If our ids match, then we must have the same max_value. And we
7992 * don't care about the other reg's fixed offset, since if it's too big
7993 * the range won't allow anything.
7994 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7995 */
c6a9efa1
PC
7996 for (i = 0; i <= vstate->curframe; i++)
7997 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7998 new_range);
969bf05e
AS
7999}
8000
3f50f132 8001static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 8002{
3f50f132
JF
8003 struct tnum subreg = tnum_subreg(reg->var_off);
8004 s32 sval = (s32)val;
a72dafaf 8005
3f50f132
JF
8006 switch (opcode) {
8007 case BPF_JEQ:
8008 if (tnum_is_const(subreg))
8009 return !!tnum_equals_const(subreg, val);
8010 break;
8011 case BPF_JNE:
8012 if (tnum_is_const(subreg))
8013 return !tnum_equals_const(subreg, val);
8014 break;
8015 case BPF_JSET:
8016 if ((~subreg.mask & subreg.value) & val)
8017 return 1;
8018 if (!((subreg.mask | subreg.value) & val))
8019 return 0;
8020 break;
8021 case BPF_JGT:
8022 if (reg->u32_min_value > val)
8023 return 1;
8024 else if (reg->u32_max_value <= val)
8025 return 0;
8026 break;
8027 case BPF_JSGT:
8028 if (reg->s32_min_value > sval)
8029 return 1;
ee114dd6 8030 else if (reg->s32_max_value <= sval)
3f50f132
JF
8031 return 0;
8032 break;
8033 case BPF_JLT:
8034 if (reg->u32_max_value < val)
8035 return 1;
8036 else if (reg->u32_min_value >= val)
8037 return 0;
8038 break;
8039 case BPF_JSLT:
8040 if (reg->s32_max_value < sval)
8041 return 1;
8042 else if (reg->s32_min_value >= sval)
8043 return 0;
8044 break;
8045 case BPF_JGE:
8046 if (reg->u32_min_value >= val)
8047 return 1;
8048 else if (reg->u32_max_value < val)
8049 return 0;
8050 break;
8051 case BPF_JSGE:
8052 if (reg->s32_min_value >= sval)
8053 return 1;
8054 else if (reg->s32_max_value < sval)
8055 return 0;
8056 break;
8057 case BPF_JLE:
8058 if (reg->u32_max_value <= val)
8059 return 1;
8060 else if (reg->u32_min_value > val)
8061 return 0;
8062 break;
8063 case BPF_JSLE:
8064 if (reg->s32_max_value <= sval)
8065 return 1;
8066 else if (reg->s32_min_value > sval)
8067 return 0;
8068 break;
8069 }
4f7b3e82 8070
3f50f132
JF
8071 return -1;
8072}
092ed096 8073
3f50f132
JF
8074
8075static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8076{
8077 s64 sval = (s64)val;
a72dafaf 8078
4f7b3e82
AS
8079 switch (opcode) {
8080 case BPF_JEQ:
8081 if (tnum_is_const(reg->var_off))
8082 return !!tnum_equals_const(reg->var_off, val);
8083 break;
8084 case BPF_JNE:
8085 if (tnum_is_const(reg->var_off))
8086 return !tnum_equals_const(reg->var_off, val);
8087 break;
960ea056
JK
8088 case BPF_JSET:
8089 if ((~reg->var_off.mask & reg->var_off.value) & val)
8090 return 1;
8091 if (!((reg->var_off.mask | reg->var_off.value) & val))
8092 return 0;
8093 break;
4f7b3e82
AS
8094 case BPF_JGT:
8095 if (reg->umin_value > val)
8096 return 1;
8097 else if (reg->umax_value <= val)
8098 return 0;
8099 break;
8100 case BPF_JSGT:
a72dafaf 8101 if (reg->smin_value > sval)
4f7b3e82 8102 return 1;
ee114dd6 8103 else if (reg->smax_value <= sval)
4f7b3e82
AS
8104 return 0;
8105 break;
8106 case BPF_JLT:
8107 if (reg->umax_value < val)
8108 return 1;
8109 else if (reg->umin_value >= val)
8110 return 0;
8111 break;
8112 case BPF_JSLT:
a72dafaf 8113 if (reg->smax_value < sval)
4f7b3e82 8114 return 1;
a72dafaf 8115 else if (reg->smin_value >= sval)
4f7b3e82
AS
8116 return 0;
8117 break;
8118 case BPF_JGE:
8119 if (reg->umin_value >= val)
8120 return 1;
8121 else if (reg->umax_value < val)
8122 return 0;
8123 break;
8124 case BPF_JSGE:
a72dafaf 8125 if (reg->smin_value >= sval)
4f7b3e82 8126 return 1;
a72dafaf 8127 else if (reg->smax_value < sval)
4f7b3e82
AS
8128 return 0;
8129 break;
8130 case BPF_JLE:
8131 if (reg->umax_value <= val)
8132 return 1;
8133 else if (reg->umin_value > val)
8134 return 0;
8135 break;
8136 case BPF_JSLE:
a72dafaf 8137 if (reg->smax_value <= sval)
4f7b3e82 8138 return 1;
a72dafaf 8139 else if (reg->smin_value > sval)
4f7b3e82
AS
8140 return 0;
8141 break;
8142 }
8143
8144 return -1;
8145}
8146
3f50f132
JF
8147/* compute branch direction of the expression "if (reg opcode val) goto target;"
8148 * and return:
8149 * 1 - branch will be taken and "goto target" will be executed
8150 * 0 - branch will not be taken and fall-through to next insn
8151 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8152 * range [0,10]
604dca5e 8153 */
3f50f132
JF
8154static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8155 bool is_jmp32)
604dca5e 8156{
cac616db
JF
8157 if (__is_pointer_value(false, reg)) {
8158 if (!reg_type_not_null(reg->type))
8159 return -1;
8160
8161 /* If pointer is valid tests against zero will fail so we can
8162 * use this to direct branch taken.
8163 */
8164 if (val != 0)
8165 return -1;
8166
8167 switch (opcode) {
8168 case BPF_JEQ:
8169 return 0;
8170 case BPF_JNE:
8171 return 1;
8172 default:
8173 return -1;
8174 }
8175 }
604dca5e 8176
3f50f132
JF
8177 if (is_jmp32)
8178 return is_branch32_taken(reg, val, opcode);
8179 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
8180}
8181
6d94e741
AS
8182static int flip_opcode(u32 opcode)
8183{
8184 /* How can we transform "a <op> b" into "b <op> a"? */
8185 static const u8 opcode_flip[16] = {
8186 /* these stay the same */
8187 [BPF_JEQ >> 4] = BPF_JEQ,
8188 [BPF_JNE >> 4] = BPF_JNE,
8189 [BPF_JSET >> 4] = BPF_JSET,
8190 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8191 [BPF_JGE >> 4] = BPF_JLE,
8192 [BPF_JGT >> 4] = BPF_JLT,
8193 [BPF_JLE >> 4] = BPF_JGE,
8194 [BPF_JLT >> 4] = BPF_JGT,
8195 [BPF_JSGE >> 4] = BPF_JSLE,
8196 [BPF_JSGT >> 4] = BPF_JSLT,
8197 [BPF_JSLE >> 4] = BPF_JSGE,
8198 [BPF_JSLT >> 4] = BPF_JSGT
8199 };
8200 return opcode_flip[opcode >> 4];
8201}
8202
8203static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8204 struct bpf_reg_state *src_reg,
8205 u8 opcode)
8206{
8207 struct bpf_reg_state *pkt;
8208
8209 if (src_reg->type == PTR_TO_PACKET_END) {
8210 pkt = dst_reg;
8211 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8212 pkt = src_reg;
8213 opcode = flip_opcode(opcode);
8214 } else {
8215 return -1;
8216 }
8217
8218 if (pkt->range >= 0)
8219 return -1;
8220
8221 switch (opcode) {
8222 case BPF_JLE:
8223 /* pkt <= pkt_end */
8224 fallthrough;
8225 case BPF_JGT:
8226 /* pkt > pkt_end */
8227 if (pkt->range == BEYOND_PKT_END)
8228 /* pkt has at last one extra byte beyond pkt_end */
8229 return opcode == BPF_JGT;
8230 break;
8231 case BPF_JLT:
8232 /* pkt < pkt_end */
8233 fallthrough;
8234 case BPF_JGE:
8235 /* pkt >= pkt_end */
8236 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8237 return opcode == BPF_JGE;
8238 break;
8239 }
8240 return -1;
8241}
8242
48461135
JB
8243/* Adjusts the register min/max values in the case that the dst_reg is the
8244 * variable register that we are working on, and src_reg is a constant or we're
8245 * simply doing a BPF_K check.
f1174f77 8246 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
8247 */
8248static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
8249 struct bpf_reg_state *false_reg,
8250 u64 val, u32 val32,
092ed096 8251 u8 opcode, bool is_jmp32)
48461135 8252{
3f50f132
JF
8253 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8254 struct tnum false_64off = false_reg->var_off;
8255 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8256 struct tnum true_64off = true_reg->var_off;
8257 s64 sval = (s64)val;
8258 s32 sval32 = (s32)val32;
a72dafaf 8259
f1174f77
EC
8260 /* If the dst_reg is a pointer, we can't learn anything about its
8261 * variable offset from the compare (unless src_reg were a pointer into
8262 * the same object, but we don't bother with that.
8263 * Since false_reg and true_reg have the same type by construction, we
8264 * only need to check one of them for pointerness.
8265 */
8266 if (__is_pointer_value(false, false_reg))
8267 return;
4cabc5b1 8268
48461135
JB
8269 switch (opcode) {
8270 case BPF_JEQ:
48461135 8271 case BPF_JNE:
a72dafaf
JW
8272 {
8273 struct bpf_reg_state *reg =
8274 opcode == BPF_JEQ ? true_reg : false_reg;
8275
e688c3db
AS
8276 /* JEQ/JNE comparison doesn't change the register equivalence.
8277 * r1 = r2;
8278 * if (r1 == 42) goto label;
8279 * ...
8280 * label: // here both r1 and r2 are known to be 42.
8281 *
8282 * Hence when marking register as known preserve it's ID.
48461135 8283 */
3f50f132
JF
8284 if (is_jmp32)
8285 __mark_reg32_known(reg, val32);
8286 else
e688c3db 8287 ___mark_reg_known(reg, val);
48461135 8288 break;
a72dafaf 8289 }
960ea056 8290 case BPF_JSET:
3f50f132
JF
8291 if (is_jmp32) {
8292 false_32off = tnum_and(false_32off, tnum_const(~val32));
8293 if (is_power_of_2(val32))
8294 true_32off = tnum_or(true_32off,
8295 tnum_const(val32));
8296 } else {
8297 false_64off = tnum_and(false_64off, tnum_const(~val));
8298 if (is_power_of_2(val))
8299 true_64off = tnum_or(true_64off,
8300 tnum_const(val));
8301 }
960ea056 8302 break;
48461135 8303 case BPF_JGE:
a72dafaf
JW
8304 case BPF_JGT:
8305 {
3f50f132
JF
8306 if (is_jmp32) {
8307 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8308 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8309
8310 false_reg->u32_max_value = min(false_reg->u32_max_value,
8311 false_umax);
8312 true_reg->u32_min_value = max(true_reg->u32_min_value,
8313 true_umin);
8314 } else {
8315 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8316 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8317
8318 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8319 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8320 }
b03c9f9f 8321 break;
a72dafaf 8322 }
48461135 8323 case BPF_JSGE:
a72dafaf
JW
8324 case BPF_JSGT:
8325 {
3f50f132
JF
8326 if (is_jmp32) {
8327 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8328 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 8329
3f50f132
JF
8330 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8331 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8332 } else {
8333 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8334 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8335
8336 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8337 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8338 }
48461135 8339 break;
a72dafaf 8340 }
b4e432f1 8341 case BPF_JLE:
a72dafaf
JW
8342 case BPF_JLT:
8343 {
3f50f132
JF
8344 if (is_jmp32) {
8345 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8346 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8347
8348 false_reg->u32_min_value = max(false_reg->u32_min_value,
8349 false_umin);
8350 true_reg->u32_max_value = min(true_reg->u32_max_value,
8351 true_umax);
8352 } else {
8353 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8354 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8355
8356 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8357 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8358 }
b4e432f1 8359 break;
a72dafaf 8360 }
b4e432f1 8361 case BPF_JSLE:
a72dafaf
JW
8362 case BPF_JSLT:
8363 {
3f50f132
JF
8364 if (is_jmp32) {
8365 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8366 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 8367
3f50f132
JF
8368 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8369 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8370 } else {
8371 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8372 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8373
8374 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8375 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8376 }
b4e432f1 8377 break;
a72dafaf 8378 }
48461135 8379 default:
0fc31b10 8380 return;
48461135
JB
8381 }
8382
3f50f132
JF
8383 if (is_jmp32) {
8384 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8385 tnum_subreg(false_32off));
8386 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8387 tnum_subreg(true_32off));
8388 __reg_combine_32_into_64(false_reg);
8389 __reg_combine_32_into_64(true_reg);
8390 } else {
8391 false_reg->var_off = false_64off;
8392 true_reg->var_off = true_64off;
8393 __reg_combine_64_into_32(false_reg);
8394 __reg_combine_64_into_32(true_reg);
8395 }
48461135
JB
8396}
8397
f1174f77
EC
8398/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8399 * the variable reg.
48461135
JB
8400 */
8401static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
8402 struct bpf_reg_state *false_reg,
8403 u64 val, u32 val32,
092ed096 8404 u8 opcode, bool is_jmp32)
48461135 8405{
6d94e741 8406 opcode = flip_opcode(opcode);
0fc31b10
JH
8407 /* This uses zero as "not present in table"; luckily the zero opcode,
8408 * BPF_JA, can't get here.
b03c9f9f 8409 */
0fc31b10 8410 if (opcode)
3f50f132 8411 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
8412}
8413
8414/* Regs are known to be equal, so intersect their min/max/var_off */
8415static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8416 struct bpf_reg_state *dst_reg)
8417{
b03c9f9f
EC
8418 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8419 dst_reg->umin_value);
8420 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8421 dst_reg->umax_value);
8422 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8423 dst_reg->smin_value);
8424 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8425 dst_reg->smax_value);
f1174f77
EC
8426 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8427 dst_reg->var_off);
b03c9f9f
EC
8428 /* We might have learned new bounds from the var_off. */
8429 __update_reg_bounds(src_reg);
8430 __update_reg_bounds(dst_reg);
8431 /* We might have learned something about the sign bit. */
8432 __reg_deduce_bounds(src_reg);
8433 __reg_deduce_bounds(dst_reg);
8434 /* We might have learned some bits from the bounds. */
8435 __reg_bound_offset(src_reg);
8436 __reg_bound_offset(dst_reg);
8437 /* Intersecting with the old var_off might have improved our bounds
8438 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8439 * then new var_off is (0; 0x7f...fc) which improves our umax.
8440 */
8441 __update_reg_bounds(src_reg);
8442 __update_reg_bounds(dst_reg);
f1174f77
EC
8443}
8444
8445static void reg_combine_min_max(struct bpf_reg_state *true_src,
8446 struct bpf_reg_state *true_dst,
8447 struct bpf_reg_state *false_src,
8448 struct bpf_reg_state *false_dst,
8449 u8 opcode)
8450{
8451 switch (opcode) {
8452 case BPF_JEQ:
8453 __reg_combine_min_max(true_src, true_dst);
8454 break;
8455 case BPF_JNE:
8456 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 8457 break;
4cabc5b1 8458 }
48461135
JB
8459}
8460
fd978bf7
JS
8461static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8462 struct bpf_reg_state *reg, u32 id,
840b9615 8463 bool is_null)
57a09bf0 8464{
93c230e3
MKL
8465 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8466 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
8467 /* Old offset (both fixed and variable parts) should
8468 * have been known-zero, because we don't allow pointer
8469 * arithmetic on pointers that might be NULL.
8470 */
b03c9f9f
EC
8471 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8472 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 8473 reg->off)) {
b03c9f9f
EC
8474 __mark_reg_known_zero(reg);
8475 reg->off = 0;
f1174f77
EC
8476 }
8477 if (is_null) {
8478 reg->type = SCALAR_VALUE;
1b986589
MKL
8479 /* We don't need id and ref_obj_id from this point
8480 * onwards anymore, thus we should better reset it,
8481 * so that state pruning has chances to take effect.
8482 */
8483 reg->id = 0;
8484 reg->ref_obj_id = 0;
4ddb7416
DB
8485
8486 return;
8487 }
8488
8489 mark_ptr_not_null_reg(reg);
8490
8491 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
8492 /* For not-NULL ptr, reg->ref_obj_id will be reset
8493 * in release_reg_references().
8494 *
8495 * reg->id is still used by spin_lock ptr. Other
8496 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
8497 */
8498 reg->id = 0;
56f668df 8499 }
57a09bf0
TG
8500 }
8501}
8502
c6a9efa1
PC
8503static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8504 bool is_null)
8505{
8506 struct bpf_reg_state *reg;
8507 int i;
8508
8509 for (i = 0; i < MAX_BPF_REG; i++)
8510 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8511
8512 bpf_for_each_spilled_reg(i, state, reg) {
8513 if (!reg)
8514 continue;
8515 mark_ptr_or_null_reg(state, reg, id, is_null);
8516 }
8517}
8518
57a09bf0
TG
8519/* The logic is similar to find_good_pkt_pointers(), both could eventually
8520 * be folded together at some point.
8521 */
840b9615
JS
8522static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8523 bool is_null)
57a09bf0 8524{
f4d7e40a 8525 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 8526 struct bpf_reg_state *regs = state->regs;
1b986589 8527 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 8528 u32 id = regs[regno].id;
c6a9efa1 8529 int i;
57a09bf0 8530
1b986589
MKL
8531 if (ref_obj_id && ref_obj_id == id && is_null)
8532 /* regs[regno] is in the " == NULL" branch.
8533 * No one could have freed the reference state before
8534 * doing the NULL check.
8535 */
8536 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 8537
c6a9efa1
PC
8538 for (i = 0; i <= vstate->curframe; i++)
8539 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
8540}
8541
5beca081
DB
8542static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8543 struct bpf_reg_state *dst_reg,
8544 struct bpf_reg_state *src_reg,
8545 struct bpf_verifier_state *this_branch,
8546 struct bpf_verifier_state *other_branch)
8547{
8548 if (BPF_SRC(insn->code) != BPF_X)
8549 return false;
8550
092ed096
JW
8551 /* Pointers are always 64-bit. */
8552 if (BPF_CLASS(insn->code) == BPF_JMP32)
8553 return false;
8554
5beca081
DB
8555 switch (BPF_OP(insn->code)) {
8556 case BPF_JGT:
8557 if ((dst_reg->type == PTR_TO_PACKET &&
8558 src_reg->type == PTR_TO_PACKET_END) ||
8559 (dst_reg->type == PTR_TO_PACKET_META &&
8560 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8561 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8562 find_good_pkt_pointers(this_branch, dst_reg,
8563 dst_reg->type, false);
6d94e741 8564 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
8565 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8566 src_reg->type == PTR_TO_PACKET) ||
8567 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8568 src_reg->type == PTR_TO_PACKET_META)) {
8569 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8570 find_good_pkt_pointers(other_branch, src_reg,
8571 src_reg->type, true);
6d94e741 8572 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
8573 } else {
8574 return false;
8575 }
8576 break;
8577 case BPF_JLT:
8578 if ((dst_reg->type == PTR_TO_PACKET &&
8579 src_reg->type == PTR_TO_PACKET_END) ||
8580 (dst_reg->type == PTR_TO_PACKET_META &&
8581 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8582 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8583 find_good_pkt_pointers(other_branch, dst_reg,
8584 dst_reg->type, true);
6d94e741 8585 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
8586 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8587 src_reg->type == PTR_TO_PACKET) ||
8588 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8589 src_reg->type == PTR_TO_PACKET_META)) {
8590 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8591 find_good_pkt_pointers(this_branch, src_reg,
8592 src_reg->type, false);
6d94e741 8593 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
8594 } else {
8595 return false;
8596 }
8597 break;
8598 case BPF_JGE:
8599 if ((dst_reg->type == PTR_TO_PACKET &&
8600 src_reg->type == PTR_TO_PACKET_END) ||
8601 (dst_reg->type == PTR_TO_PACKET_META &&
8602 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8603 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8604 find_good_pkt_pointers(this_branch, dst_reg,
8605 dst_reg->type, true);
6d94e741 8606 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
8607 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8608 src_reg->type == PTR_TO_PACKET) ||
8609 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8610 src_reg->type == PTR_TO_PACKET_META)) {
8611 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8612 find_good_pkt_pointers(other_branch, src_reg,
8613 src_reg->type, false);
6d94e741 8614 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
8615 } else {
8616 return false;
8617 }
8618 break;
8619 case BPF_JLE:
8620 if ((dst_reg->type == PTR_TO_PACKET &&
8621 src_reg->type == PTR_TO_PACKET_END) ||
8622 (dst_reg->type == PTR_TO_PACKET_META &&
8623 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8624 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8625 find_good_pkt_pointers(other_branch, dst_reg,
8626 dst_reg->type, false);
6d94e741 8627 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
8628 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8629 src_reg->type == PTR_TO_PACKET) ||
8630 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8631 src_reg->type == PTR_TO_PACKET_META)) {
8632 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8633 find_good_pkt_pointers(this_branch, src_reg,
8634 src_reg->type, true);
6d94e741 8635 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
8636 } else {
8637 return false;
8638 }
8639 break;
8640 default:
8641 return false;
8642 }
8643
8644 return true;
8645}
8646
75748837
AS
8647static void find_equal_scalars(struct bpf_verifier_state *vstate,
8648 struct bpf_reg_state *known_reg)
8649{
8650 struct bpf_func_state *state;
8651 struct bpf_reg_state *reg;
8652 int i, j;
8653
8654 for (i = 0; i <= vstate->curframe; i++) {
8655 state = vstate->frame[i];
8656 for (j = 0; j < MAX_BPF_REG; j++) {
8657 reg = &state->regs[j];
8658 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8659 *reg = *known_reg;
8660 }
8661
8662 bpf_for_each_spilled_reg(j, state, reg) {
8663 if (!reg)
8664 continue;
8665 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8666 *reg = *known_reg;
8667 }
8668 }
8669}
8670
58e2af8b 8671static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8672 struct bpf_insn *insn, int *insn_idx)
8673{
f4d7e40a
AS
8674 struct bpf_verifier_state *this_branch = env->cur_state;
8675 struct bpf_verifier_state *other_branch;
8676 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8677 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8678 u8 opcode = BPF_OP(insn->code);
092ed096 8679 bool is_jmp32;
fb8d251e 8680 int pred = -1;
17a52670
AS
8681 int err;
8682
092ed096
JW
8683 /* Only conditional jumps are expected to reach here. */
8684 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8685 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8686 return -EINVAL;
8687 }
8688
8689 if (BPF_SRC(insn->code) == BPF_X) {
8690 if (insn->imm != 0) {
092ed096 8691 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8692 return -EINVAL;
8693 }
8694
8695 /* check src1 operand */
dc503a8a 8696 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8697 if (err)
8698 return err;
1be7f75d
AS
8699
8700 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8701 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8702 insn->src_reg);
8703 return -EACCES;
8704 }
fb8d251e 8705 src_reg = &regs[insn->src_reg];
17a52670
AS
8706 } else {
8707 if (insn->src_reg != BPF_REG_0) {
092ed096 8708 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8709 return -EINVAL;
8710 }
8711 }
8712
8713 /* check src2 operand */
dc503a8a 8714 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8715 if (err)
8716 return err;
8717
1a0dc1ac 8718 dst_reg = &regs[insn->dst_reg];
092ed096 8719 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8720
3f50f132
JF
8721 if (BPF_SRC(insn->code) == BPF_K) {
8722 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8723 } else if (src_reg->type == SCALAR_VALUE &&
8724 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8725 pred = is_branch_taken(dst_reg,
8726 tnum_subreg(src_reg->var_off).value,
8727 opcode,
8728 is_jmp32);
8729 } else if (src_reg->type == SCALAR_VALUE &&
8730 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8731 pred = is_branch_taken(dst_reg,
8732 src_reg->var_off.value,
8733 opcode,
8734 is_jmp32);
6d94e741
AS
8735 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8736 reg_is_pkt_pointer_any(src_reg) &&
8737 !is_jmp32) {
8738 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8739 }
8740
b5dc0163 8741 if (pred >= 0) {
cac616db
JF
8742 /* If we get here with a dst_reg pointer type it is because
8743 * above is_branch_taken() special cased the 0 comparison.
8744 */
8745 if (!__is_pointer_value(false, dst_reg))
8746 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8747 if (BPF_SRC(insn->code) == BPF_X && !err &&
8748 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8749 err = mark_chain_precision(env, insn->src_reg);
8750 if (err)
8751 return err;
8752 }
fb8d251e
AS
8753 if (pred == 1) {
8754 /* only follow the goto, ignore fall-through */
8755 *insn_idx += insn->off;
8756 return 0;
8757 } else if (pred == 0) {
8758 /* only follow fall-through branch, since
8759 * that's where the program will go
8760 */
8761 return 0;
17a52670
AS
8762 }
8763
979d63d5
DB
8764 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8765 false);
17a52670
AS
8766 if (!other_branch)
8767 return -EFAULT;
f4d7e40a 8768 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8769
48461135
JB
8770 /* detect if we are comparing against a constant value so we can adjust
8771 * our min/max values for our dst register.
f1174f77
EC
8772 * this is only legit if both are scalars (or pointers to the same
8773 * object, I suppose, but we don't support that right now), because
8774 * otherwise the different base pointers mean the offsets aren't
8775 * comparable.
48461135
JB
8776 */
8777 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8778 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8779
f1174f77 8780 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8781 src_reg->type == SCALAR_VALUE) {
8782 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8783 (is_jmp32 &&
8784 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8785 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8786 dst_reg,
3f50f132
JF
8787 src_reg->var_off.value,
8788 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8789 opcode, is_jmp32);
8790 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8791 (is_jmp32 &&
8792 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8793 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8794 src_reg,
3f50f132
JF
8795 dst_reg->var_off.value,
8796 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8797 opcode, is_jmp32);
8798 else if (!is_jmp32 &&
8799 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8800 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8801 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8802 &other_branch_regs[insn->dst_reg],
092ed096 8803 src_reg, dst_reg, opcode);
e688c3db
AS
8804 if (src_reg->id &&
8805 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8806 find_equal_scalars(this_branch, src_reg);
8807 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8808 }
8809
f1174f77
EC
8810 }
8811 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8812 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8813 dst_reg, insn->imm, (u32)insn->imm,
8814 opcode, is_jmp32);
48461135
JB
8815 }
8816
e688c3db
AS
8817 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8818 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8819 find_equal_scalars(this_branch, dst_reg);
8820 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8821 }
8822
092ed096
JW
8823 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8824 * NOTE: these optimizations below are related with pointer comparison
8825 * which will never be JMP32.
8826 */
8827 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8828 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8829 reg_type_may_be_null(dst_reg->type)) {
8830 /* Mark all identical registers in each branch as either
57a09bf0
TG
8831 * safe or unknown depending R == 0 or R != 0 conditional.
8832 */
840b9615
JS
8833 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8834 opcode == BPF_JNE);
8835 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8836 opcode == BPF_JEQ);
5beca081
DB
8837 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8838 this_branch, other_branch) &&
8839 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8840 verbose(env, "R%d pointer comparison prohibited\n",
8841 insn->dst_reg);
1be7f75d 8842 return -EACCES;
17a52670 8843 }
06ee7115 8844 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8845 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8846 return 0;
8847}
8848
17a52670 8849/* verify BPF_LD_IMM64 instruction */
58e2af8b 8850static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8851{
d8eca5bb 8852 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8853 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8854 struct bpf_reg_state *dst_reg;
d8eca5bb 8855 struct bpf_map *map;
17a52670
AS
8856 int err;
8857
8858 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8859 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8860 return -EINVAL;
8861 }
8862 if (insn->off != 0) {
61bd5218 8863 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8864 return -EINVAL;
8865 }
8866
dc503a8a 8867 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8868 if (err)
8869 return err;
8870
4976b718 8871 dst_reg = &regs[insn->dst_reg];
6b173873 8872 if (insn->src_reg == 0) {
6b173873
JK
8873 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8874
4976b718 8875 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8876 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8877 return 0;
6b173873 8878 }
17a52670 8879
4976b718
HL
8880 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8881 mark_reg_known_zero(env, regs, insn->dst_reg);
8882
8883 dst_reg->type = aux->btf_var.reg_type;
8884 switch (dst_reg->type) {
8885 case PTR_TO_MEM:
8886 dst_reg->mem_size = aux->btf_var.mem_size;
8887 break;
8888 case PTR_TO_BTF_ID:
eaa6bcb7 8889 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8890 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8891 dst_reg->btf_id = aux->btf_var.btf_id;
8892 break;
8893 default:
8894 verbose(env, "bpf verifier is misconfigured\n");
8895 return -EFAULT;
8896 }
8897 return 0;
8898 }
8899
69c087ba
YS
8900 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8901 struct bpf_prog_aux *aux = env->prog->aux;
8902 u32 subprogno = insn[1].imm;
8903
8904 if (!aux->func_info) {
8905 verbose(env, "missing btf func_info\n");
8906 return -EINVAL;
8907 }
8908 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8909 verbose(env, "callback function not static\n");
8910 return -EINVAL;
8911 }
8912
8913 dst_reg->type = PTR_TO_FUNC;
8914 dst_reg->subprogno = subprogno;
8915 return 0;
8916 }
8917
d8eca5bb
DB
8918 map = env->used_maps[aux->map_index];
8919 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8920 dst_reg->map_ptr = map;
d8eca5bb
DB
8921
8922 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
8923 dst_reg->type = PTR_TO_MAP_VALUE;
8924 dst_reg->off = aux->map_off;
d8eca5bb 8925 if (map_value_has_spin_lock(map))
4976b718 8926 dst_reg->id = ++env->id_gen;
d8eca5bb 8927 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 8928 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8929 } else {
8930 verbose(env, "bpf verifier is misconfigured\n");
8931 return -EINVAL;
8932 }
17a52670 8933
17a52670
AS
8934 return 0;
8935}
8936
96be4325
DB
8937static bool may_access_skb(enum bpf_prog_type type)
8938{
8939 switch (type) {
8940 case BPF_PROG_TYPE_SOCKET_FILTER:
8941 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 8942 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
8943 return true;
8944 default:
8945 return false;
8946 }
8947}
8948
ddd872bc
AS
8949/* verify safety of LD_ABS|LD_IND instructions:
8950 * - they can only appear in the programs where ctx == skb
8951 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8952 * preserve R6-R9, and store return value into R0
8953 *
8954 * Implicit input:
8955 * ctx == skb == R6 == CTX
8956 *
8957 * Explicit input:
8958 * SRC == any register
8959 * IMM == 32-bit immediate
8960 *
8961 * Output:
8962 * R0 - 8/16/32-bit skb data converted to cpu endianness
8963 */
58e2af8b 8964static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 8965{
638f5b90 8966 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 8967 static const int ctx_reg = BPF_REG_6;
ddd872bc 8968 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
8969 int i, err;
8970
7e40781c 8971 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 8972 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
8973 return -EINVAL;
8974 }
8975
e0cea7ce
DB
8976 if (!env->ops->gen_ld_abs) {
8977 verbose(env, "bpf verifier is misconfigured\n");
8978 return -EINVAL;
8979 }
8980
ddd872bc 8981 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 8982 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 8983 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 8984 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
8985 return -EINVAL;
8986 }
8987
8988 /* check whether implicit source operand (register R6) is readable */
6d4f151a 8989 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
8990 if (err)
8991 return err;
8992
fd978bf7
JS
8993 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8994 * gen_ld_abs() may terminate the program at runtime, leading to
8995 * reference leak.
8996 */
8997 err = check_reference_leak(env);
8998 if (err) {
8999 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9000 return err;
9001 }
9002
d83525ca
AS
9003 if (env->cur_state->active_spin_lock) {
9004 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9005 return -EINVAL;
9006 }
9007
6d4f151a 9008 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
9009 verbose(env,
9010 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
9011 return -EINVAL;
9012 }
9013
9014 if (mode == BPF_IND) {
9015 /* check explicit source operand */
dc503a8a 9016 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
9017 if (err)
9018 return err;
9019 }
9020
6d4f151a
DB
9021 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9022 if (err < 0)
9023 return err;
9024
ddd872bc 9025 /* reset caller saved regs to unreadable */
dc503a8a 9026 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 9027 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
9028 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9029 }
ddd872bc
AS
9030
9031 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
9032 * the value fetched from the packet.
9033 * Already marked as written above.
ddd872bc 9034 */
61bd5218 9035 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
9036 /* ld_abs load up to 32-bit skb data. */
9037 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
9038 return 0;
9039}
9040
390ee7e2
AS
9041static int check_return_code(struct bpf_verifier_env *env)
9042{
5cf1e914 9043 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 9044 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
9045 struct bpf_reg_state *reg;
9046 struct tnum range = tnum_range(0, 1);
7e40781c 9047 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 9048 int err;
f782e2c3 9049 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 9050
9e4e01df 9051 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
9052 if (!is_subprog &&
9053 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 9054 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
9055 !prog->aux->attach_func_proto->type)
9056 return 0;
9057
9058 /* eBPF calling convetion is such that R0 is used
9059 * to return the value from eBPF program.
9060 * Make sure that it's readable at this time
9061 * of bpf_exit, which means that program wrote
9062 * something into it earlier
9063 */
9064 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9065 if (err)
9066 return err;
9067
9068 if (is_pointer_value(env, BPF_REG_0)) {
9069 verbose(env, "R0 leaks addr as return value\n");
9070 return -EACCES;
9071 }
390ee7e2 9072
f782e2c3
DB
9073 reg = cur_regs(env) + BPF_REG_0;
9074 if (is_subprog) {
9075 if (reg->type != SCALAR_VALUE) {
9076 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9077 reg_type_str[reg->type]);
9078 return -EINVAL;
9079 }
9080 return 0;
9081 }
9082
7e40781c 9083 switch (prog_type) {
983695fa
DB
9084 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9085 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
9086 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9087 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9088 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9089 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9090 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 9091 range = tnum_range(1, 1);
77241217
SF
9092 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9093 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9094 range = tnum_range(0, 3);
ed4ed404 9095 break;
390ee7e2 9096 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 9097 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9098 range = tnum_range(0, 3);
9099 enforce_attach_type_range = tnum_range(2, 3);
9100 }
ed4ed404 9101 break;
390ee7e2
AS
9102 case BPF_PROG_TYPE_CGROUP_SOCK:
9103 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 9104 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 9105 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 9106 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 9107 break;
15ab09bd
AS
9108 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9109 if (!env->prog->aux->attach_btf_id)
9110 return 0;
9111 range = tnum_const(0);
9112 break;
15d83c4d 9113 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
9114 switch (env->prog->expected_attach_type) {
9115 case BPF_TRACE_FENTRY:
9116 case BPF_TRACE_FEXIT:
9117 range = tnum_const(0);
9118 break;
9119 case BPF_TRACE_RAW_TP:
9120 case BPF_MODIFY_RETURN:
15d83c4d 9121 return 0;
2ec0616e
DB
9122 case BPF_TRACE_ITER:
9123 break;
e92888c7
YS
9124 default:
9125 return -ENOTSUPP;
9126 }
15d83c4d 9127 break;
e9ddbb77
JS
9128 case BPF_PROG_TYPE_SK_LOOKUP:
9129 range = tnum_range(SK_DROP, SK_PASS);
9130 break;
e92888c7
YS
9131 case BPF_PROG_TYPE_EXT:
9132 /* freplace program can return anything as its return value
9133 * depends on the to-be-replaced kernel func or bpf program.
9134 */
390ee7e2
AS
9135 default:
9136 return 0;
9137 }
9138
390ee7e2 9139 if (reg->type != SCALAR_VALUE) {
61bd5218 9140 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
9141 reg_type_str[reg->type]);
9142 return -EINVAL;
9143 }
9144
9145 if (!tnum_in(range, reg->var_off)) {
bc2591d6 9146 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
9147 return -EINVAL;
9148 }
5cf1e914 9149
9150 if (!tnum_is_unknown(enforce_attach_type_range) &&
9151 tnum_in(enforce_attach_type_range, reg->var_off))
9152 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
9153 return 0;
9154}
9155
475fb78f
AS
9156/* non-recursive DFS pseudo code
9157 * 1 procedure DFS-iterative(G,v):
9158 * 2 label v as discovered
9159 * 3 let S be a stack
9160 * 4 S.push(v)
9161 * 5 while S is not empty
9162 * 6 t <- S.pop()
9163 * 7 if t is what we're looking for:
9164 * 8 return t
9165 * 9 for all edges e in G.adjacentEdges(t) do
9166 * 10 if edge e is already labelled
9167 * 11 continue with the next edge
9168 * 12 w <- G.adjacentVertex(t,e)
9169 * 13 if vertex w is not discovered and not explored
9170 * 14 label e as tree-edge
9171 * 15 label w as discovered
9172 * 16 S.push(w)
9173 * 17 continue at 5
9174 * 18 else if vertex w is discovered
9175 * 19 label e as back-edge
9176 * 20 else
9177 * 21 // vertex w is explored
9178 * 22 label e as forward- or cross-edge
9179 * 23 label t as explored
9180 * 24 S.pop()
9181 *
9182 * convention:
9183 * 0x10 - discovered
9184 * 0x11 - discovered and fall-through edge labelled
9185 * 0x12 - discovered and fall-through and branch edges labelled
9186 * 0x20 - explored
9187 */
9188
9189enum {
9190 DISCOVERED = 0x10,
9191 EXPLORED = 0x20,
9192 FALLTHROUGH = 1,
9193 BRANCH = 2,
9194};
9195
dc2a4ebc
AS
9196static u32 state_htab_size(struct bpf_verifier_env *env)
9197{
9198 return env->prog->len;
9199}
9200
5d839021
AS
9201static struct bpf_verifier_state_list **explored_state(
9202 struct bpf_verifier_env *env,
9203 int idx)
9204{
dc2a4ebc
AS
9205 struct bpf_verifier_state *cur = env->cur_state;
9206 struct bpf_func_state *state = cur->frame[cur->curframe];
9207
9208 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
9209}
9210
9211static void init_explored_state(struct bpf_verifier_env *env, int idx)
9212{
a8f500af 9213 env->insn_aux_data[idx].prune_point = true;
5d839021 9214}
f1bca824 9215
59e2e27d
WAF
9216enum {
9217 DONE_EXPLORING = 0,
9218 KEEP_EXPLORING = 1,
9219};
9220
475fb78f
AS
9221/* t, w, e - match pseudo-code above:
9222 * t - index of current instruction
9223 * w - next instruction
9224 * e - edge
9225 */
2589726d
AS
9226static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9227 bool loop_ok)
475fb78f 9228{
7df737e9
AS
9229 int *insn_stack = env->cfg.insn_stack;
9230 int *insn_state = env->cfg.insn_state;
9231
475fb78f 9232 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 9233 return DONE_EXPLORING;
475fb78f
AS
9234
9235 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 9236 return DONE_EXPLORING;
475fb78f
AS
9237
9238 if (w < 0 || w >= env->prog->len) {
d9762e84 9239 verbose_linfo(env, t, "%d: ", t);
61bd5218 9240 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
9241 return -EINVAL;
9242 }
9243
f1bca824
AS
9244 if (e == BRANCH)
9245 /* mark branch target for state pruning */
5d839021 9246 init_explored_state(env, w);
f1bca824 9247
475fb78f
AS
9248 if (insn_state[w] == 0) {
9249 /* tree-edge */
9250 insn_state[t] = DISCOVERED | e;
9251 insn_state[w] = DISCOVERED;
7df737e9 9252 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 9253 return -E2BIG;
7df737e9 9254 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 9255 return KEEP_EXPLORING;
475fb78f 9256 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 9257 if (loop_ok && env->bpf_capable)
59e2e27d 9258 return DONE_EXPLORING;
d9762e84
MKL
9259 verbose_linfo(env, t, "%d: ", t);
9260 verbose_linfo(env, w, "%d: ", w);
61bd5218 9261 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
9262 return -EINVAL;
9263 } else if (insn_state[w] == EXPLORED) {
9264 /* forward- or cross-edge */
9265 insn_state[t] = DISCOVERED | e;
9266 } else {
61bd5218 9267 verbose(env, "insn state internal bug\n");
475fb78f
AS
9268 return -EFAULT;
9269 }
59e2e27d
WAF
9270 return DONE_EXPLORING;
9271}
9272
efdb22de
YS
9273static int visit_func_call_insn(int t, int insn_cnt,
9274 struct bpf_insn *insns,
9275 struct bpf_verifier_env *env,
9276 bool visit_callee)
9277{
9278 int ret;
9279
9280 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9281 if (ret)
9282 return ret;
9283
9284 if (t + 1 < insn_cnt)
9285 init_explored_state(env, t + 1);
9286 if (visit_callee) {
9287 init_explored_state(env, t);
9288 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9289 env, false);
9290 }
9291 return ret;
9292}
9293
59e2e27d
WAF
9294/* Visits the instruction at index t and returns one of the following:
9295 * < 0 - an error occurred
9296 * DONE_EXPLORING - the instruction was fully explored
9297 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9298 */
9299static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9300{
9301 struct bpf_insn *insns = env->prog->insnsi;
9302 int ret;
9303
69c087ba
YS
9304 if (bpf_pseudo_func(insns + t))
9305 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9306
59e2e27d
WAF
9307 /* All non-branch instructions have a single fall-through edge. */
9308 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9309 BPF_CLASS(insns[t].code) != BPF_JMP32)
9310 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9311
9312 switch (BPF_OP(insns[t].code)) {
9313 case BPF_EXIT:
9314 return DONE_EXPLORING;
9315
9316 case BPF_CALL:
efdb22de
YS
9317 return visit_func_call_insn(t, insn_cnt, insns, env,
9318 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
9319
9320 case BPF_JA:
9321 if (BPF_SRC(insns[t].code) != BPF_K)
9322 return -EINVAL;
9323
9324 /* unconditional jump with single edge */
9325 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9326 true);
9327 if (ret)
9328 return ret;
9329
9330 /* unconditional jmp is not a good pruning point,
9331 * but it's marked, since backtracking needs
9332 * to record jmp history in is_state_visited().
9333 */
9334 init_explored_state(env, t + insns[t].off + 1);
9335 /* tell verifier to check for equivalent states
9336 * after every call and jump
9337 */
9338 if (t + 1 < insn_cnt)
9339 init_explored_state(env, t + 1);
9340
9341 return ret;
9342
9343 default:
9344 /* conditional jump with two edges */
9345 init_explored_state(env, t);
9346 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9347 if (ret)
9348 return ret;
9349
9350 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9351 }
475fb78f
AS
9352}
9353
9354/* non-recursive depth-first-search to detect loops in BPF program
9355 * loop == back-edge in directed graph
9356 */
58e2af8b 9357static int check_cfg(struct bpf_verifier_env *env)
475fb78f 9358{
475fb78f 9359 int insn_cnt = env->prog->len;
7df737e9 9360 int *insn_stack, *insn_state;
475fb78f 9361 int ret = 0;
59e2e27d 9362 int i;
475fb78f 9363
7df737e9 9364 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
9365 if (!insn_state)
9366 return -ENOMEM;
9367
7df737e9 9368 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 9369 if (!insn_stack) {
71dde681 9370 kvfree(insn_state);
475fb78f
AS
9371 return -ENOMEM;
9372 }
9373
9374 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9375 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 9376 env->cfg.cur_stack = 1;
475fb78f 9377
59e2e27d
WAF
9378 while (env->cfg.cur_stack > 0) {
9379 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 9380
59e2e27d
WAF
9381 ret = visit_insn(t, insn_cnt, env);
9382 switch (ret) {
9383 case DONE_EXPLORING:
9384 insn_state[t] = EXPLORED;
9385 env->cfg.cur_stack--;
9386 break;
9387 case KEEP_EXPLORING:
9388 break;
9389 default:
9390 if (ret > 0) {
9391 verbose(env, "visit_insn internal bug\n");
9392 ret = -EFAULT;
475fb78f 9393 }
475fb78f 9394 goto err_free;
59e2e27d 9395 }
475fb78f
AS
9396 }
9397
59e2e27d 9398 if (env->cfg.cur_stack < 0) {
61bd5218 9399 verbose(env, "pop stack internal bug\n");
475fb78f
AS
9400 ret = -EFAULT;
9401 goto err_free;
9402 }
475fb78f 9403
475fb78f
AS
9404 for (i = 0; i < insn_cnt; i++) {
9405 if (insn_state[i] != EXPLORED) {
61bd5218 9406 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
9407 ret = -EINVAL;
9408 goto err_free;
9409 }
9410 }
9411 ret = 0; /* cfg looks good */
9412
9413err_free:
71dde681
AS
9414 kvfree(insn_state);
9415 kvfree(insn_stack);
7df737e9 9416 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
9417 return ret;
9418}
9419
09b28d76
AS
9420static int check_abnormal_return(struct bpf_verifier_env *env)
9421{
9422 int i;
9423
9424 for (i = 1; i < env->subprog_cnt; i++) {
9425 if (env->subprog_info[i].has_ld_abs) {
9426 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9427 return -EINVAL;
9428 }
9429 if (env->subprog_info[i].has_tail_call) {
9430 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9431 return -EINVAL;
9432 }
9433 }
9434 return 0;
9435}
9436
838e9690
YS
9437/* The minimum supported BTF func info size */
9438#define MIN_BPF_FUNCINFO_SIZE 8
9439#define MAX_FUNCINFO_REC_SIZE 252
9440
c454a46b
MKL
9441static int check_btf_func(struct bpf_verifier_env *env,
9442 const union bpf_attr *attr,
9443 union bpf_attr __user *uattr)
838e9690 9444{
09b28d76 9445 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 9446 u32 i, nfuncs, urec_size, min_size;
838e9690 9447 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 9448 struct bpf_func_info *krecord;
8c1b6e69 9449 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
9450 struct bpf_prog *prog;
9451 const struct btf *btf;
838e9690 9452 void __user *urecord;
d0b2818e 9453 u32 prev_offset = 0;
09b28d76 9454 bool scalar_return;
e7ed83d6 9455 int ret = -ENOMEM;
838e9690
YS
9456
9457 nfuncs = attr->func_info_cnt;
09b28d76
AS
9458 if (!nfuncs) {
9459 if (check_abnormal_return(env))
9460 return -EINVAL;
838e9690 9461 return 0;
09b28d76 9462 }
838e9690
YS
9463
9464 if (nfuncs != env->subprog_cnt) {
9465 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9466 return -EINVAL;
9467 }
9468
9469 urec_size = attr->func_info_rec_size;
9470 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9471 urec_size > MAX_FUNCINFO_REC_SIZE ||
9472 urec_size % sizeof(u32)) {
9473 verbose(env, "invalid func info rec size %u\n", urec_size);
9474 return -EINVAL;
9475 }
9476
c454a46b
MKL
9477 prog = env->prog;
9478 btf = prog->aux->btf;
838e9690
YS
9479
9480 urecord = u64_to_user_ptr(attr->func_info);
9481 min_size = min_t(u32, krec_size, urec_size);
9482
ba64e7d8 9483 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
9484 if (!krecord)
9485 return -ENOMEM;
8c1b6e69
AS
9486 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9487 if (!info_aux)
9488 goto err_free;
ba64e7d8 9489
838e9690
YS
9490 for (i = 0; i < nfuncs; i++) {
9491 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9492 if (ret) {
9493 if (ret == -E2BIG) {
9494 verbose(env, "nonzero tailing record in func info");
9495 /* set the size kernel expects so loader can zero
9496 * out the rest of the record.
9497 */
9498 if (put_user(min_size, &uattr->func_info_rec_size))
9499 ret = -EFAULT;
9500 }
c454a46b 9501 goto err_free;
838e9690
YS
9502 }
9503
ba64e7d8 9504 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 9505 ret = -EFAULT;
c454a46b 9506 goto err_free;
838e9690
YS
9507 }
9508
d30d42e0 9509 /* check insn_off */
09b28d76 9510 ret = -EINVAL;
838e9690 9511 if (i == 0) {
d30d42e0 9512 if (krecord[i].insn_off) {
838e9690 9513 verbose(env,
d30d42e0
MKL
9514 "nonzero insn_off %u for the first func info record",
9515 krecord[i].insn_off);
c454a46b 9516 goto err_free;
838e9690 9517 }
d30d42e0 9518 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
9519 verbose(env,
9520 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 9521 krecord[i].insn_off, prev_offset);
c454a46b 9522 goto err_free;
838e9690
YS
9523 }
9524
d30d42e0 9525 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 9526 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 9527 goto err_free;
838e9690
YS
9528 }
9529
9530 /* check type_id */
ba64e7d8 9531 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 9532 if (!type || !btf_type_is_func(type)) {
838e9690 9533 verbose(env, "invalid type id %d in func info",
ba64e7d8 9534 krecord[i].type_id);
c454a46b 9535 goto err_free;
838e9690 9536 }
51c39bb1 9537 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
9538
9539 func_proto = btf_type_by_id(btf, type->type);
9540 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9541 /* btf_func_check() already verified it during BTF load */
9542 goto err_free;
9543 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9544 scalar_return =
9545 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9546 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9547 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9548 goto err_free;
9549 }
9550 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9551 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9552 goto err_free;
9553 }
9554
d30d42e0 9555 prev_offset = krecord[i].insn_off;
838e9690
YS
9556 urecord += urec_size;
9557 }
9558
ba64e7d8
YS
9559 prog->aux->func_info = krecord;
9560 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 9561 prog->aux->func_info_aux = info_aux;
838e9690
YS
9562 return 0;
9563
c454a46b 9564err_free:
ba64e7d8 9565 kvfree(krecord);
8c1b6e69 9566 kfree(info_aux);
838e9690
YS
9567 return ret;
9568}
9569
ba64e7d8
YS
9570static void adjust_btf_func(struct bpf_verifier_env *env)
9571{
8c1b6e69 9572 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
9573 int i;
9574
8c1b6e69 9575 if (!aux->func_info)
ba64e7d8
YS
9576 return;
9577
9578 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 9579 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
9580}
9581
c454a46b
MKL
9582#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9583 sizeof(((struct bpf_line_info *)(0))->line_col))
9584#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9585
9586static int check_btf_line(struct bpf_verifier_env *env,
9587 const union bpf_attr *attr,
9588 union bpf_attr __user *uattr)
9589{
9590 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9591 struct bpf_subprog_info *sub;
9592 struct bpf_line_info *linfo;
9593 struct bpf_prog *prog;
9594 const struct btf *btf;
9595 void __user *ulinfo;
9596 int err;
9597
9598 nr_linfo = attr->line_info_cnt;
9599 if (!nr_linfo)
9600 return 0;
9601
9602 rec_size = attr->line_info_rec_size;
9603 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9604 rec_size > MAX_LINEINFO_REC_SIZE ||
9605 rec_size & (sizeof(u32) - 1))
9606 return -EINVAL;
9607
9608 /* Need to zero it in case the userspace may
9609 * pass in a smaller bpf_line_info object.
9610 */
9611 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9612 GFP_KERNEL | __GFP_NOWARN);
9613 if (!linfo)
9614 return -ENOMEM;
9615
9616 prog = env->prog;
9617 btf = prog->aux->btf;
9618
9619 s = 0;
9620 sub = env->subprog_info;
9621 ulinfo = u64_to_user_ptr(attr->line_info);
9622 expected_size = sizeof(struct bpf_line_info);
9623 ncopy = min_t(u32, expected_size, rec_size);
9624 for (i = 0; i < nr_linfo; i++) {
9625 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9626 if (err) {
9627 if (err == -E2BIG) {
9628 verbose(env, "nonzero tailing record in line_info");
9629 if (put_user(expected_size,
9630 &uattr->line_info_rec_size))
9631 err = -EFAULT;
9632 }
9633 goto err_free;
9634 }
9635
9636 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9637 err = -EFAULT;
9638 goto err_free;
9639 }
9640
9641 /*
9642 * Check insn_off to ensure
9643 * 1) strictly increasing AND
9644 * 2) bounded by prog->len
9645 *
9646 * The linfo[0].insn_off == 0 check logically falls into
9647 * the later "missing bpf_line_info for func..." case
9648 * because the first linfo[0].insn_off must be the
9649 * first sub also and the first sub must have
9650 * subprog_info[0].start == 0.
9651 */
9652 if ((i && linfo[i].insn_off <= prev_offset) ||
9653 linfo[i].insn_off >= prog->len) {
9654 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9655 i, linfo[i].insn_off, prev_offset,
9656 prog->len);
9657 err = -EINVAL;
9658 goto err_free;
9659 }
9660
fdbaa0be
MKL
9661 if (!prog->insnsi[linfo[i].insn_off].code) {
9662 verbose(env,
9663 "Invalid insn code at line_info[%u].insn_off\n",
9664 i);
9665 err = -EINVAL;
9666 goto err_free;
9667 }
9668
23127b33
MKL
9669 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9670 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
9671 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9672 err = -EINVAL;
9673 goto err_free;
9674 }
9675
9676 if (s != env->subprog_cnt) {
9677 if (linfo[i].insn_off == sub[s].start) {
9678 sub[s].linfo_idx = i;
9679 s++;
9680 } else if (sub[s].start < linfo[i].insn_off) {
9681 verbose(env, "missing bpf_line_info for func#%u\n", s);
9682 err = -EINVAL;
9683 goto err_free;
9684 }
9685 }
9686
9687 prev_offset = linfo[i].insn_off;
9688 ulinfo += rec_size;
9689 }
9690
9691 if (s != env->subprog_cnt) {
9692 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9693 env->subprog_cnt - s, s);
9694 err = -EINVAL;
9695 goto err_free;
9696 }
9697
9698 prog->aux->linfo = linfo;
9699 prog->aux->nr_linfo = nr_linfo;
9700
9701 return 0;
9702
9703err_free:
9704 kvfree(linfo);
9705 return err;
9706}
9707
9708static int check_btf_info(struct bpf_verifier_env *env,
9709 const union bpf_attr *attr,
9710 union bpf_attr __user *uattr)
9711{
9712 struct btf *btf;
9713 int err;
9714
09b28d76
AS
9715 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9716 if (check_abnormal_return(env))
9717 return -EINVAL;
c454a46b 9718 return 0;
09b28d76 9719 }
c454a46b
MKL
9720
9721 btf = btf_get_by_fd(attr->prog_btf_fd);
9722 if (IS_ERR(btf))
9723 return PTR_ERR(btf);
350a5c4d
AS
9724 if (btf_is_kernel(btf)) {
9725 btf_put(btf);
9726 return -EACCES;
9727 }
c454a46b
MKL
9728 env->prog->aux->btf = btf;
9729
9730 err = check_btf_func(env, attr, uattr);
9731 if (err)
9732 return err;
9733
9734 err = check_btf_line(env, attr, uattr);
9735 if (err)
9736 return err;
9737
9738 return 0;
ba64e7d8
YS
9739}
9740
f1174f77
EC
9741/* check %cur's range satisfies %old's */
9742static bool range_within(struct bpf_reg_state *old,
9743 struct bpf_reg_state *cur)
9744{
b03c9f9f
EC
9745 return old->umin_value <= cur->umin_value &&
9746 old->umax_value >= cur->umax_value &&
9747 old->smin_value <= cur->smin_value &&
fd675184
DB
9748 old->smax_value >= cur->smax_value &&
9749 old->u32_min_value <= cur->u32_min_value &&
9750 old->u32_max_value >= cur->u32_max_value &&
9751 old->s32_min_value <= cur->s32_min_value &&
9752 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9753}
9754
9755/* Maximum number of register states that can exist at once */
9756#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9757struct idpair {
9758 u32 old;
9759 u32 cur;
9760};
9761
9762/* If in the old state two registers had the same id, then they need to have
9763 * the same id in the new state as well. But that id could be different from
9764 * the old state, so we need to track the mapping from old to new ids.
9765 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9766 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9767 * regs with a different old id could still have new id 9, we don't care about
9768 * that.
9769 * So we look through our idmap to see if this old id has been seen before. If
9770 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9771 */
f1174f77 9772static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 9773{
f1174f77 9774 unsigned int i;
969bf05e 9775
f1174f77
EC
9776 for (i = 0; i < ID_MAP_SIZE; i++) {
9777 if (!idmap[i].old) {
9778 /* Reached an empty slot; haven't seen this id before */
9779 idmap[i].old = old_id;
9780 idmap[i].cur = cur_id;
9781 return true;
9782 }
9783 if (idmap[i].old == old_id)
9784 return idmap[i].cur == cur_id;
9785 }
9786 /* We ran out of idmap slots, which should be impossible */
9787 WARN_ON_ONCE(1);
9788 return false;
9789}
9790
9242b5f5
AS
9791static void clean_func_state(struct bpf_verifier_env *env,
9792 struct bpf_func_state *st)
9793{
9794 enum bpf_reg_liveness live;
9795 int i, j;
9796
9797 for (i = 0; i < BPF_REG_FP; i++) {
9798 live = st->regs[i].live;
9799 /* liveness must not touch this register anymore */
9800 st->regs[i].live |= REG_LIVE_DONE;
9801 if (!(live & REG_LIVE_READ))
9802 /* since the register is unused, clear its state
9803 * to make further comparison simpler
9804 */
f54c7898 9805 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9806 }
9807
9808 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9809 live = st->stack[i].spilled_ptr.live;
9810 /* liveness must not touch this stack slot anymore */
9811 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9812 if (!(live & REG_LIVE_READ)) {
f54c7898 9813 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9814 for (j = 0; j < BPF_REG_SIZE; j++)
9815 st->stack[i].slot_type[j] = STACK_INVALID;
9816 }
9817 }
9818}
9819
9820static void clean_verifier_state(struct bpf_verifier_env *env,
9821 struct bpf_verifier_state *st)
9822{
9823 int i;
9824
9825 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9826 /* all regs in this state in all frames were already marked */
9827 return;
9828
9829 for (i = 0; i <= st->curframe; i++)
9830 clean_func_state(env, st->frame[i]);
9831}
9832
9833/* the parentage chains form a tree.
9834 * the verifier states are added to state lists at given insn and
9835 * pushed into state stack for future exploration.
9836 * when the verifier reaches bpf_exit insn some of the verifer states
9837 * stored in the state lists have their final liveness state already,
9838 * but a lot of states will get revised from liveness point of view when
9839 * the verifier explores other branches.
9840 * Example:
9841 * 1: r0 = 1
9842 * 2: if r1 == 100 goto pc+1
9843 * 3: r0 = 2
9844 * 4: exit
9845 * when the verifier reaches exit insn the register r0 in the state list of
9846 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9847 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9848 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9849 *
9850 * Since the verifier pushes the branch states as it sees them while exploring
9851 * the program the condition of walking the branch instruction for the second
9852 * time means that all states below this branch were already explored and
9853 * their final liveness markes are already propagated.
9854 * Hence when the verifier completes the search of state list in is_state_visited()
9855 * we can call this clean_live_states() function to mark all liveness states
9856 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9857 * will not be used.
9858 * This function also clears the registers and stack for states that !READ
9859 * to simplify state merging.
9860 *
9861 * Important note here that walking the same branch instruction in the callee
9862 * doesn't meant that the states are DONE. The verifier has to compare
9863 * the callsites
9864 */
9865static void clean_live_states(struct bpf_verifier_env *env, int insn,
9866 struct bpf_verifier_state *cur)
9867{
9868 struct bpf_verifier_state_list *sl;
9869 int i;
9870
5d839021 9871 sl = *explored_state(env, insn);
a8f500af 9872 while (sl) {
2589726d
AS
9873 if (sl->state.branches)
9874 goto next;
dc2a4ebc
AS
9875 if (sl->state.insn_idx != insn ||
9876 sl->state.curframe != cur->curframe)
9242b5f5
AS
9877 goto next;
9878 for (i = 0; i <= cur->curframe; i++)
9879 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9880 goto next;
9881 clean_verifier_state(env, &sl->state);
9882next:
9883 sl = sl->next;
9884 }
9885}
9886
f1174f77 9887/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
9888static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9889 struct idpair *idmap)
f1174f77 9890{
f4d7e40a
AS
9891 bool equal;
9892
dc503a8a
EC
9893 if (!(rold->live & REG_LIVE_READ))
9894 /* explored state didn't use this */
9895 return true;
9896
679c782d 9897 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9898
9899 if (rold->type == PTR_TO_STACK)
9900 /* two stack pointers are equal only if they're pointing to
9901 * the same stack frame, since fp-8 in foo != fp-8 in bar
9902 */
9903 return equal && rold->frameno == rcur->frameno;
9904
9905 if (equal)
969bf05e
AS
9906 return true;
9907
f1174f77
EC
9908 if (rold->type == NOT_INIT)
9909 /* explored state can't have used this */
969bf05e 9910 return true;
f1174f77
EC
9911 if (rcur->type == NOT_INIT)
9912 return false;
9913 switch (rold->type) {
9914 case SCALAR_VALUE:
9915 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9916 if (!rold->precise && !rcur->precise)
9917 return true;
f1174f77
EC
9918 /* new val must satisfy old val knowledge */
9919 return range_within(rold, rcur) &&
9920 tnum_in(rold->var_off, rcur->var_off);
9921 } else {
179d1c56
JH
9922 /* We're trying to use a pointer in place of a scalar.
9923 * Even if the scalar was unbounded, this could lead to
9924 * pointer leaks because scalars are allowed to leak
9925 * while pointers are not. We could make this safe in
9926 * special cases if root is calling us, but it's
9927 * probably not worth the hassle.
f1174f77 9928 */
179d1c56 9929 return false;
f1174f77 9930 }
69c087ba 9931 case PTR_TO_MAP_KEY:
f1174f77 9932 case PTR_TO_MAP_VALUE:
1b688a19
EC
9933 /* If the new min/max/var_off satisfy the old ones and
9934 * everything else matches, we are OK.
d83525ca
AS
9935 * 'id' is not compared, since it's only used for maps with
9936 * bpf_spin_lock inside map element and in such cases if
9937 * the rest of the prog is valid for one map element then
9938 * it's valid for all map elements regardless of the key
9939 * used in bpf_map_lookup()
1b688a19
EC
9940 */
9941 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9942 range_within(rold, rcur) &&
9943 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
9944 case PTR_TO_MAP_VALUE_OR_NULL:
9945 /* a PTR_TO_MAP_VALUE could be safe to use as a
9946 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9947 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9948 * checked, doing so could have affected others with the same
9949 * id, and we can't check for that because we lost the id when
9950 * we converted to a PTR_TO_MAP_VALUE.
9951 */
9952 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9953 return false;
9954 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9955 return false;
9956 /* Check our ids match any regs they're supposed to */
9957 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 9958 case PTR_TO_PACKET_META:
f1174f77 9959 case PTR_TO_PACKET:
de8f3a83 9960 if (rcur->type != rold->type)
f1174f77
EC
9961 return false;
9962 /* We must have at least as much range as the old ptr
9963 * did, so that any accesses which were safe before are
9964 * still safe. This is true even if old range < old off,
9965 * since someone could have accessed through (ptr - k), or
9966 * even done ptr -= k in a register, to get a safe access.
9967 */
9968 if (rold->range > rcur->range)
9969 return false;
9970 /* If the offsets don't match, we can't trust our alignment;
9971 * nor can we be sure that we won't fall out of range.
9972 */
9973 if (rold->off != rcur->off)
9974 return false;
9975 /* id relations must be preserved */
9976 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9977 return false;
9978 /* new val must satisfy old val knowledge */
9979 return range_within(rold, rcur) &&
9980 tnum_in(rold->var_off, rcur->var_off);
9981 case PTR_TO_CTX:
9982 case CONST_PTR_TO_MAP:
f1174f77 9983 case PTR_TO_PACKET_END:
d58e468b 9984 case PTR_TO_FLOW_KEYS:
c64b7983
JS
9985 case PTR_TO_SOCKET:
9986 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9987 case PTR_TO_SOCK_COMMON:
9988 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9989 case PTR_TO_TCP_SOCK:
9990 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9991 case PTR_TO_XDP_SOCK:
f1174f77
EC
9992 /* Only valid matches are exact, which memcmp() above
9993 * would have accepted
9994 */
9995 default:
9996 /* Don't know what's going on, just say it's not safe */
9997 return false;
9998 }
969bf05e 9999
f1174f77
EC
10000 /* Shouldn't get here; if we do, say it's not safe */
10001 WARN_ON_ONCE(1);
969bf05e
AS
10002 return false;
10003}
10004
f4d7e40a
AS
10005static bool stacksafe(struct bpf_func_state *old,
10006 struct bpf_func_state *cur,
638f5b90
AS
10007 struct idpair *idmap)
10008{
10009 int i, spi;
10010
638f5b90
AS
10011 /* walk slots of the explored stack and ignore any additional
10012 * slots in the current stack, since explored(safe) state
10013 * didn't use them
10014 */
10015 for (i = 0; i < old->allocated_stack; i++) {
10016 spi = i / BPF_REG_SIZE;
10017
b233920c
AS
10018 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10019 i += BPF_REG_SIZE - 1;
cc2b14d5 10020 /* explored state didn't use this */
fd05e57b 10021 continue;
b233920c 10022 }
cc2b14d5 10023
638f5b90
AS
10024 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10025 continue;
19e2dbb7
AS
10026
10027 /* explored stack has more populated slots than current stack
10028 * and these slots were used
10029 */
10030 if (i >= cur->allocated_stack)
10031 return false;
10032
cc2b14d5
AS
10033 /* if old state was safe with misc data in the stack
10034 * it will be safe with zero-initialized stack.
10035 * The opposite is not true
10036 */
10037 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10038 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10039 continue;
638f5b90
AS
10040 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10041 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10042 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 10043 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
10044 * this verifier states are not equivalent,
10045 * return false to continue verification of this path
10046 */
10047 return false;
10048 if (i % BPF_REG_SIZE)
10049 continue;
10050 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10051 continue;
10052 if (!regsafe(&old->stack[spi].spilled_ptr,
10053 &cur->stack[spi].spilled_ptr,
10054 idmap))
10055 /* when explored and current stack slot are both storing
10056 * spilled registers, check that stored pointers types
10057 * are the same as well.
10058 * Ex: explored safe path could have stored
10059 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10060 * but current path has stored:
10061 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10062 * such verifier states are not equivalent.
10063 * return false to continue verification of this path
10064 */
10065 return false;
10066 }
10067 return true;
10068}
10069
fd978bf7
JS
10070static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10071{
10072 if (old->acquired_refs != cur->acquired_refs)
10073 return false;
10074 return !memcmp(old->refs, cur->refs,
10075 sizeof(*old->refs) * old->acquired_refs);
10076}
10077
f1bca824
AS
10078/* compare two verifier states
10079 *
10080 * all states stored in state_list are known to be valid, since
10081 * verifier reached 'bpf_exit' instruction through them
10082 *
10083 * this function is called when verifier exploring different branches of
10084 * execution popped from the state stack. If it sees an old state that has
10085 * more strict register state and more strict stack state then this execution
10086 * branch doesn't need to be explored further, since verifier already
10087 * concluded that more strict state leads to valid finish.
10088 *
10089 * Therefore two states are equivalent if register state is more conservative
10090 * and explored stack state is more conservative than the current one.
10091 * Example:
10092 * explored current
10093 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10094 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10095 *
10096 * In other words if current stack state (one being explored) has more
10097 * valid slots than old one that already passed validation, it means
10098 * the verifier can stop exploring and conclude that current state is valid too
10099 *
10100 * Similarly with registers. If explored state has register type as invalid
10101 * whereas register type in current state is meaningful, it means that
10102 * the current state will reach 'bpf_exit' instruction safely
10103 */
f4d7e40a
AS
10104static bool func_states_equal(struct bpf_func_state *old,
10105 struct bpf_func_state *cur)
f1bca824 10106{
f1174f77
EC
10107 struct idpair *idmap;
10108 bool ret = false;
f1bca824
AS
10109 int i;
10110
f1174f77
EC
10111 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
10112 /* If we failed to allocate the idmap, just say it's not safe */
10113 if (!idmap)
1a0dc1ac 10114 return false;
f1174f77
EC
10115
10116 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 10117 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 10118 goto out_free;
f1bca824
AS
10119 }
10120
638f5b90
AS
10121 if (!stacksafe(old, cur, idmap))
10122 goto out_free;
fd978bf7
JS
10123
10124 if (!refsafe(old, cur))
10125 goto out_free;
f1174f77
EC
10126 ret = true;
10127out_free:
10128 kfree(idmap);
10129 return ret;
f1bca824
AS
10130}
10131
f4d7e40a
AS
10132static bool states_equal(struct bpf_verifier_env *env,
10133 struct bpf_verifier_state *old,
10134 struct bpf_verifier_state *cur)
10135{
10136 int i;
10137
10138 if (old->curframe != cur->curframe)
10139 return false;
10140
979d63d5
DB
10141 /* Verification state from speculative execution simulation
10142 * must never prune a non-speculative execution one.
10143 */
10144 if (old->speculative && !cur->speculative)
10145 return false;
10146
d83525ca
AS
10147 if (old->active_spin_lock != cur->active_spin_lock)
10148 return false;
10149
f4d7e40a
AS
10150 /* for states to be equal callsites have to be the same
10151 * and all frame states need to be equivalent
10152 */
10153 for (i = 0; i <= old->curframe; i++) {
10154 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10155 return false;
10156 if (!func_states_equal(old->frame[i], cur->frame[i]))
10157 return false;
10158 }
10159 return true;
10160}
10161
5327ed3d
JW
10162/* Return 0 if no propagation happened. Return negative error code if error
10163 * happened. Otherwise, return the propagated bit.
10164 */
55e7f3b5
JW
10165static int propagate_liveness_reg(struct bpf_verifier_env *env,
10166 struct bpf_reg_state *reg,
10167 struct bpf_reg_state *parent_reg)
10168{
5327ed3d
JW
10169 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10170 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
10171 int err;
10172
5327ed3d
JW
10173 /* When comes here, read flags of PARENT_REG or REG could be any of
10174 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10175 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10176 */
10177 if (parent_flag == REG_LIVE_READ64 ||
10178 /* Or if there is no read flag from REG. */
10179 !flag ||
10180 /* Or if the read flag from REG is the same as PARENT_REG. */
10181 parent_flag == flag)
55e7f3b5
JW
10182 return 0;
10183
5327ed3d 10184 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
10185 if (err)
10186 return err;
10187
5327ed3d 10188 return flag;
55e7f3b5
JW
10189}
10190
8e9cd9ce 10191/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
10192 * straight-line code between a state and its parent. When we arrive at an
10193 * equivalent state (jump target or such) we didn't arrive by the straight-line
10194 * code, so read marks in the state must propagate to the parent regardless
10195 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 10196 * in mark_reg_read() is for.
8e9cd9ce 10197 */
f4d7e40a
AS
10198static int propagate_liveness(struct bpf_verifier_env *env,
10199 const struct bpf_verifier_state *vstate,
10200 struct bpf_verifier_state *vparent)
dc503a8a 10201{
3f8cafa4 10202 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 10203 struct bpf_func_state *state, *parent;
3f8cafa4 10204 int i, frame, err = 0;
dc503a8a 10205
f4d7e40a
AS
10206 if (vparent->curframe != vstate->curframe) {
10207 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10208 vparent->curframe, vstate->curframe);
10209 return -EFAULT;
10210 }
dc503a8a
EC
10211 /* Propagate read liveness of registers... */
10212 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 10213 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
10214 parent = vparent->frame[frame];
10215 state = vstate->frame[frame];
10216 parent_reg = parent->regs;
10217 state_reg = state->regs;
83d16312
JK
10218 /* We don't need to worry about FP liveness, it's read-only */
10219 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
10220 err = propagate_liveness_reg(env, &state_reg[i],
10221 &parent_reg[i]);
5327ed3d 10222 if (err < 0)
3f8cafa4 10223 return err;
5327ed3d
JW
10224 if (err == REG_LIVE_READ64)
10225 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 10226 }
f4d7e40a 10227
1b04aee7 10228 /* Propagate stack slots. */
f4d7e40a
AS
10229 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10230 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
10231 parent_reg = &parent->stack[i].spilled_ptr;
10232 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
10233 err = propagate_liveness_reg(env, state_reg,
10234 parent_reg);
5327ed3d 10235 if (err < 0)
3f8cafa4 10236 return err;
dc503a8a
EC
10237 }
10238 }
5327ed3d 10239 return 0;
dc503a8a
EC
10240}
10241
a3ce685d
AS
10242/* find precise scalars in the previous equivalent state and
10243 * propagate them into the current state
10244 */
10245static int propagate_precision(struct bpf_verifier_env *env,
10246 const struct bpf_verifier_state *old)
10247{
10248 struct bpf_reg_state *state_reg;
10249 struct bpf_func_state *state;
10250 int i, err = 0;
10251
10252 state = old->frame[old->curframe];
10253 state_reg = state->regs;
10254 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10255 if (state_reg->type != SCALAR_VALUE ||
10256 !state_reg->precise)
10257 continue;
10258 if (env->log.level & BPF_LOG_LEVEL2)
10259 verbose(env, "propagating r%d\n", i);
10260 err = mark_chain_precision(env, i);
10261 if (err < 0)
10262 return err;
10263 }
10264
10265 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10266 if (state->stack[i].slot_type[0] != STACK_SPILL)
10267 continue;
10268 state_reg = &state->stack[i].spilled_ptr;
10269 if (state_reg->type != SCALAR_VALUE ||
10270 !state_reg->precise)
10271 continue;
10272 if (env->log.level & BPF_LOG_LEVEL2)
10273 verbose(env, "propagating fp%d\n",
10274 (-i - 1) * BPF_REG_SIZE);
10275 err = mark_chain_precision_stack(env, i);
10276 if (err < 0)
10277 return err;
10278 }
10279 return 0;
10280}
10281
2589726d
AS
10282static bool states_maybe_looping(struct bpf_verifier_state *old,
10283 struct bpf_verifier_state *cur)
10284{
10285 struct bpf_func_state *fold, *fcur;
10286 int i, fr = cur->curframe;
10287
10288 if (old->curframe != fr)
10289 return false;
10290
10291 fold = old->frame[fr];
10292 fcur = cur->frame[fr];
10293 for (i = 0; i < MAX_BPF_REG; i++)
10294 if (memcmp(&fold->regs[i], &fcur->regs[i],
10295 offsetof(struct bpf_reg_state, parent)))
10296 return false;
10297 return true;
10298}
10299
10300
58e2af8b 10301static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 10302{
58e2af8b 10303 struct bpf_verifier_state_list *new_sl;
9f4686c4 10304 struct bpf_verifier_state_list *sl, **pprev;
679c782d 10305 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 10306 int i, j, err, states_cnt = 0;
10d274e8 10307 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 10308
b5dc0163 10309 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 10310 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
10311 /* this 'insn_idx' instruction wasn't marked, so we will not
10312 * be doing state search here
10313 */
10314 return 0;
10315
2589726d
AS
10316 /* bpf progs typically have pruning point every 4 instructions
10317 * http://vger.kernel.org/bpfconf2019.html#session-1
10318 * Do not add new state for future pruning if the verifier hasn't seen
10319 * at least 2 jumps and at least 8 instructions.
10320 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10321 * In tests that amounts to up to 50% reduction into total verifier
10322 * memory consumption and 20% verifier time speedup.
10323 */
10324 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10325 env->insn_processed - env->prev_insn_processed >= 8)
10326 add_new_state = true;
10327
a8f500af
AS
10328 pprev = explored_state(env, insn_idx);
10329 sl = *pprev;
10330
9242b5f5
AS
10331 clean_live_states(env, insn_idx, cur);
10332
a8f500af 10333 while (sl) {
dc2a4ebc
AS
10334 states_cnt++;
10335 if (sl->state.insn_idx != insn_idx)
10336 goto next;
2589726d
AS
10337 if (sl->state.branches) {
10338 if (states_maybe_looping(&sl->state, cur) &&
10339 states_equal(env, &sl->state, cur)) {
10340 verbose_linfo(env, insn_idx, "; ");
10341 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10342 return -EINVAL;
10343 }
10344 /* if the verifier is processing a loop, avoid adding new state
10345 * too often, since different loop iterations have distinct
10346 * states and may not help future pruning.
10347 * This threshold shouldn't be too low to make sure that
10348 * a loop with large bound will be rejected quickly.
10349 * The most abusive loop will be:
10350 * r1 += 1
10351 * if r1 < 1000000 goto pc-2
10352 * 1M insn_procssed limit / 100 == 10k peak states.
10353 * This threshold shouldn't be too high either, since states
10354 * at the end of the loop are likely to be useful in pruning.
10355 */
10356 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10357 env->insn_processed - env->prev_insn_processed < 100)
10358 add_new_state = false;
10359 goto miss;
10360 }
638f5b90 10361 if (states_equal(env, &sl->state, cur)) {
9f4686c4 10362 sl->hit_cnt++;
f1bca824 10363 /* reached equivalent register/stack state,
dc503a8a
EC
10364 * prune the search.
10365 * Registers read by the continuation are read by us.
8e9cd9ce
EC
10366 * If we have any write marks in env->cur_state, they
10367 * will prevent corresponding reads in the continuation
10368 * from reaching our parent (an explored_state). Our
10369 * own state will get the read marks recorded, but
10370 * they'll be immediately forgotten as we're pruning
10371 * this state and will pop a new one.
f1bca824 10372 */
f4d7e40a 10373 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
10374
10375 /* if previous state reached the exit with precision and
10376 * current state is equivalent to it (except precsion marks)
10377 * the precision needs to be propagated back in
10378 * the current state.
10379 */
10380 err = err ? : push_jmp_history(env, cur);
10381 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
10382 if (err)
10383 return err;
f1bca824 10384 return 1;
dc503a8a 10385 }
2589726d
AS
10386miss:
10387 /* when new state is not going to be added do not increase miss count.
10388 * Otherwise several loop iterations will remove the state
10389 * recorded earlier. The goal of these heuristics is to have
10390 * states from some iterations of the loop (some in the beginning
10391 * and some at the end) to help pruning.
10392 */
10393 if (add_new_state)
10394 sl->miss_cnt++;
9f4686c4
AS
10395 /* heuristic to determine whether this state is beneficial
10396 * to keep checking from state equivalence point of view.
10397 * Higher numbers increase max_states_per_insn and verification time,
10398 * but do not meaningfully decrease insn_processed.
10399 */
10400 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10401 /* the state is unlikely to be useful. Remove it to
10402 * speed up verification
10403 */
10404 *pprev = sl->next;
10405 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
10406 u32 br = sl->state.branches;
10407
10408 WARN_ONCE(br,
10409 "BUG live_done but branches_to_explore %d\n",
10410 br);
9f4686c4
AS
10411 free_verifier_state(&sl->state, false);
10412 kfree(sl);
10413 env->peak_states--;
10414 } else {
10415 /* cannot free this state, since parentage chain may
10416 * walk it later. Add it for free_list instead to
10417 * be freed at the end of verification
10418 */
10419 sl->next = env->free_list;
10420 env->free_list = sl;
10421 }
10422 sl = *pprev;
10423 continue;
10424 }
dc2a4ebc 10425next:
9f4686c4
AS
10426 pprev = &sl->next;
10427 sl = *pprev;
f1bca824
AS
10428 }
10429
06ee7115
AS
10430 if (env->max_states_per_insn < states_cnt)
10431 env->max_states_per_insn = states_cnt;
10432
2c78ee89 10433 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 10434 return push_jmp_history(env, cur);
ceefbc96 10435
2589726d 10436 if (!add_new_state)
b5dc0163 10437 return push_jmp_history(env, cur);
ceefbc96 10438
2589726d
AS
10439 /* There were no equivalent states, remember the current one.
10440 * Technically the current state is not proven to be safe yet,
f4d7e40a 10441 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 10442 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 10443 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
10444 * again on the way to bpf_exit.
10445 * When looping the sl->state.branches will be > 0 and this state
10446 * will not be considered for equivalence until branches == 0.
f1bca824 10447 */
638f5b90 10448 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
10449 if (!new_sl)
10450 return -ENOMEM;
06ee7115
AS
10451 env->total_states++;
10452 env->peak_states++;
2589726d
AS
10453 env->prev_jmps_processed = env->jmps_processed;
10454 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
10455
10456 /* add new state to the head of linked list */
679c782d
EC
10457 new = &new_sl->state;
10458 err = copy_verifier_state(new, cur);
1969db47 10459 if (err) {
679c782d 10460 free_verifier_state(new, false);
1969db47
AS
10461 kfree(new_sl);
10462 return err;
10463 }
dc2a4ebc 10464 new->insn_idx = insn_idx;
2589726d
AS
10465 WARN_ONCE(new->branches != 1,
10466 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 10467
2589726d 10468 cur->parent = new;
b5dc0163
AS
10469 cur->first_insn_idx = insn_idx;
10470 clear_jmp_history(cur);
5d839021
AS
10471 new_sl->next = *explored_state(env, insn_idx);
10472 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
10473 /* connect new state to parentage chain. Current frame needs all
10474 * registers connected. Only r6 - r9 of the callers are alive (pushed
10475 * to the stack implicitly by JITs) so in callers' frames connect just
10476 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10477 * the state of the call instruction (with WRITTEN set), and r0 comes
10478 * from callee with its full parentage chain, anyway.
10479 */
8e9cd9ce
EC
10480 /* clear write marks in current state: the writes we did are not writes
10481 * our child did, so they don't screen off its reads from us.
10482 * (There are no read marks in current state, because reads always mark
10483 * their parent and current state never has children yet. Only
10484 * explored_states can get read marks.)
10485 */
eea1c227
AS
10486 for (j = 0; j <= cur->curframe; j++) {
10487 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10488 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10489 for (i = 0; i < BPF_REG_FP; i++)
10490 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10491 }
f4d7e40a
AS
10492
10493 /* all stack frames are accessible from callee, clear them all */
10494 for (j = 0; j <= cur->curframe; j++) {
10495 struct bpf_func_state *frame = cur->frame[j];
679c782d 10496 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 10497
679c782d 10498 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 10499 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
10500 frame->stack[i].spilled_ptr.parent =
10501 &newframe->stack[i].spilled_ptr;
10502 }
f4d7e40a 10503 }
f1bca824
AS
10504 return 0;
10505}
10506
c64b7983
JS
10507/* Return true if it's OK to have the same insn return a different type. */
10508static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10509{
10510 switch (type) {
10511 case PTR_TO_CTX:
10512 case PTR_TO_SOCKET:
10513 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10514 case PTR_TO_SOCK_COMMON:
10515 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10516 case PTR_TO_TCP_SOCK:
10517 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10518 case PTR_TO_XDP_SOCK:
2a02759e 10519 case PTR_TO_BTF_ID:
b121b341 10520 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
10521 return false;
10522 default:
10523 return true;
10524 }
10525}
10526
10527/* If an instruction was previously used with particular pointer types, then we
10528 * need to be careful to avoid cases such as the below, where it may be ok
10529 * for one branch accessing the pointer, but not ok for the other branch:
10530 *
10531 * R1 = sock_ptr
10532 * goto X;
10533 * ...
10534 * R1 = some_other_valid_ptr;
10535 * goto X;
10536 * ...
10537 * R2 = *(u32 *)(R1 + 0);
10538 */
10539static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10540{
10541 return src != prev && (!reg_type_mismatch_ok(src) ||
10542 !reg_type_mismatch_ok(prev));
10543}
10544
58e2af8b 10545static int do_check(struct bpf_verifier_env *env)
17a52670 10546{
6f8a57cc 10547 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 10548 struct bpf_verifier_state *state = env->cur_state;
17a52670 10549 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 10550 struct bpf_reg_state *regs;
06ee7115 10551 int insn_cnt = env->prog->len;
17a52670 10552 bool do_print_state = false;
b5dc0163 10553 int prev_insn_idx = -1;
17a52670 10554
17a52670
AS
10555 for (;;) {
10556 struct bpf_insn *insn;
10557 u8 class;
10558 int err;
10559
b5dc0163 10560 env->prev_insn_idx = prev_insn_idx;
c08435ec 10561 if (env->insn_idx >= insn_cnt) {
61bd5218 10562 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 10563 env->insn_idx, insn_cnt);
17a52670
AS
10564 return -EFAULT;
10565 }
10566
c08435ec 10567 insn = &insns[env->insn_idx];
17a52670
AS
10568 class = BPF_CLASS(insn->code);
10569
06ee7115 10570 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
10571 verbose(env,
10572 "BPF program is too large. Processed %d insn\n",
06ee7115 10573 env->insn_processed);
17a52670
AS
10574 return -E2BIG;
10575 }
10576
c08435ec 10577 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
10578 if (err < 0)
10579 return err;
10580 if (err == 1) {
10581 /* found equivalent state, can prune the search */
06ee7115 10582 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 10583 if (do_print_state)
979d63d5
DB
10584 verbose(env, "\nfrom %d to %d%s: safe\n",
10585 env->prev_insn_idx, env->insn_idx,
10586 env->cur_state->speculative ?
10587 " (speculative execution)" : "");
f1bca824 10588 else
c08435ec 10589 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
10590 }
10591 goto process_bpf_exit;
10592 }
10593
c3494801
AS
10594 if (signal_pending(current))
10595 return -EAGAIN;
10596
3c2ce60b
DB
10597 if (need_resched())
10598 cond_resched();
10599
06ee7115
AS
10600 if (env->log.level & BPF_LOG_LEVEL2 ||
10601 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10602 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 10603 verbose(env, "%d:", env->insn_idx);
c5fc9692 10604 else
979d63d5
DB
10605 verbose(env, "\nfrom %d to %d%s:",
10606 env->prev_insn_idx, env->insn_idx,
10607 env->cur_state->speculative ?
10608 " (speculative execution)" : "");
f4d7e40a 10609 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
10610 do_print_state = false;
10611 }
10612
06ee7115 10613 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 10614 const struct bpf_insn_cbs cbs = {
e6ac2450 10615 .cb_call = disasm_kfunc_name,
7105e828 10616 .cb_print = verbose,
abe08840 10617 .private_data = env,
7105e828
DB
10618 };
10619
c08435ec
DB
10620 verbose_linfo(env, env->insn_idx, "; ");
10621 verbose(env, "%d: ", env->insn_idx);
abe08840 10622 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
10623 }
10624
cae1927c 10625 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
10626 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10627 env->prev_insn_idx);
cae1927c
JK
10628 if (err)
10629 return err;
10630 }
13a27dfc 10631
638f5b90 10632 regs = cur_regs(env);
51c39bb1 10633 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 10634 prev_insn_idx = env->insn_idx;
fd978bf7 10635
17a52670 10636 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 10637 err = check_alu_op(env, insn);
17a52670
AS
10638 if (err)
10639 return err;
10640
10641 } else if (class == BPF_LDX) {
3df126f3 10642 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
10643
10644 /* check for reserved fields is already done */
10645
17a52670 10646 /* check src operand */
dc503a8a 10647 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10648 if (err)
10649 return err;
10650
dc503a8a 10651 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10652 if (err)
10653 return err;
10654
725f9dcd
AS
10655 src_reg_type = regs[insn->src_reg].type;
10656
17a52670
AS
10657 /* check that memory (src_reg + off) is readable,
10658 * the state of dst_reg will be updated by this func
10659 */
c08435ec
DB
10660 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10661 insn->off, BPF_SIZE(insn->code),
10662 BPF_READ, insn->dst_reg, false);
17a52670
AS
10663 if (err)
10664 return err;
10665
c08435ec 10666 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10667
10668 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
10669 /* saw a valid insn
10670 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 10671 * save type to validate intersecting paths
9bac3d6d 10672 */
3df126f3 10673 *prev_src_type = src_reg_type;
9bac3d6d 10674
c64b7983 10675 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
10676 /* ABuser program is trying to use the same insn
10677 * dst_reg = *(u32*) (src_reg + off)
10678 * with different pointer types:
10679 * src_reg == ctx in one branch and
10680 * src_reg == stack|map in some other branch.
10681 * Reject it.
10682 */
61bd5218 10683 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
10684 return -EINVAL;
10685 }
10686
17a52670 10687 } else if (class == BPF_STX) {
3df126f3 10688 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 10689
91c960b0
BJ
10690 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10691 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
10692 if (err)
10693 return err;
c08435ec 10694 env->insn_idx++;
17a52670
AS
10695 continue;
10696 }
10697
5ca419f2
BJ
10698 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10699 verbose(env, "BPF_STX uses reserved fields\n");
10700 return -EINVAL;
10701 }
10702
17a52670 10703 /* check src1 operand */
dc503a8a 10704 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10705 if (err)
10706 return err;
10707 /* check src2 operand */
dc503a8a 10708 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10709 if (err)
10710 return err;
10711
d691f9e8
AS
10712 dst_reg_type = regs[insn->dst_reg].type;
10713
17a52670 10714 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10715 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10716 insn->off, BPF_SIZE(insn->code),
10717 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10718 if (err)
10719 return err;
10720
c08435ec 10721 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10722
10723 if (*prev_dst_type == NOT_INIT) {
10724 *prev_dst_type = dst_reg_type;
c64b7983 10725 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10726 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10727 return -EINVAL;
10728 }
10729
17a52670
AS
10730 } else if (class == BPF_ST) {
10731 if (BPF_MODE(insn->code) != BPF_MEM ||
10732 insn->src_reg != BPF_REG_0) {
61bd5218 10733 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10734 return -EINVAL;
10735 }
10736 /* check src operand */
dc503a8a 10737 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10738 if (err)
10739 return err;
10740
f37a8cb8 10741 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10742 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10743 insn->dst_reg,
10744 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10745 return -EACCES;
10746 }
10747
17a52670 10748 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10749 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10750 insn->off, BPF_SIZE(insn->code),
10751 BPF_WRITE, -1, false);
17a52670
AS
10752 if (err)
10753 return err;
10754
092ed096 10755 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10756 u8 opcode = BPF_OP(insn->code);
10757
2589726d 10758 env->jmps_processed++;
17a52670
AS
10759 if (opcode == BPF_CALL) {
10760 if (BPF_SRC(insn->code) != BPF_K ||
10761 insn->off != 0 ||
f4d7e40a 10762 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
10763 insn->src_reg != BPF_PSEUDO_CALL &&
10764 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
10765 insn->dst_reg != BPF_REG_0 ||
10766 class == BPF_JMP32) {
61bd5218 10767 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10768 return -EINVAL;
10769 }
10770
d83525ca
AS
10771 if (env->cur_state->active_spin_lock &&
10772 (insn->src_reg == BPF_PSEUDO_CALL ||
10773 insn->imm != BPF_FUNC_spin_unlock)) {
10774 verbose(env, "function calls are not allowed while holding a lock\n");
10775 return -EINVAL;
10776 }
f4d7e40a 10777 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10778 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450
MKL
10779 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10780 err = check_kfunc_call(env, insn);
f4d7e40a 10781 else
69c087ba 10782 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
10783 if (err)
10784 return err;
17a52670
AS
10785 } else if (opcode == BPF_JA) {
10786 if (BPF_SRC(insn->code) != BPF_K ||
10787 insn->imm != 0 ||
10788 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10789 insn->dst_reg != BPF_REG_0 ||
10790 class == BPF_JMP32) {
61bd5218 10791 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10792 return -EINVAL;
10793 }
10794
c08435ec 10795 env->insn_idx += insn->off + 1;
17a52670
AS
10796 continue;
10797
10798 } else if (opcode == BPF_EXIT) {
10799 if (BPF_SRC(insn->code) != BPF_K ||
10800 insn->imm != 0 ||
10801 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10802 insn->dst_reg != BPF_REG_0 ||
10803 class == BPF_JMP32) {
61bd5218 10804 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10805 return -EINVAL;
10806 }
10807
d83525ca
AS
10808 if (env->cur_state->active_spin_lock) {
10809 verbose(env, "bpf_spin_unlock is missing\n");
10810 return -EINVAL;
10811 }
10812
f4d7e40a
AS
10813 if (state->curframe) {
10814 /* exit from nested function */
c08435ec 10815 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10816 if (err)
10817 return err;
10818 do_print_state = true;
10819 continue;
10820 }
10821
fd978bf7
JS
10822 err = check_reference_leak(env);
10823 if (err)
10824 return err;
10825
390ee7e2
AS
10826 err = check_return_code(env);
10827 if (err)
10828 return err;
f1bca824 10829process_bpf_exit:
2589726d 10830 update_branch_counts(env, env->cur_state);
b5dc0163 10831 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10832 &env->insn_idx, pop_log);
638f5b90
AS
10833 if (err < 0) {
10834 if (err != -ENOENT)
10835 return err;
17a52670
AS
10836 break;
10837 } else {
10838 do_print_state = true;
10839 continue;
10840 }
10841 } else {
c08435ec 10842 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10843 if (err)
10844 return err;
10845 }
10846 } else if (class == BPF_LD) {
10847 u8 mode = BPF_MODE(insn->code);
10848
10849 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10850 err = check_ld_abs(env, insn);
10851 if (err)
10852 return err;
10853
17a52670
AS
10854 } else if (mode == BPF_IMM) {
10855 err = check_ld_imm(env, insn);
10856 if (err)
10857 return err;
10858
c08435ec 10859 env->insn_idx++;
51c39bb1 10860 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 10861 } else {
61bd5218 10862 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10863 return -EINVAL;
10864 }
10865 } else {
61bd5218 10866 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10867 return -EINVAL;
10868 }
10869
c08435ec 10870 env->insn_idx++;
17a52670
AS
10871 }
10872
10873 return 0;
10874}
10875
541c3bad
AN
10876static int find_btf_percpu_datasec(struct btf *btf)
10877{
10878 const struct btf_type *t;
10879 const char *tname;
10880 int i, n;
10881
10882 /*
10883 * Both vmlinux and module each have their own ".data..percpu"
10884 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10885 * types to look at only module's own BTF types.
10886 */
10887 n = btf_nr_types(btf);
10888 if (btf_is_module(btf))
10889 i = btf_nr_types(btf_vmlinux);
10890 else
10891 i = 1;
10892
10893 for(; i < n; i++) {
10894 t = btf_type_by_id(btf, i);
10895 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10896 continue;
10897
10898 tname = btf_name_by_offset(btf, t->name_off);
10899 if (!strcmp(tname, ".data..percpu"))
10900 return i;
10901 }
10902
10903 return -ENOENT;
10904}
10905
4976b718
HL
10906/* replace pseudo btf_id with kernel symbol address */
10907static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10908 struct bpf_insn *insn,
10909 struct bpf_insn_aux_data *aux)
10910{
eaa6bcb7
HL
10911 const struct btf_var_secinfo *vsi;
10912 const struct btf_type *datasec;
541c3bad 10913 struct btf_mod_pair *btf_mod;
4976b718
HL
10914 const struct btf_type *t;
10915 const char *sym_name;
eaa6bcb7 10916 bool percpu = false;
f16e6313 10917 u32 type, id = insn->imm;
541c3bad 10918 struct btf *btf;
f16e6313 10919 s32 datasec_id;
4976b718 10920 u64 addr;
541c3bad 10921 int i, btf_fd, err;
4976b718 10922
541c3bad
AN
10923 btf_fd = insn[1].imm;
10924 if (btf_fd) {
10925 btf = btf_get_by_fd(btf_fd);
10926 if (IS_ERR(btf)) {
10927 verbose(env, "invalid module BTF object FD specified.\n");
10928 return -EINVAL;
10929 }
10930 } else {
10931 if (!btf_vmlinux) {
10932 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10933 return -EINVAL;
10934 }
10935 btf = btf_vmlinux;
10936 btf_get(btf);
4976b718
HL
10937 }
10938
541c3bad 10939 t = btf_type_by_id(btf, id);
4976b718
HL
10940 if (!t) {
10941 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
10942 err = -ENOENT;
10943 goto err_put;
4976b718
HL
10944 }
10945
10946 if (!btf_type_is_var(t)) {
541c3bad
AN
10947 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10948 err = -EINVAL;
10949 goto err_put;
4976b718
HL
10950 }
10951
541c3bad 10952 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10953 addr = kallsyms_lookup_name(sym_name);
10954 if (!addr) {
10955 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10956 sym_name);
541c3bad
AN
10957 err = -ENOENT;
10958 goto err_put;
4976b718
HL
10959 }
10960
541c3bad 10961 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 10962 if (datasec_id > 0) {
541c3bad 10963 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
10964 for_each_vsi(i, datasec, vsi) {
10965 if (vsi->type == id) {
10966 percpu = true;
10967 break;
10968 }
10969 }
10970 }
10971
4976b718
HL
10972 insn[0].imm = (u32)addr;
10973 insn[1].imm = addr >> 32;
10974
10975 type = t->type;
541c3bad 10976 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7
HL
10977 if (percpu) {
10978 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
541c3bad 10979 aux->btf_var.btf = btf;
eaa6bcb7
HL
10980 aux->btf_var.btf_id = type;
10981 } else if (!btf_type_is_struct(t)) {
4976b718
HL
10982 const struct btf_type *ret;
10983 const char *tname;
10984 u32 tsize;
10985
10986 /* resolve the type size of ksym. */
541c3bad 10987 ret = btf_resolve_size(btf, t, &tsize);
4976b718 10988 if (IS_ERR(ret)) {
541c3bad 10989 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10990 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10991 tname, PTR_ERR(ret));
541c3bad
AN
10992 err = -EINVAL;
10993 goto err_put;
4976b718
HL
10994 }
10995 aux->btf_var.reg_type = PTR_TO_MEM;
10996 aux->btf_var.mem_size = tsize;
10997 } else {
10998 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 10999 aux->btf_var.btf = btf;
4976b718
HL
11000 aux->btf_var.btf_id = type;
11001 }
541c3bad
AN
11002
11003 /* check whether we recorded this BTF (and maybe module) already */
11004 for (i = 0; i < env->used_btf_cnt; i++) {
11005 if (env->used_btfs[i].btf == btf) {
11006 btf_put(btf);
11007 return 0;
11008 }
11009 }
11010
11011 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11012 err = -E2BIG;
11013 goto err_put;
11014 }
11015
11016 btf_mod = &env->used_btfs[env->used_btf_cnt];
11017 btf_mod->btf = btf;
11018 btf_mod->module = NULL;
11019
11020 /* if we reference variables from kernel module, bump its refcount */
11021 if (btf_is_module(btf)) {
11022 btf_mod->module = btf_try_get_module(btf);
11023 if (!btf_mod->module) {
11024 err = -ENXIO;
11025 goto err_put;
11026 }
11027 }
11028
11029 env->used_btf_cnt++;
11030
4976b718 11031 return 0;
541c3bad
AN
11032err_put:
11033 btf_put(btf);
11034 return err;
4976b718
HL
11035}
11036
56f668df
MKL
11037static int check_map_prealloc(struct bpf_map *map)
11038{
11039 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
11040 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11041 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
11042 !(map->map_flags & BPF_F_NO_PREALLOC);
11043}
11044
d83525ca
AS
11045static bool is_tracing_prog_type(enum bpf_prog_type type)
11046{
11047 switch (type) {
11048 case BPF_PROG_TYPE_KPROBE:
11049 case BPF_PROG_TYPE_TRACEPOINT:
11050 case BPF_PROG_TYPE_PERF_EVENT:
11051 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11052 return true;
11053 default:
11054 return false;
11055 }
11056}
11057
94dacdbd
TG
11058static bool is_preallocated_map(struct bpf_map *map)
11059{
11060 if (!check_map_prealloc(map))
11061 return false;
11062 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11063 return false;
11064 return true;
11065}
11066
61bd5218
JK
11067static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11068 struct bpf_map *map,
fdc15d38
AS
11069 struct bpf_prog *prog)
11070
11071{
7e40781c 11072 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
11073 /*
11074 * Validate that trace type programs use preallocated hash maps.
11075 *
11076 * For programs attached to PERF events this is mandatory as the
11077 * perf NMI can hit any arbitrary code sequence.
11078 *
11079 * All other trace types using preallocated hash maps are unsafe as
11080 * well because tracepoint or kprobes can be inside locked regions
11081 * of the memory allocator or at a place where a recursion into the
11082 * memory allocator would see inconsistent state.
11083 *
2ed905c5
TG
11084 * On RT enabled kernels run-time allocation of all trace type
11085 * programs is strictly prohibited due to lock type constraints. On
11086 * !RT kernels it is allowed for backwards compatibility reasons for
11087 * now, but warnings are emitted so developers are made aware of
11088 * the unsafety and can fix their programs before this is enforced.
56f668df 11089 */
7e40781c
UP
11090 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11091 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 11092 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
11093 return -EINVAL;
11094 }
2ed905c5
TG
11095 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11096 verbose(env, "trace type programs can only use preallocated hash map\n");
11097 return -EINVAL;
11098 }
94dacdbd
TG
11099 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11100 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 11101 }
a3884572 11102
9e7a4d98
KS
11103 if (map_value_has_spin_lock(map)) {
11104 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11105 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11106 return -EINVAL;
11107 }
11108
11109 if (is_tracing_prog_type(prog_type)) {
11110 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11111 return -EINVAL;
11112 }
11113
11114 if (prog->aux->sleepable) {
11115 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11116 return -EINVAL;
11117 }
d83525ca
AS
11118 }
11119
a3884572 11120 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 11121 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
11122 verbose(env, "offload device mismatch between prog and map\n");
11123 return -EINVAL;
11124 }
11125
85d33df3
MKL
11126 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11127 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11128 return -EINVAL;
11129 }
11130
1e6c62a8
AS
11131 if (prog->aux->sleepable)
11132 switch (map->map_type) {
11133 case BPF_MAP_TYPE_HASH:
11134 case BPF_MAP_TYPE_LRU_HASH:
11135 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
11136 case BPF_MAP_TYPE_PERCPU_HASH:
11137 case BPF_MAP_TYPE_PERCPU_ARRAY:
11138 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11139 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11140 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
11141 if (!is_preallocated_map(map)) {
11142 verbose(env,
638e4b82 11143 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
11144 return -EINVAL;
11145 }
11146 break;
ba90c2cc
KS
11147 case BPF_MAP_TYPE_RINGBUF:
11148 break;
1e6c62a8
AS
11149 default:
11150 verbose(env,
ba90c2cc 11151 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
11152 return -EINVAL;
11153 }
11154
fdc15d38
AS
11155 return 0;
11156}
11157
b741f163
RG
11158static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11159{
11160 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11161 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11162}
11163
4976b718
HL
11164/* find and rewrite pseudo imm in ld_imm64 instructions:
11165 *
11166 * 1. if it accesses map FD, replace it with actual map pointer.
11167 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11168 *
11169 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 11170 */
4976b718 11171static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
11172{
11173 struct bpf_insn *insn = env->prog->insnsi;
11174 int insn_cnt = env->prog->len;
fdc15d38 11175 int i, j, err;
0246e64d 11176
f1f7714e 11177 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
11178 if (err)
11179 return err;
11180
0246e64d 11181 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 11182 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 11183 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 11184 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
11185 return -EINVAL;
11186 }
11187
0246e64d 11188 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 11189 struct bpf_insn_aux_data *aux;
0246e64d
AS
11190 struct bpf_map *map;
11191 struct fd f;
d8eca5bb 11192 u64 addr;
0246e64d
AS
11193
11194 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11195 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11196 insn[1].off != 0) {
61bd5218 11197 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
11198 return -EINVAL;
11199 }
11200
d8eca5bb 11201 if (insn[0].src_reg == 0)
0246e64d
AS
11202 /* valid generic load 64-bit imm */
11203 goto next_insn;
11204
4976b718
HL
11205 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11206 aux = &env->insn_aux_data[i];
11207 err = check_pseudo_btf_id(env, insn, aux);
11208 if (err)
11209 return err;
11210 goto next_insn;
11211 }
11212
69c087ba
YS
11213 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11214 aux = &env->insn_aux_data[i];
11215 aux->ptr_type = PTR_TO_FUNC;
11216 goto next_insn;
11217 }
11218
d8eca5bb
DB
11219 /* In final convert_pseudo_ld_imm64() step, this is
11220 * converted into regular 64-bit imm load insn.
11221 */
11222 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11223 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11224 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11225 insn[1].imm != 0)) {
11226 verbose(env,
11227 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
11228 return -EINVAL;
11229 }
11230
20182390 11231 f = fdget(insn[0].imm);
c2101297 11232 map = __bpf_map_get(f);
0246e64d 11233 if (IS_ERR(map)) {
61bd5218 11234 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 11235 insn[0].imm);
0246e64d
AS
11236 return PTR_ERR(map);
11237 }
11238
61bd5218 11239 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
11240 if (err) {
11241 fdput(f);
11242 return err;
11243 }
11244
d8eca5bb
DB
11245 aux = &env->insn_aux_data[i];
11246 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11247 addr = (unsigned long)map;
11248 } else {
11249 u32 off = insn[1].imm;
11250
11251 if (off >= BPF_MAX_VAR_OFF) {
11252 verbose(env, "direct value offset of %u is not allowed\n", off);
11253 fdput(f);
11254 return -EINVAL;
11255 }
11256
11257 if (!map->ops->map_direct_value_addr) {
11258 verbose(env, "no direct value access support for this map type\n");
11259 fdput(f);
11260 return -EINVAL;
11261 }
11262
11263 err = map->ops->map_direct_value_addr(map, &addr, off);
11264 if (err) {
11265 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11266 map->value_size, off);
11267 fdput(f);
11268 return err;
11269 }
11270
11271 aux->map_off = off;
11272 addr += off;
11273 }
11274
11275 insn[0].imm = (u32)addr;
11276 insn[1].imm = addr >> 32;
0246e64d
AS
11277
11278 /* check whether we recorded this map already */
d8eca5bb 11279 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 11280 if (env->used_maps[j] == map) {
d8eca5bb 11281 aux->map_index = j;
0246e64d
AS
11282 fdput(f);
11283 goto next_insn;
11284 }
d8eca5bb 11285 }
0246e64d
AS
11286
11287 if (env->used_map_cnt >= MAX_USED_MAPS) {
11288 fdput(f);
11289 return -E2BIG;
11290 }
11291
0246e64d
AS
11292 /* hold the map. If the program is rejected by verifier,
11293 * the map will be released by release_maps() or it
11294 * will be used by the valid program until it's unloaded
ab7f5bf0 11295 * and all maps are released in free_used_maps()
0246e64d 11296 */
1e0bd5a0 11297 bpf_map_inc(map);
d8eca5bb
DB
11298
11299 aux->map_index = env->used_map_cnt;
92117d84
AS
11300 env->used_maps[env->used_map_cnt++] = map;
11301
b741f163 11302 if (bpf_map_is_cgroup_storage(map) &&
e4730423 11303 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 11304 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
11305 fdput(f);
11306 return -EBUSY;
11307 }
11308
0246e64d
AS
11309 fdput(f);
11310next_insn:
11311 insn++;
11312 i++;
5e581dad
DB
11313 continue;
11314 }
11315
11316 /* Basic sanity check before we invest more work here. */
11317 if (!bpf_opcode_in_insntable(insn->code)) {
11318 verbose(env, "unknown opcode %02x\n", insn->code);
11319 return -EINVAL;
0246e64d
AS
11320 }
11321 }
11322
11323 /* now all pseudo BPF_LD_IMM64 instructions load valid
11324 * 'struct bpf_map *' into a register instead of user map_fd.
11325 * These pointers will be used later by verifier to validate map access.
11326 */
11327 return 0;
11328}
11329
11330/* drop refcnt of maps used by the rejected program */
58e2af8b 11331static void release_maps(struct bpf_verifier_env *env)
0246e64d 11332{
a2ea0746
DB
11333 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11334 env->used_map_cnt);
0246e64d
AS
11335}
11336
541c3bad
AN
11337/* drop refcnt of maps used by the rejected program */
11338static void release_btfs(struct bpf_verifier_env *env)
11339{
11340 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11341 env->used_btf_cnt);
11342}
11343
0246e64d 11344/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 11345static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
11346{
11347 struct bpf_insn *insn = env->prog->insnsi;
11348 int insn_cnt = env->prog->len;
11349 int i;
11350
69c087ba
YS
11351 for (i = 0; i < insn_cnt; i++, insn++) {
11352 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11353 continue;
11354 if (insn->src_reg == BPF_PSEUDO_FUNC)
11355 continue;
11356 insn->src_reg = 0;
11357 }
0246e64d
AS
11358}
11359
8041902d
AS
11360/* single env->prog->insni[off] instruction was replaced with the range
11361 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11362 * [0, off) and [off, end) to new locations, so the patched range stays zero
11363 */
b325fbca
JW
11364static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11365 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
11366{
11367 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca 11368 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 11369 u32 old_seen = old_data[off].seen;
b325fbca 11370 u32 prog_len;
c131187d 11371 int i;
8041902d 11372
b325fbca
JW
11373 /* aux info at OFF always needs adjustment, no matter fast path
11374 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11375 * original insn at old prog.
11376 */
11377 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11378
8041902d
AS
11379 if (cnt == 1)
11380 return 0;
b325fbca 11381 prog_len = new_prog->len;
fad953ce
KC
11382 new_data = vzalloc(array_size(prog_len,
11383 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
11384 if (!new_data)
11385 return -ENOMEM;
11386 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11387 memcpy(new_data + off + cnt - 1, old_data + off,
11388 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 11389 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
11390 /* Expand insni[off]'s seen count to the patched range. */
11391 new_data[i].seen = old_seen;
b325fbca
JW
11392 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11393 }
8041902d
AS
11394 env->insn_aux_data = new_data;
11395 vfree(old_data);
11396 return 0;
11397}
11398
cc8b0b92
AS
11399static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11400{
11401 int i;
11402
11403 if (len == 1)
11404 return;
4cb3d99c
JW
11405 /* NOTE: fake 'exit' subprog should be updated as well. */
11406 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 11407 if (env->subprog_info[i].start <= off)
cc8b0b92 11408 continue;
9c8105bd 11409 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
11410 }
11411}
11412
a748c697
MF
11413static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
11414{
11415 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11416 int i, sz = prog->aux->size_poke_tab;
11417 struct bpf_jit_poke_descriptor *desc;
11418
11419 for (i = 0; i < sz; i++) {
11420 desc = &tab[i];
11421 desc->insn_idx += len - 1;
11422 }
11423}
11424
8041902d
AS
11425static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11426 const struct bpf_insn *patch, u32 len)
11427{
11428 struct bpf_prog *new_prog;
11429
11430 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
11431 if (IS_ERR(new_prog)) {
11432 if (PTR_ERR(new_prog) == -ERANGE)
11433 verbose(env,
11434 "insn %d cannot be patched due to 16-bit range\n",
11435 env->insn_aux_data[off].orig_idx);
8041902d 11436 return NULL;
4f73379e 11437 }
b325fbca 11438 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 11439 return NULL;
cc8b0b92 11440 adjust_subprog_starts(env, off, len);
a748c697 11441 adjust_poke_descs(new_prog, len);
8041902d
AS
11442 return new_prog;
11443}
11444
52875a04
JK
11445static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11446 u32 off, u32 cnt)
11447{
11448 int i, j;
11449
11450 /* find first prog starting at or after off (first to remove) */
11451 for (i = 0; i < env->subprog_cnt; i++)
11452 if (env->subprog_info[i].start >= off)
11453 break;
11454 /* find first prog starting at or after off + cnt (first to stay) */
11455 for (j = i; j < env->subprog_cnt; j++)
11456 if (env->subprog_info[j].start >= off + cnt)
11457 break;
11458 /* if j doesn't start exactly at off + cnt, we are just removing
11459 * the front of previous prog
11460 */
11461 if (env->subprog_info[j].start != off + cnt)
11462 j--;
11463
11464 if (j > i) {
11465 struct bpf_prog_aux *aux = env->prog->aux;
11466 int move;
11467
11468 /* move fake 'exit' subprog as well */
11469 move = env->subprog_cnt + 1 - j;
11470
11471 memmove(env->subprog_info + i,
11472 env->subprog_info + j,
11473 sizeof(*env->subprog_info) * move);
11474 env->subprog_cnt -= j - i;
11475
11476 /* remove func_info */
11477 if (aux->func_info) {
11478 move = aux->func_info_cnt - j;
11479
11480 memmove(aux->func_info + i,
11481 aux->func_info + j,
11482 sizeof(*aux->func_info) * move);
11483 aux->func_info_cnt -= j - i;
11484 /* func_info->insn_off is set after all code rewrites,
11485 * in adjust_btf_func() - no need to adjust
11486 */
11487 }
11488 } else {
11489 /* convert i from "first prog to remove" to "first to adjust" */
11490 if (env->subprog_info[i].start == off)
11491 i++;
11492 }
11493
11494 /* update fake 'exit' subprog as well */
11495 for (; i <= env->subprog_cnt; i++)
11496 env->subprog_info[i].start -= cnt;
11497
11498 return 0;
11499}
11500
11501static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11502 u32 cnt)
11503{
11504 struct bpf_prog *prog = env->prog;
11505 u32 i, l_off, l_cnt, nr_linfo;
11506 struct bpf_line_info *linfo;
11507
11508 nr_linfo = prog->aux->nr_linfo;
11509 if (!nr_linfo)
11510 return 0;
11511
11512 linfo = prog->aux->linfo;
11513
11514 /* find first line info to remove, count lines to be removed */
11515 for (i = 0; i < nr_linfo; i++)
11516 if (linfo[i].insn_off >= off)
11517 break;
11518
11519 l_off = i;
11520 l_cnt = 0;
11521 for (; i < nr_linfo; i++)
11522 if (linfo[i].insn_off < off + cnt)
11523 l_cnt++;
11524 else
11525 break;
11526
11527 /* First live insn doesn't match first live linfo, it needs to "inherit"
11528 * last removed linfo. prog is already modified, so prog->len == off
11529 * means no live instructions after (tail of the program was removed).
11530 */
11531 if (prog->len != off && l_cnt &&
11532 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11533 l_cnt--;
11534 linfo[--i].insn_off = off + cnt;
11535 }
11536
11537 /* remove the line info which refer to the removed instructions */
11538 if (l_cnt) {
11539 memmove(linfo + l_off, linfo + i,
11540 sizeof(*linfo) * (nr_linfo - i));
11541
11542 prog->aux->nr_linfo -= l_cnt;
11543 nr_linfo = prog->aux->nr_linfo;
11544 }
11545
11546 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11547 for (i = l_off; i < nr_linfo; i++)
11548 linfo[i].insn_off -= cnt;
11549
11550 /* fix up all subprogs (incl. 'exit') which start >= off */
11551 for (i = 0; i <= env->subprog_cnt; i++)
11552 if (env->subprog_info[i].linfo_idx > l_off) {
11553 /* program may have started in the removed region but
11554 * may not be fully removed
11555 */
11556 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11557 env->subprog_info[i].linfo_idx -= l_cnt;
11558 else
11559 env->subprog_info[i].linfo_idx = l_off;
11560 }
11561
11562 return 0;
11563}
11564
11565static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11566{
11567 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11568 unsigned int orig_prog_len = env->prog->len;
11569 int err;
11570
08ca90af
JK
11571 if (bpf_prog_is_dev_bound(env->prog->aux))
11572 bpf_prog_offload_remove_insns(env, off, cnt);
11573
52875a04
JK
11574 err = bpf_remove_insns(env->prog, off, cnt);
11575 if (err)
11576 return err;
11577
11578 err = adjust_subprog_starts_after_remove(env, off, cnt);
11579 if (err)
11580 return err;
11581
11582 err = bpf_adj_linfo_after_remove(env, off, cnt);
11583 if (err)
11584 return err;
11585
11586 memmove(aux_data + off, aux_data + off + cnt,
11587 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11588
11589 return 0;
11590}
11591
2a5418a1
DB
11592/* The verifier does more data flow analysis than llvm and will not
11593 * explore branches that are dead at run time. Malicious programs can
11594 * have dead code too. Therefore replace all dead at-run-time code
11595 * with 'ja -1'.
11596 *
11597 * Just nops are not optimal, e.g. if they would sit at the end of the
11598 * program and through another bug we would manage to jump there, then
11599 * we'd execute beyond program memory otherwise. Returning exception
11600 * code also wouldn't work since we can have subprogs where the dead
11601 * code could be located.
c131187d
AS
11602 */
11603static void sanitize_dead_code(struct bpf_verifier_env *env)
11604{
11605 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 11606 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
11607 struct bpf_insn *insn = env->prog->insnsi;
11608 const int insn_cnt = env->prog->len;
11609 int i;
11610
11611 for (i = 0; i < insn_cnt; i++) {
11612 if (aux_data[i].seen)
11613 continue;
2a5418a1 11614 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
11615 }
11616}
11617
e2ae4ca2
JK
11618static bool insn_is_cond_jump(u8 code)
11619{
11620 u8 op;
11621
092ed096
JW
11622 if (BPF_CLASS(code) == BPF_JMP32)
11623 return true;
11624
e2ae4ca2
JK
11625 if (BPF_CLASS(code) != BPF_JMP)
11626 return false;
11627
11628 op = BPF_OP(code);
11629 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11630}
11631
11632static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11633{
11634 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11635 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11636 struct bpf_insn *insn = env->prog->insnsi;
11637 const int insn_cnt = env->prog->len;
11638 int i;
11639
11640 for (i = 0; i < insn_cnt; i++, insn++) {
11641 if (!insn_is_cond_jump(insn->code))
11642 continue;
11643
11644 if (!aux_data[i + 1].seen)
11645 ja.off = insn->off;
11646 else if (!aux_data[i + 1 + insn->off].seen)
11647 ja.off = 0;
11648 else
11649 continue;
11650
08ca90af
JK
11651 if (bpf_prog_is_dev_bound(env->prog->aux))
11652 bpf_prog_offload_replace_insn(env, i, &ja);
11653
e2ae4ca2
JK
11654 memcpy(insn, &ja, sizeof(ja));
11655 }
11656}
11657
52875a04
JK
11658static int opt_remove_dead_code(struct bpf_verifier_env *env)
11659{
11660 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11661 int insn_cnt = env->prog->len;
11662 int i, err;
11663
11664 for (i = 0; i < insn_cnt; i++) {
11665 int j;
11666
11667 j = 0;
11668 while (i + j < insn_cnt && !aux_data[i + j].seen)
11669 j++;
11670 if (!j)
11671 continue;
11672
11673 err = verifier_remove_insns(env, i, j);
11674 if (err)
11675 return err;
11676 insn_cnt = env->prog->len;
11677 }
11678
11679 return 0;
11680}
11681
a1b14abc
JK
11682static int opt_remove_nops(struct bpf_verifier_env *env)
11683{
11684 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11685 struct bpf_insn *insn = env->prog->insnsi;
11686 int insn_cnt = env->prog->len;
11687 int i, err;
11688
11689 for (i = 0; i < insn_cnt; i++) {
11690 if (memcmp(&insn[i], &ja, sizeof(ja)))
11691 continue;
11692
11693 err = verifier_remove_insns(env, i, 1);
11694 if (err)
11695 return err;
11696 insn_cnt--;
11697 i--;
11698 }
11699
11700 return 0;
11701}
11702
d6c2308c
JW
11703static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11704 const union bpf_attr *attr)
a4b1d3c1 11705{
d6c2308c 11706 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 11707 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 11708 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 11709 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 11710 struct bpf_prog *new_prog;
d6c2308c 11711 bool rnd_hi32;
a4b1d3c1 11712
d6c2308c 11713 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 11714 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
11715 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11716 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11717 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
11718 for (i = 0; i < len; i++) {
11719 int adj_idx = i + delta;
11720 struct bpf_insn insn;
83a28819 11721 int load_reg;
a4b1d3c1 11722
d6c2308c 11723 insn = insns[adj_idx];
83a28819 11724 load_reg = insn_def_regno(&insn);
d6c2308c
JW
11725 if (!aux[adj_idx].zext_dst) {
11726 u8 code, class;
11727 u32 imm_rnd;
11728
11729 if (!rnd_hi32)
11730 continue;
11731
11732 code = insn.code;
11733 class = BPF_CLASS(code);
83a28819 11734 if (load_reg == -1)
d6c2308c
JW
11735 continue;
11736
11737 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
11738 * BPF_STX + SRC_OP, so it is safe to pass NULL
11739 * here.
d6c2308c 11740 */
83a28819 11741 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
11742 if (class == BPF_LD &&
11743 BPF_MODE(code) == BPF_IMM)
11744 i++;
11745 continue;
11746 }
11747
11748 /* ctx load could be transformed into wider load. */
11749 if (class == BPF_LDX &&
11750 aux[adj_idx].ptr_type == PTR_TO_CTX)
11751 continue;
11752
11753 imm_rnd = get_random_int();
11754 rnd_hi32_patch[0] = insn;
11755 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 11756 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
11757 patch = rnd_hi32_patch;
11758 patch_len = 4;
11759 goto apply_patch_buffer;
11760 }
11761
39491867
BJ
11762 /* Add in an zero-extend instruction if a) the JIT has requested
11763 * it or b) it's a CMPXCHG.
11764 *
11765 * The latter is because: BPF_CMPXCHG always loads a value into
11766 * R0, therefore always zero-extends. However some archs'
11767 * equivalent instruction only does this load when the
11768 * comparison is successful. This detail of CMPXCHG is
11769 * orthogonal to the general zero-extension behaviour of the
11770 * CPU, so it's treated independently of bpf_jit_needs_zext.
11771 */
11772 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
11773 continue;
11774
83a28819
IL
11775 if (WARN_ON(load_reg == -1)) {
11776 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11777 return -EFAULT;
b2e37a71
IL
11778 }
11779
a4b1d3c1 11780 zext_patch[0] = insn;
b2e37a71
IL
11781 zext_patch[1].dst_reg = load_reg;
11782 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
11783 patch = zext_patch;
11784 patch_len = 2;
11785apply_patch_buffer:
11786 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
11787 if (!new_prog)
11788 return -ENOMEM;
11789 env->prog = new_prog;
11790 insns = new_prog->insnsi;
11791 aux = env->insn_aux_data;
d6c2308c 11792 delta += patch_len - 1;
a4b1d3c1
JW
11793 }
11794
11795 return 0;
11796}
11797
c64b7983
JS
11798/* convert load instructions that access fields of a context type into a
11799 * sequence of instructions that access fields of the underlying structure:
11800 * struct __sk_buff -> struct sk_buff
11801 * struct bpf_sock_ops -> struct sock
9bac3d6d 11802 */
58e2af8b 11803static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 11804{
00176a34 11805 const struct bpf_verifier_ops *ops = env->ops;
f96da094 11806 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 11807 const int insn_cnt = env->prog->len;
36bbef52 11808 struct bpf_insn insn_buf[16], *insn;
46f53a65 11809 u32 target_size, size_default, off;
9bac3d6d 11810 struct bpf_prog *new_prog;
d691f9e8 11811 enum bpf_access_type type;
f96da094 11812 bool is_narrower_load;
9bac3d6d 11813
b09928b9
DB
11814 if (ops->gen_prologue || env->seen_direct_write) {
11815 if (!ops->gen_prologue) {
11816 verbose(env, "bpf verifier is misconfigured\n");
11817 return -EINVAL;
11818 }
36bbef52
DB
11819 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11820 env->prog);
11821 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11822 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11823 return -EINVAL;
11824 } else if (cnt) {
8041902d 11825 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11826 if (!new_prog)
11827 return -ENOMEM;
8041902d 11828
36bbef52 11829 env->prog = new_prog;
3df126f3 11830 delta += cnt - 1;
36bbef52
DB
11831 }
11832 }
11833
c64b7983 11834 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11835 return 0;
11836
3df126f3 11837 insn = env->prog->insnsi + delta;
36bbef52 11838
9bac3d6d 11839 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11840 bpf_convert_ctx_access_t convert_ctx_access;
11841
62c7989b
DB
11842 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11843 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11844 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11845 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11846 type = BPF_READ;
62c7989b
DB
11847 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11848 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11849 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11850 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11851 type = BPF_WRITE;
11852 else
9bac3d6d
AS
11853 continue;
11854
af86ca4e
AS
11855 if (type == BPF_WRITE &&
11856 env->insn_aux_data[i + delta].sanitize_stack_off) {
11857 struct bpf_insn patch[] = {
11858 /* Sanitize suspicious stack slot with zero.
11859 * There are no memory dependencies for this store,
11860 * since it's only using frame pointer and immediate
11861 * constant of zero
11862 */
11863 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11864 env->insn_aux_data[i + delta].sanitize_stack_off,
11865 0),
11866 /* the original STX instruction will immediately
11867 * overwrite the same stack slot with appropriate value
11868 */
11869 *insn,
11870 };
11871
11872 cnt = ARRAY_SIZE(patch);
11873 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11874 if (!new_prog)
11875 return -ENOMEM;
11876
11877 delta += cnt - 1;
11878 env->prog = new_prog;
11879 insn = new_prog->insnsi + i + delta;
11880 continue;
11881 }
11882
c64b7983
JS
11883 switch (env->insn_aux_data[i + delta].ptr_type) {
11884 case PTR_TO_CTX:
11885 if (!ops->convert_ctx_access)
11886 continue;
11887 convert_ctx_access = ops->convert_ctx_access;
11888 break;
11889 case PTR_TO_SOCKET:
46f8bc92 11890 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11891 convert_ctx_access = bpf_sock_convert_ctx_access;
11892 break;
655a51e5
MKL
11893 case PTR_TO_TCP_SOCK:
11894 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11895 break;
fada7fdc
JL
11896 case PTR_TO_XDP_SOCK:
11897 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11898 break;
2a02759e 11899 case PTR_TO_BTF_ID:
27ae7997
MKL
11900 if (type == BPF_READ) {
11901 insn->code = BPF_LDX | BPF_PROBE_MEM |
11902 BPF_SIZE((insn)->code);
11903 env->prog->aux->num_exentries++;
7e40781c 11904 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11905 verbose(env, "Writes through BTF pointers are not allowed\n");
11906 return -EINVAL;
11907 }
2a02759e 11908 continue;
c64b7983 11909 default:
9bac3d6d 11910 continue;
c64b7983 11911 }
9bac3d6d 11912
31fd8581 11913 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11914 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11915
11916 /* If the read access is a narrower load of the field,
11917 * convert to a 4/8-byte load, to minimum program type specific
11918 * convert_ctx_access changes. If conversion is successful,
11919 * we will apply proper mask to the result.
11920 */
f96da094 11921 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11922 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11923 off = insn->off;
31fd8581 11924 if (is_narrower_load) {
f96da094
DB
11925 u8 size_code;
11926
11927 if (type == BPF_WRITE) {
61bd5218 11928 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
11929 return -EINVAL;
11930 }
31fd8581 11931
f96da094 11932 size_code = BPF_H;
31fd8581
YS
11933 if (ctx_field_size == 4)
11934 size_code = BPF_W;
11935 else if (ctx_field_size == 8)
11936 size_code = BPF_DW;
f96da094 11937
bc23105c 11938 insn->off = off & ~(size_default - 1);
31fd8581
YS
11939 insn->code = BPF_LDX | BPF_MEM | size_code;
11940 }
f96da094
DB
11941
11942 target_size = 0;
c64b7983
JS
11943 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11944 &target_size);
f96da094
DB
11945 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11946 (ctx_field_size && !target_size)) {
61bd5218 11947 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
11948 return -EINVAL;
11949 }
f96da094
DB
11950
11951 if (is_narrower_load && size < target_size) {
d895a0f1
IL
11952 u8 shift = bpf_ctx_narrow_access_offset(
11953 off, size, size_default) * 8;
46f53a65
AI
11954 if (ctx_field_size <= 4) {
11955 if (shift)
11956 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11957 insn->dst_reg,
11958 shift);
31fd8581 11959 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 11960 (1 << size * 8) - 1);
46f53a65
AI
11961 } else {
11962 if (shift)
11963 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11964 insn->dst_reg,
11965 shift);
31fd8581 11966 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 11967 (1ULL << size * 8) - 1);
46f53a65 11968 }
31fd8581 11969 }
9bac3d6d 11970
8041902d 11971 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
11972 if (!new_prog)
11973 return -ENOMEM;
11974
3df126f3 11975 delta += cnt - 1;
9bac3d6d
AS
11976
11977 /* keep walking new program and skip insns we just inserted */
11978 env->prog = new_prog;
3df126f3 11979 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
11980 }
11981
11982 return 0;
11983}
11984
1c2a088a
AS
11985static int jit_subprogs(struct bpf_verifier_env *env)
11986{
11987 struct bpf_prog *prog = env->prog, **func, *tmp;
11988 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 11989 struct bpf_map *map_ptr;
7105e828 11990 struct bpf_insn *insn;
1c2a088a 11991 void *old_bpf_func;
c4c0bdc0 11992 int err, num_exentries;
1c2a088a 11993
f910cefa 11994 if (env->subprog_cnt <= 1)
1c2a088a
AS
11995 return 0;
11996
7105e828 11997 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11998 if (bpf_pseudo_func(insn)) {
11999 env->insn_aux_data[i].call_imm = insn->imm;
12000 /* subprog is encoded in insn[1].imm */
12001 continue;
12002 }
12003
23a2d70c 12004 if (!bpf_pseudo_call(insn))
1c2a088a 12005 continue;
c7a89784
DB
12006 /* Upon error here we cannot fall back to interpreter but
12007 * need a hard reject of the program. Thus -EFAULT is
12008 * propagated in any case.
12009 */
1c2a088a
AS
12010 subprog = find_subprog(env, i + insn->imm + 1);
12011 if (subprog < 0) {
12012 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12013 i + insn->imm + 1);
12014 return -EFAULT;
12015 }
12016 /* temporarily remember subprog id inside insn instead of
12017 * aux_data, since next loop will split up all insns into funcs
12018 */
f910cefa 12019 insn->off = subprog;
1c2a088a
AS
12020 /* remember original imm in case JIT fails and fallback
12021 * to interpreter will be needed
12022 */
12023 env->insn_aux_data[i].call_imm = insn->imm;
12024 /* point imm to __bpf_call_base+1 from JITs point of view */
12025 insn->imm = 1;
12026 }
12027
c454a46b
MKL
12028 err = bpf_prog_alloc_jited_linfo(prog);
12029 if (err)
12030 goto out_undo_insn;
12031
12032 err = -ENOMEM;
6396bb22 12033 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 12034 if (!func)
c7a89784 12035 goto out_undo_insn;
1c2a088a 12036
f910cefa 12037 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 12038 subprog_start = subprog_end;
4cb3d99c 12039 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
12040
12041 len = subprog_end - subprog_start;
492ecee8
AS
12042 /* BPF_PROG_RUN doesn't call subprogs directly,
12043 * hence main prog stats include the runtime of subprogs.
12044 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 12045 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
12046 */
12047 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
12048 if (!func[i])
12049 goto out_free;
12050 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12051 len * sizeof(struct bpf_insn));
4f74d809 12052 func[i]->type = prog->type;
1c2a088a 12053 func[i]->len = len;
4f74d809
DB
12054 if (bpf_prog_calc_tag(func[i]))
12055 goto out_free;
1c2a088a 12056 func[i]->is_func = 1;
ba64e7d8
YS
12057 func[i]->aux->func_idx = i;
12058 /* the btf and func_info will be freed only at prog->aux */
12059 func[i]->aux->btf = prog->aux->btf;
12060 func[i]->aux->func_info = prog->aux->func_info;
12061
a748c697
MF
12062 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12063 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
12064 int ret;
12065
12066 if (!(insn_idx >= subprog_start &&
12067 insn_idx <= subprog_end))
12068 continue;
12069
12070 ret = bpf_jit_add_poke_descriptor(func[i],
12071 &prog->aux->poke_tab[j]);
12072 if (ret < 0) {
12073 verbose(env, "adding tail call poke descriptor failed\n");
12074 goto out_free;
12075 }
12076
12077 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
12078
12079 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
12080 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
12081 if (ret < 0) {
12082 verbose(env, "tracking tail call prog failed\n");
12083 goto out_free;
12084 }
12085 }
12086
1c2a088a
AS
12087 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12088 * Long term would need debug info to populate names
12089 */
12090 func[i]->aux->name[0] = 'F';
9c8105bd 12091 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 12092 func[i]->jit_requested = 1;
e6ac2450 12093 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
c454a46b
MKL
12094 func[i]->aux->linfo = prog->aux->linfo;
12095 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12096 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12097 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
12098 num_exentries = 0;
12099 insn = func[i]->insnsi;
12100 for (j = 0; j < func[i]->len; j++, insn++) {
12101 if (BPF_CLASS(insn->code) == BPF_LDX &&
12102 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12103 num_exentries++;
12104 }
12105 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 12106 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
12107 func[i] = bpf_int_jit_compile(func[i]);
12108 if (!func[i]->jited) {
12109 err = -ENOTSUPP;
12110 goto out_free;
12111 }
12112 cond_resched();
12113 }
a748c697
MF
12114
12115 /* Untrack main program's aux structs so that during map_poke_run()
12116 * we will not stumble upon the unfilled poke descriptors; each
12117 * of the main program's poke descs got distributed across subprogs
12118 * and got tracked onto map, so we are sure that none of them will
12119 * be missed after the operation below
12120 */
12121 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12122 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12123
12124 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12125 }
12126
1c2a088a
AS
12127 /* at this point all bpf functions were successfully JITed
12128 * now populate all bpf_calls with correct addresses and
12129 * run last pass of JIT
12130 */
f910cefa 12131 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12132 insn = func[i]->insnsi;
12133 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba
YS
12134 if (bpf_pseudo_func(insn)) {
12135 subprog = insn[1].imm;
12136 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12137 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12138 continue;
12139 }
23a2d70c 12140 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12141 continue;
12142 subprog = insn->off;
0d306c31
PB
12143 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12144 __bpf_call_base;
1c2a088a 12145 }
2162fed4
SD
12146
12147 /* we use the aux data to keep a list of the start addresses
12148 * of the JITed images for each function in the program
12149 *
12150 * for some architectures, such as powerpc64, the imm field
12151 * might not be large enough to hold the offset of the start
12152 * address of the callee's JITed image from __bpf_call_base
12153 *
12154 * in such cases, we can lookup the start address of a callee
12155 * by using its subprog id, available from the off field of
12156 * the call instruction, as an index for this list
12157 */
12158 func[i]->aux->func = func;
12159 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 12160 }
f910cefa 12161 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12162 old_bpf_func = func[i]->bpf_func;
12163 tmp = bpf_int_jit_compile(func[i]);
12164 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12165 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 12166 err = -ENOTSUPP;
1c2a088a
AS
12167 goto out_free;
12168 }
12169 cond_resched();
12170 }
12171
12172 /* finally lock prog and jit images for all functions and
12173 * populate kallsysm
12174 */
f910cefa 12175 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12176 bpf_prog_lock_ro(func[i]);
12177 bpf_prog_kallsyms_add(func[i]);
12178 }
7105e828
DB
12179
12180 /* Last step: make now unused interpreter insns from main
12181 * prog consistent for later dump requests, so they can
12182 * later look the same as if they were interpreted only.
12183 */
12184 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
12185 if (bpf_pseudo_func(insn)) {
12186 insn[0].imm = env->insn_aux_data[i].call_imm;
12187 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12188 continue;
12189 }
23a2d70c 12190 if (!bpf_pseudo_call(insn))
7105e828
DB
12191 continue;
12192 insn->off = env->insn_aux_data[i].call_imm;
12193 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 12194 insn->imm = subprog;
7105e828
DB
12195 }
12196
1c2a088a
AS
12197 prog->jited = 1;
12198 prog->bpf_func = func[0]->bpf_func;
12199 prog->aux->func = func;
f910cefa 12200 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 12201 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12202 return 0;
12203out_free:
a748c697
MF
12204 for (i = 0; i < env->subprog_cnt; i++) {
12205 if (!func[i])
12206 continue;
12207
12208 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12209 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12210 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12211 }
12212 bpf_jit_free(func[i]);
12213 }
1c2a088a 12214 kfree(func);
c7a89784 12215out_undo_insn:
1c2a088a
AS
12216 /* cleanup main prog to be interpreted */
12217 prog->jit_requested = 0;
12218 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 12219 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12220 continue;
12221 insn->off = 0;
12222 insn->imm = env->insn_aux_data[i].call_imm;
12223 }
e16301fb 12224 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12225 return err;
12226}
12227
1ea47e01
AS
12228static int fixup_call_args(struct bpf_verifier_env *env)
12229{
19d28fbd 12230#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
12231 struct bpf_prog *prog = env->prog;
12232 struct bpf_insn *insn = prog->insnsi;
e6ac2450 12233 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 12234 int i, depth;
19d28fbd 12235#endif
e4052d06 12236 int err = 0;
1ea47e01 12237
e4052d06
QM
12238 if (env->prog->jit_requested &&
12239 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
12240 err = jit_subprogs(env);
12241 if (err == 0)
1c2a088a 12242 return 0;
c7a89784
DB
12243 if (err == -EFAULT)
12244 return err;
19d28fbd
DM
12245 }
12246#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
12247 if (has_kfunc_call) {
12248 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12249 return -EINVAL;
12250 }
e411901c
MF
12251 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12252 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12253 * have to be rejected, since interpreter doesn't support them yet.
12254 */
12255 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12256 return -EINVAL;
12257 }
1ea47e01 12258 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
12259 if (bpf_pseudo_func(insn)) {
12260 /* When JIT fails the progs with callback calls
12261 * have to be rejected, since interpreter doesn't support them yet.
12262 */
12263 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12264 return -EINVAL;
12265 }
12266
23a2d70c 12267 if (!bpf_pseudo_call(insn))
1ea47e01
AS
12268 continue;
12269 depth = get_callee_stack_depth(env, insn, i);
12270 if (depth < 0)
12271 return depth;
12272 bpf_patch_call_args(insn, depth);
12273 }
19d28fbd
DM
12274 err = 0;
12275#endif
12276 return err;
1ea47e01
AS
12277}
12278
e6ac2450
MKL
12279static int fixup_kfunc_call(struct bpf_verifier_env *env,
12280 struct bpf_insn *insn)
12281{
12282 const struct bpf_kfunc_desc *desc;
12283
12284 /* insn->imm has the btf func_id. Replace it with
12285 * an address (relative to __bpf_base_call).
12286 */
12287 desc = find_kfunc_desc(env->prog, insn->imm);
12288 if (!desc) {
12289 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12290 insn->imm);
12291 return -EFAULT;
12292 }
12293
12294 insn->imm = desc->imm;
12295
12296 return 0;
12297}
12298
e6ac5933
BJ
12299/* Do various post-verification rewrites in a single program pass.
12300 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 12301 */
e6ac5933 12302static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 12303{
79741b3b 12304 struct bpf_prog *prog = env->prog;
d2e4c1e6 12305 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 12306 struct bpf_insn *insn = prog->insnsi;
e245c5c6 12307 const struct bpf_func_proto *fn;
79741b3b 12308 const int insn_cnt = prog->len;
09772d92 12309 const struct bpf_map_ops *ops;
c93552c4 12310 struct bpf_insn_aux_data *aux;
81ed18ab
AS
12311 struct bpf_insn insn_buf[16];
12312 struct bpf_prog *new_prog;
12313 struct bpf_map *map_ptr;
d2e4c1e6 12314 int i, ret, cnt, delta = 0;
e245c5c6 12315
79741b3b 12316 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 12317 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
12318 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12319 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12320 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 12321 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 12322 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
12323 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12324 struct bpf_insn *patchlet;
12325 struct bpf_insn chk_and_div[] = {
9b00f1b7 12326 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
12327 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12328 BPF_JNE | BPF_K, insn->src_reg,
12329 0, 2, 0),
f6b1b3bf
DB
12330 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12331 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12332 *insn,
12333 };
e88b2c6e 12334 struct bpf_insn chk_and_mod[] = {
9b00f1b7 12335 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
12336 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12337 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 12338 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 12339 *insn,
9b00f1b7
DB
12340 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12341 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 12342 };
f6b1b3bf 12343
e88b2c6e
DB
12344 patchlet = isdiv ? chk_and_div : chk_and_mod;
12345 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 12346 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
12347
12348 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
12349 if (!new_prog)
12350 return -ENOMEM;
12351
12352 delta += cnt - 1;
12353 env->prog = prog = new_prog;
12354 insn = new_prog->insnsi + i + delta;
12355 continue;
12356 }
12357
e6ac5933 12358 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
12359 if (BPF_CLASS(insn->code) == BPF_LD &&
12360 (BPF_MODE(insn->code) == BPF_ABS ||
12361 BPF_MODE(insn->code) == BPF_IND)) {
12362 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12363 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12364 verbose(env, "bpf verifier is misconfigured\n");
12365 return -EINVAL;
12366 }
12367
12368 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12369 if (!new_prog)
12370 return -ENOMEM;
12371
12372 delta += cnt - 1;
12373 env->prog = prog = new_prog;
12374 insn = new_prog->insnsi + i + delta;
12375 continue;
12376 }
12377
e6ac5933 12378 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
12379 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12380 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12381 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12382 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 12383 struct bpf_insn *patch = &insn_buf[0];
801c6058 12384 bool issrc, isneg, isimm;
979d63d5
DB
12385 u32 off_reg;
12386
12387 aux = &env->insn_aux_data[i + delta];
3612af78
DB
12388 if (!aux->alu_state ||
12389 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
12390 continue;
12391
12392 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12393 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12394 BPF_ALU_SANITIZE_SRC;
801c6058 12395 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
12396
12397 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
12398 if (isimm) {
12399 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12400 } else {
12401 if (isneg)
12402 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12403 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12404 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12405 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12406 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12407 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12408 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12409 }
b9b34ddb
DB
12410 if (!issrc)
12411 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12412 insn->src_reg = BPF_REG_AX;
979d63d5
DB
12413 if (isneg)
12414 insn->code = insn->code == code_add ?
12415 code_sub : code_add;
12416 *patch++ = *insn;
801c6058 12417 if (issrc && isneg && !isimm)
979d63d5
DB
12418 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12419 cnt = patch - insn_buf;
12420
12421 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12422 if (!new_prog)
12423 return -ENOMEM;
12424
12425 delta += cnt - 1;
12426 env->prog = prog = new_prog;
12427 insn = new_prog->insnsi + i + delta;
12428 continue;
12429 }
12430
79741b3b
AS
12431 if (insn->code != (BPF_JMP | BPF_CALL))
12432 continue;
cc8b0b92
AS
12433 if (insn->src_reg == BPF_PSEUDO_CALL)
12434 continue;
e6ac2450
MKL
12435 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12436 ret = fixup_kfunc_call(env, insn);
12437 if (ret)
12438 return ret;
12439 continue;
12440 }
e245c5c6 12441
79741b3b
AS
12442 if (insn->imm == BPF_FUNC_get_route_realm)
12443 prog->dst_needed = 1;
12444 if (insn->imm == BPF_FUNC_get_prandom_u32)
12445 bpf_user_rnd_init_once();
9802d865
JB
12446 if (insn->imm == BPF_FUNC_override_return)
12447 prog->kprobe_override = 1;
79741b3b 12448 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
12449 /* If we tail call into other programs, we
12450 * cannot make any assumptions since they can
12451 * be replaced dynamically during runtime in
12452 * the program array.
12453 */
12454 prog->cb_access = 1;
e411901c
MF
12455 if (!allow_tail_call_in_subprogs(env))
12456 prog->aux->stack_depth = MAX_BPF_STACK;
12457 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 12458
79741b3b
AS
12459 /* mark bpf_tail_call as different opcode to avoid
12460 * conditional branch in the interpeter for every normal
12461 * call and to prevent accidental JITing by JIT compiler
12462 * that doesn't support bpf_tail_call yet
e245c5c6 12463 */
79741b3b 12464 insn->imm = 0;
71189fa9 12465 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 12466
c93552c4 12467 aux = &env->insn_aux_data[i + delta];
2c78ee89 12468 if (env->bpf_capable && !expect_blinding &&
cc52d914 12469 prog->jit_requested &&
d2e4c1e6
DB
12470 !bpf_map_key_poisoned(aux) &&
12471 !bpf_map_ptr_poisoned(aux) &&
12472 !bpf_map_ptr_unpriv(aux)) {
12473 struct bpf_jit_poke_descriptor desc = {
12474 .reason = BPF_POKE_REASON_TAIL_CALL,
12475 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12476 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 12477 .insn_idx = i + delta,
d2e4c1e6
DB
12478 };
12479
12480 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12481 if (ret < 0) {
12482 verbose(env, "adding tail call poke descriptor failed\n");
12483 return ret;
12484 }
12485
12486 insn->imm = ret + 1;
12487 continue;
12488 }
12489
c93552c4
DB
12490 if (!bpf_map_ptr_unpriv(aux))
12491 continue;
12492
b2157399
AS
12493 /* instead of changing every JIT dealing with tail_call
12494 * emit two extra insns:
12495 * if (index >= max_entries) goto out;
12496 * index &= array->index_mask;
12497 * to avoid out-of-bounds cpu speculation
12498 */
c93552c4 12499 if (bpf_map_ptr_poisoned(aux)) {
40950343 12500 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
12501 return -EINVAL;
12502 }
c93552c4 12503
d2e4c1e6 12504 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
12505 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12506 map_ptr->max_entries, 2);
12507 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12508 container_of(map_ptr,
12509 struct bpf_array,
12510 map)->index_mask);
12511 insn_buf[2] = *insn;
12512 cnt = 3;
12513 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12514 if (!new_prog)
12515 return -ENOMEM;
12516
12517 delta += cnt - 1;
12518 env->prog = prog = new_prog;
12519 insn = new_prog->insnsi + i + delta;
79741b3b
AS
12520 continue;
12521 }
e245c5c6 12522
89c63074 12523 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
12524 * and other inlining handlers are currently limited to 64 bit
12525 * only.
89c63074 12526 */
60b58afc 12527 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
12528 (insn->imm == BPF_FUNC_map_lookup_elem ||
12529 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
12530 insn->imm == BPF_FUNC_map_delete_elem ||
12531 insn->imm == BPF_FUNC_map_push_elem ||
12532 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f
BT
12533 insn->imm == BPF_FUNC_map_peek_elem ||
12534 insn->imm == BPF_FUNC_redirect_map)) {
c93552c4
DB
12535 aux = &env->insn_aux_data[i + delta];
12536 if (bpf_map_ptr_poisoned(aux))
12537 goto patch_call_imm;
12538
d2e4c1e6 12539 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
12540 ops = map_ptr->ops;
12541 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12542 ops->map_gen_lookup) {
12543 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
12544 if (cnt == -EOPNOTSUPP)
12545 goto patch_map_ops_generic;
12546 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
12547 verbose(env, "bpf verifier is misconfigured\n");
12548 return -EINVAL;
12549 }
81ed18ab 12550
09772d92
DB
12551 new_prog = bpf_patch_insn_data(env, i + delta,
12552 insn_buf, cnt);
12553 if (!new_prog)
12554 return -ENOMEM;
81ed18ab 12555
09772d92
DB
12556 delta += cnt - 1;
12557 env->prog = prog = new_prog;
12558 insn = new_prog->insnsi + i + delta;
12559 continue;
12560 }
81ed18ab 12561
09772d92
DB
12562 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12563 (void *(*)(struct bpf_map *map, void *key))NULL));
12564 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12565 (int (*)(struct bpf_map *map, void *key))NULL));
12566 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12567 (int (*)(struct bpf_map *map, void *key, void *value,
12568 u64 flags))NULL));
84430d42
DB
12569 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12570 (int (*)(struct bpf_map *map, void *value,
12571 u64 flags))NULL));
12572 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12573 (int (*)(struct bpf_map *map, void *value))NULL));
12574 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12575 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f
BT
12576 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12577 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12578
4a8f87e6 12579patch_map_ops_generic:
09772d92
DB
12580 switch (insn->imm) {
12581 case BPF_FUNC_map_lookup_elem:
12582 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12583 __bpf_call_base;
12584 continue;
12585 case BPF_FUNC_map_update_elem:
12586 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12587 __bpf_call_base;
12588 continue;
12589 case BPF_FUNC_map_delete_elem:
12590 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12591 __bpf_call_base;
12592 continue;
84430d42
DB
12593 case BPF_FUNC_map_push_elem:
12594 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12595 __bpf_call_base;
12596 continue;
12597 case BPF_FUNC_map_pop_elem:
12598 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12599 __bpf_call_base;
12600 continue;
12601 case BPF_FUNC_map_peek_elem:
12602 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12603 __bpf_call_base;
12604 continue;
e6a4750f
BT
12605 case BPF_FUNC_redirect_map:
12606 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12607 __bpf_call_base;
12608 continue;
09772d92 12609 }
81ed18ab 12610
09772d92 12611 goto patch_call_imm;
81ed18ab
AS
12612 }
12613
e6ac5933 12614 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
12615 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12616 insn->imm == BPF_FUNC_jiffies64) {
12617 struct bpf_insn ld_jiffies_addr[2] = {
12618 BPF_LD_IMM64(BPF_REG_0,
12619 (unsigned long)&jiffies),
12620 };
12621
12622 insn_buf[0] = ld_jiffies_addr[0];
12623 insn_buf[1] = ld_jiffies_addr[1];
12624 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12625 BPF_REG_0, 0);
12626 cnt = 3;
12627
12628 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12629 cnt);
12630 if (!new_prog)
12631 return -ENOMEM;
12632
12633 delta += cnt - 1;
12634 env->prog = prog = new_prog;
12635 insn = new_prog->insnsi + i + delta;
12636 continue;
12637 }
12638
81ed18ab 12639patch_call_imm:
5e43f899 12640 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
12641 /* all functions that have prototype and verifier allowed
12642 * programs to call them, must be real in-kernel functions
12643 */
12644 if (!fn->func) {
61bd5218
JK
12645 verbose(env,
12646 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
12647 func_id_name(insn->imm), insn->imm);
12648 return -EFAULT;
e245c5c6 12649 }
79741b3b 12650 insn->imm = fn->func - __bpf_call_base;
e245c5c6 12651 }
e245c5c6 12652
d2e4c1e6
DB
12653 /* Since poke tab is now finalized, publish aux to tracker. */
12654 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12655 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12656 if (!map_ptr->ops->map_poke_track ||
12657 !map_ptr->ops->map_poke_untrack ||
12658 !map_ptr->ops->map_poke_run) {
12659 verbose(env, "bpf verifier is misconfigured\n");
12660 return -EINVAL;
12661 }
12662
12663 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12664 if (ret < 0) {
12665 verbose(env, "tracking tail call prog failed\n");
12666 return ret;
12667 }
12668 }
12669
e6ac2450
MKL
12670 sort_kfunc_descs_by_imm(env->prog);
12671
79741b3b
AS
12672 return 0;
12673}
e245c5c6 12674
58e2af8b 12675static void free_states(struct bpf_verifier_env *env)
f1bca824 12676{
58e2af8b 12677 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
12678 int i;
12679
9f4686c4
AS
12680 sl = env->free_list;
12681 while (sl) {
12682 sln = sl->next;
12683 free_verifier_state(&sl->state, false);
12684 kfree(sl);
12685 sl = sln;
12686 }
51c39bb1 12687 env->free_list = NULL;
9f4686c4 12688
f1bca824
AS
12689 if (!env->explored_states)
12690 return;
12691
dc2a4ebc 12692 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
12693 sl = env->explored_states[i];
12694
a8f500af
AS
12695 while (sl) {
12696 sln = sl->next;
12697 free_verifier_state(&sl->state, false);
12698 kfree(sl);
12699 sl = sln;
12700 }
51c39bb1 12701 env->explored_states[i] = NULL;
f1bca824 12702 }
51c39bb1 12703}
f1bca824 12704
51c39bb1
AS
12705/* The verifier is using insn_aux_data[] to store temporary data during
12706 * verification and to store information for passes that run after the
12707 * verification like dead code sanitization. do_check_common() for subprogram N
12708 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12709 * temporary data after do_check_common() finds that subprogram N cannot be
12710 * verified independently. pass_cnt counts the number of times
12711 * do_check_common() was run and insn->aux->seen tells the pass number
12712 * insn_aux_data was touched. These variables are compared to clear temporary
12713 * data from failed pass. For testing and experiments do_check_common() can be
12714 * run multiple times even when prior attempt to verify is unsuccessful.
12715 */
12716static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12717{
12718 struct bpf_insn *insn = env->prog->insnsi;
12719 struct bpf_insn_aux_data *aux;
12720 int i, class;
12721
12722 for (i = 0; i < env->prog->len; i++) {
12723 class = BPF_CLASS(insn[i].code);
12724 if (class != BPF_LDX && class != BPF_STX)
12725 continue;
12726 aux = &env->insn_aux_data[i];
12727 if (aux->seen != env->pass_cnt)
12728 continue;
12729 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12730 }
f1bca824
AS
12731}
12732
51c39bb1
AS
12733static int do_check_common(struct bpf_verifier_env *env, int subprog)
12734{
6f8a57cc 12735 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
12736 struct bpf_verifier_state *state;
12737 struct bpf_reg_state *regs;
12738 int ret, i;
12739
12740 env->prev_linfo = NULL;
12741 env->pass_cnt++;
12742
12743 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12744 if (!state)
12745 return -ENOMEM;
12746 state->curframe = 0;
12747 state->speculative = false;
12748 state->branches = 1;
12749 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12750 if (!state->frame[0]) {
12751 kfree(state);
12752 return -ENOMEM;
12753 }
12754 env->cur_state = state;
12755 init_func_state(env, state->frame[0],
12756 BPF_MAIN_FUNC /* callsite */,
12757 0 /* frameno */,
12758 subprog);
12759
12760 regs = state->frame[state->curframe]->regs;
be8704ff 12761 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
12762 ret = btf_prepare_func_args(env, subprog, regs);
12763 if (ret)
12764 goto out;
12765 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12766 if (regs[i].type == PTR_TO_CTX)
12767 mark_reg_known_zero(env, regs, i);
12768 else if (regs[i].type == SCALAR_VALUE)
12769 mark_reg_unknown(env, regs, i);
e5069b9c
DB
12770 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12771 const u32 mem_size = regs[i].mem_size;
12772
12773 mark_reg_known_zero(env, regs, i);
12774 regs[i].mem_size = mem_size;
12775 regs[i].id = ++env->id_gen;
12776 }
51c39bb1
AS
12777 }
12778 } else {
12779 /* 1st arg to a function */
12780 regs[BPF_REG_1].type = PTR_TO_CTX;
12781 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 12782 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
12783 if (ret == -EFAULT)
12784 /* unlikely verifier bug. abort.
12785 * ret == 0 and ret < 0 are sadly acceptable for
12786 * main() function due to backward compatibility.
12787 * Like socket filter program may be written as:
12788 * int bpf_prog(struct pt_regs *ctx)
12789 * and never dereference that ctx in the program.
12790 * 'struct pt_regs' is a type mismatch for socket
12791 * filter that should be using 'struct __sk_buff'.
12792 */
12793 goto out;
12794 }
12795
12796 ret = do_check(env);
12797out:
f59bbfc2
AS
12798 /* check for NULL is necessary, since cur_state can be freed inside
12799 * do_check() under memory pressure.
12800 */
12801 if (env->cur_state) {
12802 free_verifier_state(env->cur_state, true);
12803 env->cur_state = NULL;
12804 }
6f8a57cc
AN
12805 while (!pop_stack(env, NULL, NULL, false));
12806 if (!ret && pop_log)
12807 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
12808 free_states(env);
12809 if (ret)
12810 /* clean aux data in case subprog was rejected */
12811 sanitize_insn_aux_data(env);
12812 return ret;
12813}
12814
12815/* Verify all global functions in a BPF program one by one based on their BTF.
12816 * All global functions must pass verification. Otherwise the whole program is rejected.
12817 * Consider:
12818 * int bar(int);
12819 * int foo(int f)
12820 * {
12821 * return bar(f);
12822 * }
12823 * int bar(int b)
12824 * {
12825 * ...
12826 * }
12827 * foo() will be verified first for R1=any_scalar_value. During verification it
12828 * will be assumed that bar() already verified successfully and call to bar()
12829 * from foo() will be checked for type match only. Later bar() will be verified
12830 * independently to check that it's safe for R1=any_scalar_value.
12831 */
12832static int do_check_subprogs(struct bpf_verifier_env *env)
12833{
12834 struct bpf_prog_aux *aux = env->prog->aux;
12835 int i, ret;
12836
12837 if (!aux->func_info)
12838 return 0;
12839
12840 for (i = 1; i < env->subprog_cnt; i++) {
12841 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12842 continue;
12843 env->insn_idx = env->subprog_info[i].start;
12844 WARN_ON_ONCE(env->insn_idx == 0);
12845 ret = do_check_common(env, i);
12846 if (ret) {
12847 return ret;
12848 } else if (env->log.level & BPF_LOG_LEVEL) {
12849 verbose(env,
12850 "Func#%d is safe for any args that match its prototype\n",
12851 i);
12852 }
12853 }
12854 return 0;
12855}
12856
12857static int do_check_main(struct bpf_verifier_env *env)
12858{
12859 int ret;
12860
12861 env->insn_idx = 0;
12862 ret = do_check_common(env, 0);
12863 if (!ret)
12864 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12865 return ret;
12866}
12867
12868
06ee7115
AS
12869static void print_verification_stats(struct bpf_verifier_env *env)
12870{
12871 int i;
12872
12873 if (env->log.level & BPF_LOG_STATS) {
12874 verbose(env, "verification time %lld usec\n",
12875 div_u64(env->verification_time, 1000));
12876 verbose(env, "stack depth ");
12877 for (i = 0; i < env->subprog_cnt; i++) {
12878 u32 depth = env->subprog_info[i].stack_depth;
12879
12880 verbose(env, "%d", depth);
12881 if (i + 1 < env->subprog_cnt)
12882 verbose(env, "+");
12883 }
12884 verbose(env, "\n");
12885 }
12886 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12887 "total_states %d peak_states %d mark_read %d\n",
12888 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12889 env->max_states_per_insn, env->total_states,
12890 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12891}
12892
27ae7997
MKL
12893static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12894{
12895 const struct btf_type *t, *func_proto;
12896 const struct bpf_struct_ops *st_ops;
12897 const struct btf_member *member;
12898 struct bpf_prog *prog = env->prog;
12899 u32 btf_id, member_idx;
12900 const char *mname;
12901
12aa8a94
THJ
12902 if (!prog->gpl_compatible) {
12903 verbose(env, "struct ops programs must have a GPL compatible license\n");
12904 return -EINVAL;
12905 }
12906
27ae7997
MKL
12907 btf_id = prog->aux->attach_btf_id;
12908 st_ops = bpf_struct_ops_find(btf_id);
12909 if (!st_ops) {
12910 verbose(env, "attach_btf_id %u is not a supported struct\n",
12911 btf_id);
12912 return -ENOTSUPP;
12913 }
12914
12915 t = st_ops->type;
12916 member_idx = prog->expected_attach_type;
12917 if (member_idx >= btf_type_vlen(t)) {
12918 verbose(env, "attach to invalid member idx %u of struct %s\n",
12919 member_idx, st_ops->name);
12920 return -EINVAL;
12921 }
12922
12923 member = &btf_type_member(t)[member_idx];
12924 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12925 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12926 NULL);
12927 if (!func_proto) {
12928 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12929 mname, member_idx, st_ops->name);
12930 return -EINVAL;
12931 }
12932
12933 if (st_ops->check_member) {
12934 int err = st_ops->check_member(t, member);
12935
12936 if (err) {
12937 verbose(env, "attach to unsupported member %s of struct %s\n",
12938 mname, st_ops->name);
12939 return err;
12940 }
12941 }
12942
12943 prog->aux->attach_func_proto = func_proto;
12944 prog->aux->attach_func_name = mname;
12945 env->ops = st_ops->verifier_ops;
12946
12947 return 0;
12948}
6ba43b76
KS
12949#define SECURITY_PREFIX "security_"
12950
f7b12b6f 12951static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12952{
69191754 12953 if (within_error_injection_list(addr) ||
f7b12b6f 12954 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12955 return 0;
6ba43b76 12956
6ba43b76
KS
12957 return -EINVAL;
12958}
27ae7997 12959
1e6c62a8
AS
12960/* list of non-sleepable functions that are otherwise on
12961 * ALLOW_ERROR_INJECTION list
12962 */
12963BTF_SET_START(btf_non_sleepable_error_inject)
12964/* Three functions below can be called from sleepable and non-sleepable context.
12965 * Assume non-sleepable from bpf safety point of view.
12966 */
12967BTF_ID(func, __add_to_page_cache_locked)
12968BTF_ID(func, should_fail_alloc_page)
12969BTF_ID(func, should_failslab)
12970BTF_SET_END(btf_non_sleepable_error_inject)
12971
12972static int check_non_sleepable_error_inject(u32 btf_id)
12973{
12974 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12975}
12976
f7b12b6f
THJ
12977int bpf_check_attach_target(struct bpf_verifier_log *log,
12978 const struct bpf_prog *prog,
12979 const struct bpf_prog *tgt_prog,
12980 u32 btf_id,
12981 struct bpf_attach_target_info *tgt_info)
38207291 12982{
be8704ff 12983 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 12984 const char prefix[] = "btf_trace_";
5b92a28a 12985 int ret = 0, subprog = -1, i;
38207291 12986 const struct btf_type *t;
5b92a28a 12987 bool conservative = true;
38207291 12988 const char *tname;
5b92a28a 12989 struct btf *btf;
f7b12b6f 12990 long addr = 0;
38207291 12991
f1b9509c 12992 if (!btf_id) {
efc68158 12993 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
12994 return -EINVAL;
12995 }
22dc4a0f 12996 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 12997 if (!btf) {
efc68158 12998 bpf_log(log,
5b92a28a
AS
12999 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13000 return -EINVAL;
13001 }
13002 t = btf_type_by_id(btf, btf_id);
f1b9509c 13003 if (!t) {
efc68158 13004 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
13005 return -EINVAL;
13006 }
5b92a28a 13007 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 13008 if (!tname) {
efc68158 13009 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
13010 return -EINVAL;
13011 }
5b92a28a
AS
13012 if (tgt_prog) {
13013 struct bpf_prog_aux *aux = tgt_prog->aux;
13014
13015 for (i = 0; i < aux->func_info_cnt; i++)
13016 if (aux->func_info[i].type_id == btf_id) {
13017 subprog = i;
13018 break;
13019 }
13020 if (subprog == -1) {
efc68158 13021 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
13022 return -EINVAL;
13023 }
13024 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
13025 if (prog_extension) {
13026 if (conservative) {
efc68158 13027 bpf_log(log,
be8704ff
AS
13028 "Cannot replace static functions\n");
13029 return -EINVAL;
13030 }
13031 if (!prog->jit_requested) {
efc68158 13032 bpf_log(log,
be8704ff
AS
13033 "Extension programs should be JITed\n");
13034 return -EINVAL;
13035 }
be8704ff
AS
13036 }
13037 if (!tgt_prog->jited) {
efc68158 13038 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
13039 return -EINVAL;
13040 }
13041 if (tgt_prog->type == prog->type) {
13042 /* Cannot fentry/fexit another fentry/fexit program.
13043 * Cannot attach program extension to another extension.
13044 * It's ok to attach fentry/fexit to extension program.
13045 */
efc68158 13046 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
13047 return -EINVAL;
13048 }
13049 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13050 prog_extension &&
13051 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13052 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13053 /* Program extensions can extend all program types
13054 * except fentry/fexit. The reason is the following.
13055 * The fentry/fexit programs are used for performance
13056 * analysis, stats and can be attached to any program
13057 * type except themselves. When extension program is
13058 * replacing XDP function it is necessary to allow
13059 * performance analysis of all functions. Both original
13060 * XDP program and its program extension. Hence
13061 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13062 * allowed. If extending of fentry/fexit was allowed it
13063 * would be possible to create long call chain
13064 * fentry->extension->fentry->extension beyond
13065 * reasonable stack size. Hence extending fentry is not
13066 * allowed.
13067 */
efc68158 13068 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
13069 return -EINVAL;
13070 }
5b92a28a 13071 } else {
be8704ff 13072 if (prog_extension) {
efc68158 13073 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
13074 return -EINVAL;
13075 }
5b92a28a 13076 }
f1b9509c
AS
13077
13078 switch (prog->expected_attach_type) {
13079 case BPF_TRACE_RAW_TP:
5b92a28a 13080 if (tgt_prog) {
efc68158 13081 bpf_log(log,
5b92a28a
AS
13082 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13083 return -EINVAL;
13084 }
38207291 13085 if (!btf_type_is_typedef(t)) {
efc68158 13086 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
13087 btf_id);
13088 return -EINVAL;
13089 }
f1b9509c 13090 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 13091 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
13092 btf_id, tname);
13093 return -EINVAL;
13094 }
13095 tname += sizeof(prefix) - 1;
5b92a28a 13096 t = btf_type_by_id(btf, t->type);
38207291
MKL
13097 if (!btf_type_is_ptr(t))
13098 /* should never happen in valid vmlinux build */
13099 return -EINVAL;
5b92a28a 13100 t = btf_type_by_id(btf, t->type);
38207291
MKL
13101 if (!btf_type_is_func_proto(t))
13102 /* should never happen in valid vmlinux build */
13103 return -EINVAL;
13104
f7b12b6f 13105 break;
15d83c4d
YS
13106 case BPF_TRACE_ITER:
13107 if (!btf_type_is_func(t)) {
efc68158 13108 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
13109 btf_id);
13110 return -EINVAL;
13111 }
13112 t = btf_type_by_id(btf, t->type);
13113 if (!btf_type_is_func_proto(t))
13114 return -EINVAL;
f7b12b6f
THJ
13115 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13116 if (ret)
13117 return ret;
13118 break;
be8704ff
AS
13119 default:
13120 if (!prog_extension)
13121 return -EINVAL;
df561f66 13122 fallthrough;
ae240823 13123 case BPF_MODIFY_RETURN:
9e4e01df 13124 case BPF_LSM_MAC:
fec56f58
AS
13125 case BPF_TRACE_FENTRY:
13126 case BPF_TRACE_FEXIT:
13127 if (!btf_type_is_func(t)) {
efc68158 13128 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
13129 btf_id);
13130 return -EINVAL;
13131 }
be8704ff 13132 if (prog_extension &&
efc68158 13133 btf_check_type_match(log, prog, btf, t))
be8704ff 13134 return -EINVAL;
5b92a28a 13135 t = btf_type_by_id(btf, t->type);
fec56f58
AS
13136 if (!btf_type_is_func_proto(t))
13137 return -EINVAL;
f7b12b6f 13138
4a1e7c0c
THJ
13139 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13140 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13141 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13142 return -EINVAL;
13143
f7b12b6f 13144 if (tgt_prog && conservative)
5b92a28a 13145 t = NULL;
f7b12b6f
THJ
13146
13147 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 13148 if (ret < 0)
f7b12b6f
THJ
13149 return ret;
13150
5b92a28a 13151 if (tgt_prog) {
e9eeec58
YS
13152 if (subprog == 0)
13153 addr = (long) tgt_prog->bpf_func;
13154 else
13155 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
13156 } else {
13157 addr = kallsyms_lookup_name(tname);
13158 if (!addr) {
efc68158 13159 bpf_log(log,
5b92a28a
AS
13160 "The address of function %s cannot be found\n",
13161 tname);
f7b12b6f 13162 return -ENOENT;
5b92a28a 13163 }
fec56f58 13164 }
18644cec 13165
1e6c62a8
AS
13166 if (prog->aux->sleepable) {
13167 ret = -EINVAL;
13168 switch (prog->type) {
13169 case BPF_PROG_TYPE_TRACING:
13170 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13171 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13172 */
13173 if (!check_non_sleepable_error_inject(btf_id) &&
13174 within_error_injection_list(addr))
13175 ret = 0;
13176 break;
13177 case BPF_PROG_TYPE_LSM:
13178 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13179 * Only some of them are sleepable.
13180 */
423f1610 13181 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
13182 ret = 0;
13183 break;
13184 default:
13185 break;
13186 }
f7b12b6f
THJ
13187 if (ret) {
13188 bpf_log(log, "%s is not sleepable\n", tname);
13189 return ret;
13190 }
1e6c62a8 13191 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 13192 if (tgt_prog) {
efc68158 13193 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
13194 return -EINVAL;
13195 }
13196 ret = check_attach_modify_return(addr, tname);
13197 if (ret) {
13198 bpf_log(log, "%s() is not modifiable\n", tname);
13199 return ret;
1af9270e 13200 }
18644cec 13201 }
f7b12b6f
THJ
13202
13203 break;
13204 }
13205 tgt_info->tgt_addr = addr;
13206 tgt_info->tgt_name = tname;
13207 tgt_info->tgt_type = t;
13208 return 0;
13209}
13210
35e3815f
JO
13211BTF_SET_START(btf_id_deny)
13212BTF_ID_UNUSED
13213#ifdef CONFIG_SMP
13214BTF_ID(func, migrate_disable)
13215BTF_ID(func, migrate_enable)
13216#endif
13217#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13218BTF_ID(func, rcu_read_unlock_strict)
13219#endif
13220BTF_SET_END(btf_id_deny)
13221
f7b12b6f
THJ
13222static int check_attach_btf_id(struct bpf_verifier_env *env)
13223{
13224 struct bpf_prog *prog = env->prog;
3aac1ead 13225 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
13226 struct bpf_attach_target_info tgt_info = {};
13227 u32 btf_id = prog->aux->attach_btf_id;
13228 struct bpf_trampoline *tr;
13229 int ret;
13230 u64 key;
13231
13232 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13233 prog->type != BPF_PROG_TYPE_LSM) {
13234 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13235 return -EINVAL;
13236 }
13237
13238 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13239 return check_struct_ops_btf_id(env);
13240
13241 if (prog->type != BPF_PROG_TYPE_TRACING &&
13242 prog->type != BPF_PROG_TYPE_LSM &&
13243 prog->type != BPF_PROG_TYPE_EXT)
13244 return 0;
13245
13246 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13247 if (ret)
fec56f58 13248 return ret;
f7b12b6f
THJ
13249
13250 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
13251 /* to make freplace equivalent to their targets, they need to
13252 * inherit env->ops and expected_attach_type for the rest of the
13253 * verification
13254 */
f7b12b6f
THJ
13255 env->ops = bpf_verifier_ops[tgt_prog->type];
13256 prog->expected_attach_type = tgt_prog->expected_attach_type;
13257 }
13258
13259 /* store info about the attachment target that will be used later */
13260 prog->aux->attach_func_proto = tgt_info.tgt_type;
13261 prog->aux->attach_func_name = tgt_info.tgt_name;
13262
4a1e7c0c
THJ
13263 if (tgt_prog) {
13264 prog->aux->saved_dst_prog_type = tgt_prog->type;
13265 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13266 }
13267
f7b12b6f
THJ
13268 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13269 prog->aux->attach_btf_trace = true;
13270 return 0;
13271 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13272 if (!bpf_iter_prog_supported(prog))
13273 return -EINVAL;
13274 return 0;
13275 }
13276
13277 if (prog->type == BPF_PROG_TYPE_LSM) {
13278 ret = bpf_lsm_verify_prog(&env->log, prog);
13279 if (ret < 0)
13280 return ret;
35e3815f
JO
13281 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13282 btf_id_set_contains(&btf_id_deny, btf_id)) {
13283 return -EINVAL;
38207291 13284 }
f7b12b6f 13285
22dc4a0f 13286 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
13287 tr = bpf_trampoline_get(key, &tgt_info);
13288 if (!tr)
13289 return -ENOMEM;
13290
3aac1ead 13291 prog->aux->dst_trampoline = tr;
f7b12b6f 13292 return 0;
38207291
MKL
13293}
13294
76654e67
AM
13295struct btf *bpf_get_btf_vmlinux(void)
13296{
13297 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13298 mutex_lock(&bpf_verifier_lock);
13299 if (!btf_vmlinux)
13300 btf_vmlinux = btf_parse_vmlinux();
13301 mutex_unlock(&bpf_verifier_lock);
13302 }
13303 return btf_vmlinux;
13304}
13305
838e9690
YS
13306int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13307 union bpf_attr __user *uattr)
51580e79 13308{
06ee7115 13309 u64 start_time = ktime_get_ns();
58e2af8b 13310 struct bpf_verifier_env *env;
b9193c1b 13311 struct bpf_verifier_log *log;
9e4c24e7 13312 int i, len, ret = -EINVAL;
e2ae4ca2 13313 bool is_priv;
51580e79 13314
eba0c929
AB
13315 /* no program is valid */
13316 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13317 return -EINVAL;
13318
58e2af8b 13319 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
13320 * allocate/free it every time bpf_check() is called
13321 */
58e2af8b 13322 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
13323 if (!env)
13324 return -ENOMEM;
61bd5218 13325 log = &env->log;
cbd35700 13326
9e4c24e7 13327 len = (*prog)->len;
fad953ce 13328 env->insn_aux_data =
9e4c24e7 13329 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
13330 ret = -ENOMEM;
13331 if (!env->insn_aux_data)
13332 goto err_free_env;
9e4c24e7
JK
13333 for (i = 0; i < len; i++)
13334 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 13335 env->prog = *prog;
00176a34 13336 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 13337 is_priv = bpf_capable();
0246e64d 13338
76654e67 13339 bpf_get_btf_vmlinux();
8580ac94 13340
cbd35700 13341 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
13342 if (!is_priv)
13343 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
13344
13345 if (attr->log_level || attr->log_buf || attr->log_size) {
13346 /* user requested verbose verifier output
13347 * and supplied buffer to store the verification trace
13348 */
e7bf8249
JK
13349 log->level = attr->log_level;
13350 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13351 log->len_total = attr->log_size;
cbd35700
AS
13352
13353 ret = -EINVAL;
e7bf8249 13354 /* log attributes have to be sane */
7a9f5c65 13355 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 13356 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 13357 goto err_unlock;
cbd35700 13358 }
1ad2f583 13359
8580ac94
AS
13360 if (IS_ERR(btf_vmlinux)) {
13361 /* Either gcc or pahole or kernel are broken. */
13362 verbose(env, "in-kernel BTF is malformed\n");
13363 ret = PTR_ERR(btf_vmlinux);
38207291 13364 goto skip_full_check;
8580ac94
AS
13365 }
13366
1ad2f583
DB
13367 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13368 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 13369 env->strict_alignment = true;
e9ee9efc
DM
13370 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13371 env->strict_alignment = false;
cbd35700 13372
2c78ee89 13373 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 13374 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 13375 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
13376 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13377 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13378 env->bpf_capable = bpf_capable();
e2ae4ca2 13379
10d274e8
AS
13380 if (is_priv)
13381 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13382
dc2a4ebc 13383 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 13384 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
13385 GFP_USER);
13386 ret = -ENOMEM;
13387 if (!env->explored_states)
13388 goto skip_full_check;
13389
e6ac2450
MKL
13390 ret = add_subprog_and_kfunc(env);
13391 if (ret < 0)
13392 goto skip_full_check;
13393
d9762e84 13394 ret = check_subprogs(env);
475fb78f
AS
13395 if (ret < 0)
13396 goto skip_full_check;
13397
c454a46b 13398 ret = check_btf_info(env, attr, uattr);
838e9690
YS
13399 if (ret < 0)
13400 goto skip_full_check;
13401
be8704ff
AS
13402 ret = check_attach_btf_id(env);
13403 if (ret)
13404 goto skip_full_check;
13405
4976b718
HL
13406 ret = resolve_pseudo_ldimm64(env);
13407 if (ret < 0)
13408 goto skip_full_check;
13409
ceb11679
YZ
13410 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13411 ret = bpf_prog_offload_verifier_prep(env->prog);
13412 if (ret)
13413 goto skip_full_check;
13414 }
13415
d9762e84
MKL
13416 ret = check_cfg(env);
13417 if (ret < 0)
13418 goto skip_full_check;
13419
51c39bb1
AS
13420 ret = do_check_subprogs(env);
13421 ret = ret ?: do_check_main(env);
cbd35700 13422
c941ce9c
QM
13423 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13424 ret = bpf_prog_offload_finalize(env);
13425
0246e64d 13426skip_full_check:
51c39bb1 13427 kvfree(env->explored_states);
0246e64d 13428
c131187d 13429 if (ret == 0)
9b38c405 13430 ret = check_max_stack_depth(env);
c131187d 13431
9b38c405 13432 /* instruction rewrites happen after this point */
e2ae4ca2
JK
13433 if (is_priv) {
13434 if (ret == 0)
13435 opt_hard_wire_dead_code_branches(env);
52875a04
JK
13436 if (ret == 0)
13437 ret = opt_remove_dead_code(env);
a1b14abc
JK
13438 if (ret == 0)
13439 ret = opt_remove_nops(env);
52875a04
JK
13440 } else {
13441 if (ret == 0)
13442 sanitize_dead_code(env);
e2ae4ca2
JK
13443 }
13444
9bac3d6d
AS
13445 if (ret == 0)
13446 /* program is valid, convert *(u32*)(ctx + off) accesses */
13447 ret = convert_ctx_accesses(env);
13448
e245c5c6 13449 if (ret == 0)
e6ac5933 13450 ret = do_misc_fixups(env);
e245c5c6 13451
a4b1d3c1
JW
13452 /* do 32-bit optimization after insn patching has done so those patched
13453 * insns could be handled correctly.
13454 */
d6c2308c
JW
13455 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13456 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13457 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13458 : false;
a4b1d3c1
JW
13459 }
13460
1ea47e01
AS
13461 if (ret == 0)
13462 ret = fixup_call_args(env);
13463
06ee7115
AS
13464 env->verification_time = ktime_get_ns() - start_time;
13465 print_verification_stats(env);
13466
a2a7d570 13467 if (log->level && bpf_verifier_log_full(log))
cbd35700 13468 ret = -ENOSPC;
a2a7d570 13469 if (log->level && !log->ubuf) {
cbd35700 13470 ret = -EFAULT;
a2a7d570 13471 goto err_release_maps;
cbd35700
AS
13472 }
13473
541c3bad
AN
13474 if (ret)
13475 goto err_release_maps;
13476
13477 if (env->used_map_cnt) {
0246e64d 13478 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
13479 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13480 sizeof(env->used_maps[0]),
13481 GFP_KERNEL);
0246e64d 13482
9bac3d6d 13483 if (!env->prog->aux->used_maps) {
0246e64d 13484 ret = -ENOMEM;
a2a7d570 13485 goto err_release_maps;
0246e64d
AS
13486 }
13487
9bac3d6d 13488 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 13489 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 13490 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
13491 }
13492 if (env->used_btf_cnt) {
13493 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13494 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13495 sizeof(env->used_btfs[0]),
13496 GFP_KERNEL);
13497 if (!env->prog->aux->used_btfs) {
13498 ret = -ENOMEM;
13499 goto err_release_maps;
13500 }
0246e64d 13501
541c3bad
AN
13502 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13503 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13504 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13505 }
13506 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
13507 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13508 * bpf_ld_imm64 instructions
13509 */
13510 convert_pseudo_ld_imm64(env);
13511 }
cbd35700 13512
541c3bad 13513 adjust_btf_func(env);
ba64e7d8 13514
a2a7d570 13515err_release_maps:
9bac3d6d 13516 if (!env->prog->aux->used_maps)
0246e64d 13517 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 13518 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
13519 */
13520 release_maps(env);
541c3bad
AN
13521 if (!env->prog->aux->used_btfs)
13522 release_btfs(env);
03f87c0b
THJ
13523
13524 /* extension progs temporarily inherit the attach_type of their targets
13525 for verification purposes, so set it back to zero before returning
13526 */
13527 if (env->prog->type == BPF_PROG_TYPE_EXT)
13528 env->prog->expected_attach_type = 0;
13529
9bac3d6d 13530 *prog = env->prog;
3df126f3 13531err_unlock:
45a73c17
AS
13532 if (!is_priv)
13533 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
13534 vfree(env->insn_aux_data);
13535err_free_env:
13536 kfree(env);
51580e79
AS
13537 return ret;
13538}