bpf: Refactor NULL-ness check in check_reg_type().
[linux-block.git] / kernel / bpf / verifier.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
51580e79 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 3 * Copyright (c) 2016 Facebook
fd978bf7 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79 5 */
838e9690 6#include <uapi/linux/btf.h>
aef2feda 7#include <linux/bpf-cgroup.h>
51580e79
AS
8#include <linux/kernel.h>
9#include <linux/types.h>
10#include <linux/slab.h>
11#include <linux/bpf.h>
838e9690 12#include <linux/btf.h>
58e2af8b 13#include <linux/bpf_verifier.h>
51580e79
AS
14#include <linux/filter.h>
15#include <net/netlink.h>
16#include <linux/file.h>
17#include <linux/vmalloc.h>
ebb676da 18#include <linux/stringify.h>
cc8b0b92
AS
19#include <linux/bsearch.h>
20#include <linux/sort.h>
c195651e 21#include <linux/perf_event.h>
d9762e84 22#include <linux/ctype.h>
6ba43b76 23#include <linux/error-injection.h>
9e4e01df 24#include <linux/bpf_lsm.h>
1e6c62a8 25#include <linux/btf_ids.h>
47e34cb7 26#include <linux/poison.h>
bd5314f8 27#include <linux/module.h>
51580e79 28
f4ac7e0b
JK
29#include "disasm.h"
30
00176a34 31static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 32#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
33 [_id] = & _name ## _verifier_ops,
34#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 35#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
36#include <linux/bpf_types.h>
37#undef BPF_PROG_TYPE
38#undef BPF_MAP_TYPE
f2e10bff 39#undef BPF_LINK_TYPE
00176a34
JK
40};
41
51580e79
AS
42/* bpf_check() is a static code analyzer that walks eBPF program
43 * instruction by instruction and updates register/stack state.
44 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
45 *
46 * The first pass is depth-first-search to check that the program is a DAG.
47 * It rejects the following programs:
48 * - larger than BPF_MAXINSNS insns
49 * - if loop is present (detected via back-edge)
50 * - unreachable insns exist (shouldn't be a forest. program = one function)
51 * - out of bounds or malformed jumps
52 * The second pass is all possible path descent from the 1st insn.
8fb33b60 53 * Since it's analyzing all paths through the program, the length of the
eba38a96 54 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
55 * insn is less then 4K, but there are too many branches that change stack/regs.
56 * Number of 'branches to be analyzed' is limited to 1k
57 *
58 * On entry to each instruction, each register has a type, and the instruction
59 * changes the types of the registers depending on instruction semantics.
60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
61 * copied to R1.
62 *
63 * All registers are 64-bit.
64 * R0 - return register
65 * R1-R5 argument passing registers
66 * R6-R9 callee saved registers
67 * R10 - frame pointer read-only
68 *
69 * At the start of BPF program the register R1 contains a pointer to bpf_context
70 * and has type PTR_TO_CTX.
71 *
72 * Verifier tracks arithmetic operations on pointers in case:
73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75 * 1st insn copies R10 (which has FRAME_PTR) type into R1
76 * and 2nd arithmetic instruction is pattern matched to recognize
77 * that it wants to construct a pointer to some element within stack.
78 * So after 2nd insn, the register R1 has type PTR_TO_STACK
79 * (and -20 constant is saved for further stack bounds checking).
80 * Meaning that this reg is a pointer to stack plus known immediate constant.
81 *
f1174f77 82 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 83 * means the register has some value, but it's not a valid pointer.
f1174f77 84 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
85 *
86 * When verifier sees load or store instructions the type of base register
c64b7983
JS
87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88 * four pointer types recognized by check_mem_access() function.
51580e79
AS
89 *
90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91 * and the range of [ptr, ptr + map's value_size) is accessible.
92 *
93 * registers used to pass values to function calls are checked against
94 * function argument constraints.
95 *
96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97 * It means that the register type passed to this function must be
98 * PTR_TO_STACK and it will be used inside the function as
99 * 'pointer to map element key'
100 *
101 * For example the argument constraints for bpf_map_lookup_elem():
102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103 * .arg1_type = ARG_CONST_MAP_PTR,
104 * .arg2_type = ARG_PTR_TO_MAP_KEY,
105 *
106 * ret_type says that this function returns 'pointer to map elem value or null'
107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108 * 2nd argument should be a pointer to stack, which will be used inside
109 * the helper function as a pointer to map element key.
110 *
111 * On the kernel side the helper function looks like:
112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
113 * {
114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115 * void *key = (void *) (unsigned long) r2;
116 * void *value;
117 *
118 * here kernel can access 'key' and 'map' pointers safely, knowing that
119 * [key, key + map->key_size) bytes are valid and were initialized on
120 * the stack of eBPF program.
121 * }
122 *
123 * Corresponding eBPF program may look like:
124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128 * here verifier looks at prototype of map_lookup_elem() and sees:
129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
131 *
132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134 * and were initialized prior to this call.
135 * If it's ok, then verifier allows this BPF_CALL insn and looks at
136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
8fb33b60 138 * returns either pointer to map value or NULL.
51580e79
AS
139 *
140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141 * insn, the register holding that pointer in the true branch changes state to
142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143 * branch. See check_cond_jmp_op().
144 *
145 * After the call R0 is set to return type of the function and registers R1-R5
146 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
147 *
148 * The following reference types represent a potential reference to a kernel
149 * resource which, after first being allocated, must be checked and freed by
150 * the BPF program:
151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
152 *
153 * When the verifier sees a helper call return a reference type, it allocates a
154 * pointer id for the reference and stores it in the current function state.
155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157 * passes through a NULL-check conditional. For the branch wherein the state is
158 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
159 *
160 * For each helper function that allocates a reference, such as
161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162 * bpf_sk_release(). When a reference type passes into the release function,
163 * the verifier also releases the reference. If any unchecked or unreleased
164 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
165 */
166
17a52670 167/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 168struct bpf_verifier_stack_elem {
17a52670
AS
169 /* verifer state is 'st'
170 * before processing instruction 'insn_idx'
171 * and after processing instruction 'prev_insn_idx'
172 */
58e2af8b 173 struct bpf_verifier_state st;
17a52670
AS
174 int insn_idx;
175 int prev_insn_idx;
58e2af8b 176 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
177 /* length of verifier log at the time this state was pushed on stack */
178 u32 log_pos;
cbd35700
AS
179};
180
b285fcb7 181#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 182#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 183
d2e4c1e6
DB
184#define BPF_MAP_KEY_POISON (1ULL << 63)
185#define BPF_MAP_KEY_SEEN (1ULL << 62)
186
c93552c4
DB
187#define BPF_MAP_PTR_UNPRIV 1UL
188#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
189 POISON_POINTER_DELTA))
190#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
191
bc34dee6
JK
192static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
193static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
6a3cd331 194static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
5d92ddc3 195static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
6a3cd331
DM
196static int ref_set_non_owning(struct bpf_verifier_env *env,
197 struct bpf_reg_state *reg);
bc34dee6 198
c93552c4
DB
199static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
200{
d2e4c1e6 201 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
202}
203
204static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
205{
d2e4c1e6 206 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
207}
208
209static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
210 const struct bpf_map *map, bool unpriv)
211{
212 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
213 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
214 aux->map_ptr_state = (unsigned long)map |
215 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
216}
217
218static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & BPF_MAP_KEY_POISON;
221}
222
223static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
224{
225 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
226}
227
228static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
229{
230 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
231}
232
233static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
234{
235 bool poisoned = bpf_map_key_poisoned(aux);
236
237 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
238 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 239}
fad73a1a 240
23a2d70c
YS
241static bool bpf_pseudo_call(const struct bpf_insn *insn)
242{
243 return insn->code == (BPF_JMP | BPF_CALL) &&
244 insn->src_reg == BPF_PSEUDO_CALL;
245}
246
e6ac2450
MKL
247static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
248{
249 return insn->code == (BPF_JMP | BPF_CALL) &&
250 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
251}
252
33ff9823
DB
253struct bpf_call_arg_meta {
254 struct bpf_map *map_ptr;
435faee1 255 bool raw_mode;
36bbef52 256 bool pkt_access;
8f14852e 257 u8 release_regno;
435faee1
DB
258 int regno;
259 int access_size;
457f4436 260 int mem_size;
10060503 261 u64 msize_max_value;
1b986589 262 int ref_obj_id;
f8064ab9 263 int dynptr_id;
3e8ce298 264 int map_uid;
d83525ca 265 int func_id;
22dc4a0f 266 struct btf *btf;
eaa6bcb7 267 u32 btf_id;
22dc4a0f 268 struct btf *ret_btf;
eaa6bcb7 269 u32 ret_btf_id;
69c087ba 270 u32 subprogno;
aa3496ac 271 struct btf_field *kptr_field;
33ff9823
DB
272};
273
d0e1ac22
AN
274struct bpf_kfunc_call_arg_meta {
275 /* In parameters */
276 struct btf *btf;
277 u32 func_id;
278 u32 kfunc_flags;
279 const struct btf_type *func_proto;
280 const char *func_name;
281 /* Out parameters */
282 u32 ref_obj_id;
283 u8 release_regno;
284 bool r0_rdonly;
285 u32 ret_btf_id;
286 u64 r0_size;
287 u32 subprogno;
288 struct {
289 u64 value;
290 bool found;
291 } arg_constant;
292 struct {
293 struct btf *btf;
294 u32 btf_id;
295 } arg_obj_drop;
296 struct {
297 struct btf_field *field;
298 } arg_list_head;
299 struct {
300 struct btf_field *field;
301 } arg_rbtree_root;
302 struct {
303 enum bpf_dynptr_type type;
304 u32 id;
305 } initialized_dynptr;
06accc87
AN
306 struct {
307 u8 spi;
308 u8 frameno;
309 } iter;
d0e1ac22
AN
310 u64 mem_size;
311};
312
8580ac94
AS
313struct btf *btf_vmlinux;
314
cbd35700
AS
315static DEFINE_MUTEX(bpf_verifier_lock);
316
d9762e84
MKL
317static const struct bpf_line_info *
318find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
319{
320 const struct bpf_line_info *linfo;
321 const struct bpf_prog *prog;
322 u32 i, nr_linfo;
323
324 prog = env->prog;
325 nr_linfo = prog->aux->nr_linfo;
326
327 if (!nr_linfo || insn_off >= prog->len)
328 return NULL;
329
330 linfo = prog->aux->linfo;
331 for (i = 1; i < nr_linfo; i++)
332 if (insn_off < linfo[i].insn_off)
333 break;
334
335 return &linfo[i - 1];
336}
337
77d2e05a
MKL
338void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
339 va_list args)
cbd35700 340{
a2a7d570 341 unsigned int n;
cbd35700 342
a2a7d570 343 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
344
345 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
346 "verifier log line truncated - local buffer too short\n");
347
8580ac94 348 if (log->level == BPF_LOG_KERNEL) {
436d404c
HT
349 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
350
351 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
8580ac94
AS
352 return;
353 }
436d404c
HT
354
355 n = min(log->len_total - log->len_used - 1, n);
356 log->kbuf[n] = '\0';
a2a7d570
JK
357 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
358 log->len_used += n;
359 else
360 log->ubuf = NULL;
cbd35700 361}
abe08840 362
6f8a57cc
AN
363static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
364{
365 char zero = 0;
366
367 if (!bpf_verifier_log_needed(log))
368 return;
369
370 log->len_used = new_pos;
371 if (put_user(zero, log->ubuf + new_pos))
372 log->ubuf = NULL;
373}
374
abe08840
JO
375/* log_level controls verbosity level of eBPF verifier.
376 * bpf_verifier_log_write() is used to dump the verification trace to the log,
377 * so the user can figure out what's wrong with the program
430e68d1 378 */
abe08840
JO
379__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
380 const char *fmt, ...)
381{
382 va_list args;
383
77d2e05a
MKL
384 if (!bpf_verifier_log_needed(&env->log))
385 return;
386
abe08840 387 va_start(args, fmt);
77d2e05a 388 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
389 va_end(args);
390}
391EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
392
393__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
394{
77d2e05a 395 struct bpf_verifier_env *env = private_data;
abe08840
JO
396 va_list args;
397
77d2e05a
MKL
398 if (!bpf_verifier_log_needed(&env->log))
399 return;
400
abe08840 401 va_start(args, fmt);
77d2e05a 402 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
403 va_end(args);
404}
cbd35700 405
9e15db66
AS
406__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
407 const char *fmt, ...)
408{
409 va_list args;
410
411 if (!bpf_verifier_log_needed(log))
412 return;
413
414 va_start(args, fmt);
415 bpf_verifier_vlog(log, fmt, args);
416 va_end(args);
417}
84c6ac41 418EXPORT_SYMBOL_GPL(bpf_log);
9e15db66 419
d9762e84
MKL
420static const char *ltrim(const char *s)
421{
422 while (isspace(*s))
423 s++;
424
425 return s;
426}
427
428__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
429 u32 insn_off,
430 const char *prefix_fmt, ...)
431{
432 const struct bpf_line_info *linfo;
433
434 if (!bpf_verifier_log_needed(&env->log))
435 return;
436
437 linfo = find_linfo(env, insn_off);
438 if (!linfo || linfo == env->prev_linfo)
439 return;
440
441 if (prefix_fmt) {
442 va_list args;
443
444 va_start(args, prefix_fmt);
445 bpf_verifier_vlog(&env->log, prefix_fmt, args);
446 va_end(args);
447 }
448
449 verbose(env, "%s\n",
450 ltrim(btf_name_by_offset(env->prog->aux->btf,
451 linfo->line_off)));
452
453 env->prev_linfo = linfo;
454}
455
bc2591d6
YS
456static void verbose_invalid_scalar(struct bpf_verifier_env *env,
457 struct bpf_reg_state *reg,
458 struct tnum *range, const char *ctx,
459 const char *reg_name)
460{
461 char tn_buf[48];
462
463 verbose(env, "At %s the register %s ", ctx, reg_name);
464 if (!tnum_is_unknown(reg->var_off)) {
465 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
466 verbose(env, "has value %s", tn_buf);
467 } else {
468 verbose(env, "has unknown scalar value");
469 }
470 tnum_strn(tn_buf, sizeof(tn_buf), *range);
471 verbose(env, " should have been in %s\n", tn_buf);
472}
473
de8f3a83
DB
474static bool type_is_pkt_pointer(enum bpf_reg_type type)
475{
0c9a7a7e 476 type = base_type(type);
de8f3a83
DB
477 return type == PTR_TO_PACKET ||
478 type == PTR_TO_PACKET_META;
479}
480
46f8bc92
MKL
481static bool type_is_sk_pointer(enum bpf_reg_type type)
482{
483 return type == PTR_TO_SOCKET ||
655a51e5 484 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
485 type == PTR_TO_TCP_SOCK ||
486 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
487}
488
1057d299
AS
489static bool type_may_be_null(u32 type)
490{
491 return type & PTR_MAYBE_NULL;
492}
493
cac616db
JF
494static bool reg_type_not_null(enum bpf_reg_type type)
495{
1057d299
AS
496 if (type_may_be_null(type))
497 return false;
498
499 type = base_type(type);
cac616db
JF
500 return type == PTR_TO_SOCKET ||
501 type == PTR_TO_TCP_SOCK ||
502 type == PTR_TO_MAP_VALUE ||
69c087ba 503 type == PTR_TO_MAP_KEY ||
d5271c5b
AN
504 type == PTR_TO_SOCK_COMMON ||
505 type == PTR_TO_MEM;
cac616db
JF
506}
507
d8939cb0
DM
508static bool type_is_ptr_alloc_obj(u32 type)
509{
510 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
511}
512
6a3cd331
DM
513static bool type_is_non_owning_ref(u32 type)
514{
515 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
516}
517
4e814da0
KKD
518static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
519{
520 struct btf_record *rec = NULL;
521 struct btf_struct_meta *meta;
522
523 if (reg->type == PTR_TO_MAP_VALUE) {
524 rec = reg->map_ptr->record;
d8939cb0 525 } else if (type_is_ptr_alloc_obj(reg->type)) {
4e814da0
KKD
526 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
527 if (meta)
528 rec = meta->record;
529 }
530 return rec;
531}
532
d83525ca
AS
533static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
534{
4e814da0 535 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
cba368c1
MKL
536}
537
20b2aff4
HL
538static bool type_is_rdonly_mem(u32 type)
539{
540 return type & MEM_RDONLY;
cba368c1
MKL
541}
542
64d85290
JS
543static bool is_acquire_function(enum bpf_func_id func_id,
544 const struct bpf_map *map)
545{
546 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
547
548 if (func_id == BPF_FUNC_sk_lookup_tcp ||
549 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436 550 func_id == BPF_FUNC_skc_lookup_tcp ||
c0a5a21c
KKD
551 func_id == BPF_FUNC_ringbuf_reserve ||
552 func_id == BPF_FUNC_kptr_xchg)
64d85290
JS
553 return true;
554
555 if (func_id == BPF_FUNC_map_lookup_elem &&
556 (map_type == BPF_MAP_TYPE_SOCKMAP ||
557 map_type == BPF_MAP_TYPE_SOCKHASH))
558 return true;
559
560 return false;
46f8bc92
MKL
561}
562
1b986589
MKL
563static bool is_ptr_cast_function(enum bpf_func_id func_id)
564{
565 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
566 func_id == BPF_FUNC_sk_fullsock ||
567 func_id == BPF_FUNC_skc_to_tcp_sock ||
568 func_id == BPF_FUNC_skc_to_tcp6_sock ||
569 func_id == BPF_FUNC_skc_to_udp6_sock ||
3bc253c2 570 func_id == BPF_FUNC_skc_to_mptcp_sock ||
1df8f55a
MKL
571 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
572 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
573}
574
88374342 575static bool is_dynptr_ref_function(enum bpf_func_id func_id)
b2d8ef19
DM
576{
577 return func_id == BPF_FUNC_dynptr_data;
578}
579
be2ef816
AN
580static bool is_callback_calling_function(enum bpf_func_id func_id)
581{
582 return func_id == BPF_FUNC_for_each_map_elem ||
583 func_id == BPF_FUNC_timer_set_callback ||
584 func_id == BPF_FUNC_find_vma ||
585 func_id == BPF_FUNC_loop ||
586 func_id == BPF_FUNC_user_ringbuf_drain;
587}
588
9bb00b28
YS
589static bool is_storage_get_function(enum bpf_func_id func_id)
590{
591 return func_id == BPF_FUNC_sk_storage_get ||
592 func_id == BPF_FUNC_inode_storage_get ||
593 func_id == BPF_FUNC_task_storage_get ||
594 func_id == BPF_FUNC_cgrp_storage_get;
595}
596
b2d8ef19
DM
597static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
598 const struct bpf_map *map)
599{
600 int ref_obj_uses = 0;
601
602 if (is_ptr_cast_function(func_id))
603 ref_obj_uses++;
604 if (is_acquire_function(func_id, map))
605 ref_obj_uses++;
88374342 606 if (is_dynptr_ref_function(func_id))
b2d8ef19
DM
607 ref_obj_uses++;
608
609 return ref_obj_uses > 1;
610}
611
39491867
BJ
612static bool is_cmpxchg_insn(const struct bpf_insn *insn)
613{
614 return BPF_CLASS(insn->code) == BPF_STX &&
615 BPF_MODE(insn->code) == BPF_ATOMIC &&
616 insn->imm == BPF_CMPXCHG;
617}
618
c25b2ae1
HL
619/* string representation of 'enum bpf_reg_type'
620 *
621 * Note that reg_type_str() can not appear more than once in a single verbose()
622 * statement.
623 */
624static const char *reg_type_str(struct bpf_verifier_env *env,
625 enum bpf_reg_type type)
626{
ef66c547 627 char postfix[16] = {0}, prefix[64] = {0};
c25b2ae1
HL
628 static const char * const str[] = {
629 [NOT_INIT] = "?",
7df5072c 630 [SCALAR_VALUE] = "scalar",
c25b2ae1
HL
631 [PTR_TO_CTX] = "ctx",
632 [CONST_PTR_TO_MAP] = "map_ptr",
633 [PTR_TO_MAP_VALUE] = "map_value",
634 [PTR_TO_STACK] = "fp",
635 [PTR_TO_PACKET] = "pkt",
636 [PTR_TO_PACKET_META] = "pkt_meta",
637 [PTR_TO_PACKET_END] = "pkt_end",
638 [PTR_TO_FLOW_KEYS] = "flow_keys",
639 [PTR_TO_SOCKET] = "sock",
640 [PTR_TO_SOCK_COMMON] = "sock_common",
641 [PTR_TO_TCP_SOCK] = "tcp_sock",
642 [PTR_TO_TP_BUFFER] = "tp_buffer",
643 [PTR_TO_XDP_SOCK] = "xdp_sock",
644 [PTR_TO_BTF_ID] = "ptr_",
c25b2ae1 645 [PTR_TO_MEM] = "mem",
20b2aff4 646 [PTR_TO_BUF] = "buf",
c25b2ae1
HL
647 [PTR_TO_FUNC] = "func",
648 [PTR_TO_MAP_KEY] = "map_key",
27060531 649 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
c25b2ae1
HL
650 };
651
652 if (type & PTR_MAYBE_NULL) {
5844101a 653 if (base_type(type) == PTR_TO_BTF_ID)
c25b2ae1
HL
654 strncpy(postfix, "or_null_", 16);
655 else
656 strncpy(postfix, "_or_null", 16);
657 }
658
9bb00b28 659 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
ef66c547
DV
660 type & MEM_RDONLY ? "rdonly_" : "",
661 type & MEM_RINGBUF ? "ringbuf_" : "",
662 type & MEM_USER ? "user_" : "",
663 type & MEM_PERCPU ? "percpu_" : "",
9bb00b28 664 type & MEM_RCU ? "rcu_" : "",
3f00c523
DV
665 type & PTR_UNTRUSTED ? "untrusted_" : "",
666 type & PTR_TRUSTED ? "trusted_" : ""
ef66c547 667 );
20b2aff4
HL
668
669 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
670 prefix, str[base_type(type)], postfix);
c25b2ae1
HL
671 return env->type_str_buf;
672}
17a52670 673
8efea21d
EC
674static char slot_type_char[] = {
675 [STACK_INVALID] = '?',
676 [STACK_SPILL] = 'r',
677 [STACK_MISC] = 'm',
678 [STACK_ZERO] = '0',
97e03f52 679 [STACK_DYNPTR] = 'd',
06accc87 680 [STACK_ITER] = 'i',
8efea21d
EC
681};
682
4e92024a
AS
683static void print_liveness(struct bpf_verifier_env *env,
684 enum bpf_reg_liveness live)
685{
9242b5f5 686 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
687 verbose(env, "_");
688 if (live & REG_LIVE_READ)
689 verbose(env, "r");
690 if (live & REG_LIVE_WRITTEN)
691 verbose(env, "w");
9242b5f5
AS
692 if (live & REG_LIVE_DONE)
693 verbose(env, "D");
4e92024a
AS
694}
695
79168a66 696static int __get_spi(s32 off)
97e03f52
JK
697{
698 return (-off - 1) / BPF_REG_SIZE;
699}
700
f5b625e5
KKD
701static struct bpf_func_state *func(struct bpf_verifier_env *env,
702 const struct bpf_reg_state *reg)
703{
704 struct bpf_verifier_state *cur = env->cur_state;
705
706 return cur->frame[reg->frameno];
707}
708
97e03f52
JK
709static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
710{
f5b625e5 711 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
97e03f52 712
f5b625e5
KKD
713 /* We need to check that slots between [spi - nr_slots + 1, spi] are
714 * within [0, allocated_stack).
715 *
716 * Please note that the spi grows downwards. For example, a dynptr
717 * takes the size of two stack slots; the first slot will be at
718 * spi and the second slot will be at spi - 1.
719 */
720 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
97e03f52
JK
721}
722
a461f5ad
AN
723static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
724 const char *obj_kind, int nr_slots)
f4d7e40a 725{
79168a66 726 int off, spi;
f4d7e40a 727
79168a66 728 if (!tnum_is_const(reg->var_off)) {
a461f5ad 729 verbose(env, "%s has to be at a constant offset\n", obj_kind);
79168a66
KKD
730 return -EINVAL;
731 }
732
733 off = reg->off + reg->var_off.value;
734 if (off % BPF_REG_SIZE) {
a461f5ad 735 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
79168a66
KKD
736 return -EINVAL;
737 }
738
739 spi = __get_spi(off);
a461f5ad
AN
740 if (spi + 1 < nr_slots) {
741 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
79168a66
KKD
742 return -EINVAL;
743 }
97e03f52 744
a461f5ad 745 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
f5b625e5
KKD
746 return -ERANGE;
747 return spi;
f4d7e40a
AS
748}
749
a461f5ad
AN
750static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
751{
752 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
753}
754
06accc87
AN
755static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
756{
757 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
758}
759
b32a5dae 760static const char *btf_type_name(const struct btf *btf, u32 id)
9e15db66 761{
22dc4a0f 762 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
763}
764
d54e0f6c
AN
765static const char *dynptr_type_str(enum bpf_dynptr_type type)
766{
767 switch (type) {
768 case BPF_DYNPTR_TYPE_LOCAL:
769 return "local";
770 case BPF_DYNPTR_TYPE_RINGBUF:
771 return "ringbuf";
772 case BPF_DYNPTR_TYPE_SKB:
773 return "skb";
774 case BPF_DYNPTR_TYPE_XDP:
775 return "xdp";
776 case BPF_DYNPTR_TYPE_INVALID:
777 return "<invalid>";
778 default:
779 WARN_ONCE(1, "unknown dynptr type %d\n", type);
780 return "<unknown>";
781 }
782}
783
06accc87
AN
784static const char *iter_type_str(const struct btf *btf, u32 btf_id)
785{
786 if (!btf || btf_id == 0)
787 return "<invalid>";
788
789 /* we already validated that type is valid and has conforming name */
b32a5dae 790 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
06accc87
AN
791}
792
793static const char *iter_state_str(enum bpf_iter_state state)
794{
795 switch (state) {
796 case BPF_ITER_STATE_ACTIVE:
797 return "active";
798 case BPF_ITER_STATE_DRAINED:
799 return "drained";
800 case BPF_ITER_STATE_INVALID:
801 return "<invalid>";
802 default:
803 WARN_ONCE(1, "unknown iter state %d\n", state);
804 return "<unknown>";
805 }
806}
807
0f55f9ed
CL
808static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
809{
810 env->scratched_regs |= 1U << regno;
811}
812
813static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
814{
343e5375 815 env->scratched_stack_slots |= 1ULL << spi;
0f55f9ed
CL
816}
817
818static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
819{
820 return (env->scratched_regs >> regno) & 1;
821}
822
823static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
824{
825 return (env->scratched_stack_slots >> regno) & 1;
826}
827
828static bool verifier_state_scratched(const struct bpf_verifier_env *env)
829{
830 return env->scratched_regs || env->scratched_stack_slots;
831}
832
833static void mark_verifier_state_clean(struct bpf_verifier_env *env)
834{
835 env->scratched_regs = 0U;
343e5375 836 env->scratched_stack_slots = 0ULL;
0f55f9ed
CL
837}
838
839/* Used for printing the entire verifier state. */
840static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
841{
842 env->scratched_regs = ~0U;
343e5375 843 env->scratched_stack_slots = ~0ULL;
0f55f9ed
CL
844}
845
97e03f52
JK
846static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
847{
848 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
849 case DYNPTR_TYPE_LOCAL:
850 return BPF_DYNPTR_TYPE_LOCAL;
bc34dee6
JK
851 case DYNPTR_TYPE_RINGBUF:
852 return BPF_DYNPTR_TYPE_RINGBUF;
b5964b96
JK
853 case DYNPTR_TYPE_SKB:
854 return BPF_DYNPTR_TYPE_SKB;
05421aec
JK
855 case DYNPTR_TYPE_XDP:
856 return BPF_DYNPTR_TYPE_XDP;
97e03f52
JK
857 default:
858 return BPF_DYNPTR_TYPE_INVALID;
859 }
860}
861
66e3a13e
JK
862static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
863{
864 switch (type) {
865 case BPF_DYNPTR_TYPE_LOCAL:
866 return DYNPTR_TYPE_LOCAL;
867 case BPF_DYNPTR_TYPE_RINGBUF:
868 return DYNPTR_TYPE_RINGBUF;
869 case BPF_DYNPTR_TYPE_SKB:
870 return DYNPTR_TYPE_SKB;
871 case BPF_DYNPTR_TYPE_XDP:
872 return DYNPTR_TYPE_XDP;
873 default:
874 return 0;
875 }
876}
877
bc34dee6
JK
878static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
879{
880 return type == BPF_DYNPTR_TYPE_RINGBUF;
881}
882
27060531
KKD
883static void __mark_dynptr_reg(struct bpf_reg_state *reg,
884 enum bpf_dynptr_type type,
f8064ab9 885 bool first_slot, int dynptr_id);
27060531
KKD
886
887static void __mark_reg_not_init(const struct bpf_verifier_env *env,
888 struct bpf_reg_state *reg);
889
f8064ab9
KKD
890static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
891 struct bpf_reg_state *sreg1,
27060531
KKD
892 struct bpf_reg_state *sreg2,
893 enum bpf_dynptr_type type)
894{
f8064ab9
KKD
895 int id = ++env->id_gen;
896
897 __mark_dynptr_reg(sreg1, type, true, id);
898 __mark_dynptr_reg(sreg2, type, false, id);
27060531
KKD
899}
900
f8064ab9
KKD
901static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
902 struct bpf_reg_state *reg,
27060531
KKD
903 enum bpf_dynptr_type type)
904{
f8064ab9 905 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
27060531
KKD
906}
907
ef8fc7a0
KKD
908static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
909 struct bpf_func_state *state, int spi);
27060531 910
97e03f52
JK
911static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
912 enum bpf_arg_type arg_type, int insn_idx)
913{
914 struct bpf_func_state *state = func(env, reg);
915 enum bpf_dynptr_type type;
379d4ba8 916 int spi, i, id, err;
97e03f52 917
79168a66
KKD
918 spi = dynptr_get_spi(env, reg);
919 if (spi < 0)
920 return spi;
97e03f52 921
379d4ba8
KKD
922 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
923 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
924 * to ensure that for the following example:
925 * [d1][d1][d2][d2]
926 * spi 3 2 1 0
927 * So marking spi = 2 should lead to destruction of both d1 and d2. In
928 * case they do belong to same dynptr, second call won't see slot_type
929 * as STACK_DYNPTR and will simply skip destruction.
930 */
931 err = destroy_if_dynptr_stack_slot(env, state, spi);
932 if (err)
933 return err;
934 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
935 if (err)
936 return err;
97e03f52
JK
937
938 for (i = 0; i < BPF_REG_SIZE; i++) {
939 state->stack[spi].slot_type[i] = STACK_DYNPTR;
940 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
941 }
942
943 type = arg_to_dynptr_type(arg_type);
944 if (type == BPF_DYNPTR_TYPE_INVALID)
945 return -EINVAL;
946
f8064ab9 947 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
27060531 948 &state->stack[spi - 1].spilled_ptr, type);
97e03f52 949
bc34dee6
JK
950 if (dynptr_type_refcounted(type)) {
951 /* The id is used to track proper releasing */
952 id = acquire_reference_state(env, insn_idx);
953 if (id < 0)
954 return id;
955
27060531
KKD
956 state->stack[spi].spilled_ptr.ref_obj_id = id;
957 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
bc34dee6
JK
958 }
959
d6fefa11
KKD
960 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
961 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
962
97e03f52
JK
963 return 0;
964}
965
966static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
967{
968 struct bpf_func_state *state = func(env, reg);
969 int spi, i;
970
79168a66
KKD
971 spi = dynptr_get_spi(env, reg);
972 if (spi < 0)
973 return spi;
97e03f52
JK
974
975 for (i = 0; i < BPF_REG_SIZE; i++) {
976 state->stack[spi].slot_type[i] = STACK_INVALID;
977 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
978 }
979
bc34dee6 980 /* Invalidate any slices associated with this dynptr */
27060531
KKD
981 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
982 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
97e03f52 983
27060531
KKD
984 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
985 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
d6fefa11
KKD
986
987 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
988 *
989 * While we don't allow reading STACK_INVALID, it is still possible to
990 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
991 * helpers or insns can do partial read of that part without failing,
992 * but check_stack_range_initialized, check_stack_read_var_off, and
993 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
994 * the slot conservatively. Hence we need to prevent those liveness
995 * marking walks.
996 *
997 * This was not a problem before because STACK_INVALID is only set by
998 * default (where the default reg state has its reg->parent as NULL), or
999 * in clean_live_states after REG_LIVE_DONE (at which point
1000 * mark_reg_read won't walk reg->parent chain), but not randomly during
1001 * verifier state exploration (like we did above). Hence, for our case
1002 * parentage chain will still be live (i.e. reg->parent may be
1003 * non-NULL), while earlier reg->parent was NULL, so we need
1004 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
1005 * done later on reads or by mark_dynptr_read as well to unnecessary
1006 * mark registers in verifier state.
1007 */
1008 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1009 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1010
97e03f52
JK
1011 return 0;
1012}
1013
ef8fc7a0
KKD
1014static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1015 struct bpf_reg_state *reg);
1016
dbd8d228
KKD
1017static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1018{
1019 if (!env->allow_ptr_leaks)
1020 __mark_reg_not_init(env, reg);
1021 else
1022 __mark_reg_unknown(env, reg);
1023}
1024
ef8fc7a0
KKD
1025static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1026 struct bpf_func_state *state, int spi)
97e03f52 1027{
f8064ab9
KKD
1028 struct bpf_func_state *fstate;
1029 struct bpf_reg_state *dreg;
1030 int i, dynptr_id;
27060531 1031
ef8fc7a0
KKD
1032 /* We always ensure that STACK_DYNPTR is never set partially,
1033 * hence just checking for slot_type[0] is enough. This is
1034 * different for STACK_SPILL, where it may be only set for
1035 * 1 byte, so code has to use is_spilled_reg.
1036 */
1037 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1038 return 0;
97e03f52 1039
ef8fc7a0
KKD
1040 /* Reposition spi to first slot */
1041 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1042 spi = spi + 1;
1043
1044 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1045 verbose(env, "cannot overwrite referenced dynptr\n");
1046 return -EINVAL;
1047 }
1048
1049 mark_stack_slot_scratched(env, spi);
1050 mark_stack_slot_scratched(env, spi - 1);
97e03f52 1051
ef8fc7a0 1052 /* Writing partially to one dynptr stack slot destroys both. */
97e03f52 1053 for (i = 0; i < BPF_REG_SIZE; i++) {
ef8fc7a0
KKD
1054 state->stack[spi].slot_type[i] = STACK_INVALID;
1055 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
97e03f52
JK
1056 }
1057
f8064ab9
KKD
1058 dynptr_id = state->stack[spi].spilled_ptr.id;
1059 /* Invalidate any slices associated with this dynptr */
1060 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1061 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1062 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1063 continue;
dbd8d228
KKD
1064 if (dreg->dynptr_id == dynptr_id)
1065 mark_reg_invalid(env, dreg);
f8064ab9 1066 }));
ef8fc7a0
KKD
1067
1068 /* Do not release reference state, we are destroying dynptr on stack,
1069 * not using some helper to release it. Just reset register.
1070 */
1071 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1072 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1073
1074 /* Same reason as unmark_stack_slots_dynptr above */
1075 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1076 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1077
1078 return 0;
1079}
1080
7e0dac28 1081static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
97e03f52 1082{
7e0dac28
JK
1083 int spi;
1084
27060531
KKD
1085 if (reg->type == CONST_PTR_TO_DYNPTR)
1086 return false;
97e03f52 1087
7e0dac28
JK
1088 spi = dynptr_get_spi(env, reg);
1089
1090 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1091 * error because this just means the stack state hasn't been updated yet.
1092 * We will do check_mem_access to check and update stack bounds later.
f5b625e5 1093 */
7e0dac28
JK
1094 if (spi < 0 && spi != -ERANGE)
1095 return false;
1096
1097 /* We don't need to check if the stack slots are marked by previous
1098 * dynptr initializations because we allow overwriting existing unreferenced
1099 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1100 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1101 * touching are completely destructed before we reinitialize them for a new
1102 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1103 * instead of delaying it until the end where the user will get "Unreleased
379d4ba8
KKD
1104 * reference" error.
1105 */
97e03f52
JK
1106 return true;
1107}
1108
7e0dac28 1109static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
97e03f52
JK
1110{
1111 struct bpf_func_state *state = func(env, reg);
7e0dac28 1112 int i, spi;
97e03f52 1113
7e0dac28
JK
1114 /* This already represents first slot of initialized bpf_dynptr.
1115 *
1116 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1117 * check_func_arg_reg_off's logic, so we don't need to check its
1118 * offset and alignment.
1119 */
27060531
KKD
1120 if (reg->type == CONST_PTR_TO_DYNPTR)
1121 return true;
1122
7e0dac28 1123 spi = dynptr_get_spi(env, reg);
79168a66
KKD
1124 if (spi < 0)
1125 return false;
f5b625e5 1126 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
97e03f52
JK
1127 return false;
1128
1129 for (i = 0; i < BPF_REG_SIZE; i++) {
1130 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1131 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1132 return false;
1133 }
1134
e9e315b4
RS
1135 return true;
1136}
1137
6b75bd3d
KKD
1138static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1139 enum bpf_arg_type arg_type)
e9e315b4
RS
1140{
1141 struct bpf_func_state *state = func(env, reg);
1142 enum bpf_dynptr_type dynptr_type;
27060531 1143 int spi;
e9e315b4 1144
97e03f52
JK
1145 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1146 if (arg_type == ARG_PTR_TO_DYNPTR)
1147 return true;
1148
e9e315b4 1149 dynptr_type = arg_to_dynptr_type(arg_type);
27060531
KKD
1150 if (reg->type == CONST_PTR_TO_DYNPTR) {
1151 return reg->dynptr.type == dynptr_type;
1152 } else {
79168a66
KKD
1153 spi = dynptr_get_spi(env, reg);
1154 if (spi < 0)
1155 return false;
27060531
KKD
1156 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1157 }
97e03f52
JK
1158}
1159
06accc87
AN
1160static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1161
1162static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1163 struct bpf_reg_state *reg, int insn_idx,
1164 struct btf *btf, u32 btf_id, int nr_slots)
1165{
1166 struct bpf_func_state *state = func(env, reg);
1167 int spi, i, j, id;
1168
1169 spi = iter_get_spi(env, reg, nr_slots);
1170 if (spi < 0)
1171 return spi;
1172
1173 id = acquire_reference_state(env, insn_idx);
1174 if (id < 0)
1175 return id;
1176
1177 for (i = 0; i < nr_slots; i++) {
1178 struct bpf_stack_state *slot = &state->stack[spi - i];
1179 struct bpf_reg_state *st = &slot->spilled_ptr;
1180
1181 __mark_reg_known_zero(st);
1182 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1183 st->live |= REG_LIVE_WRITTEN;
1184 st->ref_obj_id = i == 0 ? id : 0;
1185 st->iter.btf = btf;
1186 st->iter.btf_id = btf_id;
1187 st->iter.state = BPF_ITER_STATE_ACTIVE;
1188 st->iter.depth = 0;
1189
1190 for (j = 0; j < BPF_REG_SIZE; j++)
1191 slot->slot_type[j] = STACK_ITER;
1192
1193 mark_stack_slot_scratched(env, spi - i);
1194 }
1195
1196 return 0;
1197}
1198
1199static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1200 struct bpf_reg_state *reg, int nr_slots)
1201{
1202 struct bpf_func_state *state = func(env, reg);
1203 int spi, i, j;
1204
1205 spi = iter_get_spi(env, reg, nr_slots);
1206 if (spi < 0)
1207 return spi;
1208
1209 for (i = 0; i < nr_slots; i++) {
1210 struct bpf_stack_state *slot = &state->stack[spi - i];
1211 struct bpf_reg_state *st = &slot->spilled_ptr;
1212
1213 if (i == 0)
1214 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1215
1216 __mark_reg_not_init(env, st);
1217
1218 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1219 st->live |= REG_LIVE_WRITTEN;
1220
1221 for (j = 0; j < BPF_REG_SIZE; j++)
1222 slot->slot_type[j] = STACK_INVALID;
1223
1224 mark_stack_slot_scratched(env, spi - i);
1225 }
1226
1227 return 0;
1228}
1229
1230static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1231 struct bpf_reg_state *reg, int nr_slots)
1232{
1233 struct bpf_func_state *state = func(env, reg);
1234 int spi, i, j;
1235
1236 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1237 * will do check_mem_access to check and update stack bounds later, so
1238 * return true for that case.
1239 */
1240 spi = iter_get_spi(env, reg, nr_slots);
1241 if (spi == -ERANGE)
1242 return true;
1243 if (spi < 0)
1244 return false;
1245
1246 for (i = 0; i < nr_slots; i++) {
1247 struct bpf_stack_state *slot = &state->stack[spi - i];
1248
1249 for (j = 0; j < BPF_REG_SIZE; j++)
1250 if (slot->slot_type[j] == STACK_ITER)
1251 return false;
1252 }
1253
1254 return true;
1255}
1256
1257static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1258 struct btf *btf, u32 btf_id, int nr_slots)
1259{
1260 struct bpf_func_state *state = func(env, reg);
1261 int spi, i, j;
1262
1263 spi = iter_get_spi(env, reg, nr_slots);
1264 if (spi < 0)
1265 return false;
1266
1267 for (i = 0; i < nr_slots; i++) {
1268 struct bpf_stack_state *slot = &state->stack[spi - i];
1269 struct bpf_reg_state *st = &slot->spilled_ptr;
1270
1271 /* only main (first) slot has ref_obj_id set */
1272 if (i == 0 && !st->ref_obj_id)
1273 return false;
1274 if (i != 0 && st->ref_obj_id)
1275 return false;
1276 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1277 return false;
1278
1279 for (j = 0; j < BPF_REG_SIZE; j++)
1280 if (slot->slot_type[j] != STACK_ITER)
1281 return false;
1282 }
1283
1284 return true;
1285}
1286
1287/* Check if given stack slot is "special":
1288 * - spilled register state (STACK_SPILL);
1289 * - dynptr state (STACK_DYNPTR);
1290 * - iter state (STACK_ITER).
1291 */
1292static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1293{
1294 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1295
1296 switch (type) {
1297 case STACK_SPILL:
1298 case STACK_DYNPTR:
1299 case STACK_ITER:
1300 return true;
1301 case STACK_INVALID:
1302 case STACK_MISC:
1303 case STACK_ZERO:
1304 return false;
1305 default:
1306 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1307 return true;
1308 }
1309}
1310
27113c59
MKL
1311/* The reg state of a pointer or a bounded scalar was saved when
1312 * it was spilled to the stack.
1313 */
1314static bool is_spilled_reg(const struct bpf_stack_state *stack)
1315{
1316 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1317}
1318
354e8f19
MKL
1319static void scrub_spilled_slot(u8 *stype)
1320{
1321 if (*stype != STACK_INVALID)
1322 *stype = STACK_MISC;
1323}
1324
61bd5218 1325static void print_verifier_state(struct bpf_verifier_env *env,
0f55f9ed
CL
1326 const struct bpf_func_state *state,
1327 bool print_all)
17a52670 1328{
f4d7e40a 1329 const struct bpf_reg_state *reg;
17a52670
AS
1330 enum bpf_reg_type t;
1331 int i;
1332
f4d7e40a
AS
1333 if (state->frameno)
1334 verbose(env, " frame%d:", state->frameno);
17a52670 1335 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
1336 reg = &state->regs[i];
1337 t = reg->type;
17a52670
AS
1338 if (t == NOT_INIT)
1339 continue;
0f55f9ed
CL
1340 if (!print_all && !reg_scratched(env, i))
1341 continue;
4e92024a
AS
1342 verbose(env, " R%d", i);
1343 print_liveness(env, reg->live);
7df5072c 1344 verbose(env, "=");
b5dc0163
AS
1345 if (t == SCALAR_VALUE && reg->precise)
1346 verbose(env, "P");
f1174f77
EC
1347 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1348 tnum_is_const(reg->var_off)) {
1349 /* reg->off should be 0 for SCALAR_VALUE */
7df5072c 1350 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
61bd5218 1351 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 1352 } else {
7df5072c
ML
1353 const char *sep = "";
1354
1355 verbose(env, "%s", reg_type_str(env, t));
5844101a 1356 if (base_type(t) == PTR_TO_BTF_ID)
b32a5dae 1357 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
7df5072c
ML
1358 verbose(env, "(");
1359/*
1360 * _a stands for append, was shortened to avoid multiline statements below.
1361 * This macro is used to output a comma separated list of attributes.
1362 */
1363#define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1364
1365 if (reg->id)
1366 verbose_a("id=%d", reg->id);
a28ace78 1367 if (reg->ref_obj_id)
7df5072c 1368 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
6a3cd331
DM
1369 if (type_is_non_owning_ref(reg->type))
1370 verbose_a("%s", "non_own_ref");
f1174f77 1371 if (t != SCALAR_VALUE)
7df5072c 1372 verbose_a("off=%d", reg->off);
de8f3a83 1373 if (type_is_pkt_pointer(t))
7df5072c 1374 verbose_a("r=%d", reg->range);
c25b2ae1
HL
1375 else if (base_type(t) == CONST_PTR_TO_MAP ||
1376 base_type(t) == PTR_TO_MAP_KEY ||
1377 base_type(t) == PTR_TO_MAP_VALUE)
7df5072c
ML
1378 verbose_a("ks=%d,vs=%d",
1379 reg->map_ptr->key_size,
1380 reg->map_ptr->value_size);
7d1238f2
EC
1381 if (tnum_is_const(reg->var_off)) {
1382 /* Typically an immediate SCALAR_VALUE, but
1383 * could be a pointer whose offset is too big
1384 * for reg->off
1385 */
7df5072c 1386 verbose_a("imm=%llx", reg->var_off.value);
7d1238f2
EC
1387 } else {
1388 if (reg->smin_value != reg->umin_value &&
1389 reg->smin_value != S64_MIN)
7df5072c 1390 verbose_a("smin=%lld", (long long)reg->smin_value);
7d1238f2
EC
1391 if (reg->smax_value != reg->umax_value &&
1392 reg->smax_value != S64_MAX)
7df5072c 1393 verbose_a("smax=%lld", (long long)reg->smax_value);
7d1238f2 1394 if (reg->umin_value != 0)
7df5072c 1395 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
7d1238f2 1396 if (reg->umax_value != U64_MAX)
7df5072c 1397 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
7d1238f2
EC
1398 if (!tnum_is_unknown(reg->var_off)) {
1399 char tn_buf[48];
f1174f77 1400
7d1238f2 1401 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7df5072c 1402 verbose_a("var_off=%s", tn_buf);
7d1238f2 1403 }
3f50f132
JF
1404 if (reg->s32_min_value != reg->smin_value &&
1405 reg->s32_min_value != S32_MIN)
7df5072c 1406 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
3f50f132
JF
1407 if (reg->s32_max_value != reg->smax_value &&
1408 reg->s32_max_value != S32_MAX)
7df5072c 1409 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
3f50f132
JF
1410 if (reg->u32_min_value != reg->umin_value &&
1411 reg->u32_min_value != U32_MIN)
7df5072c 1412 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
3f50f132
JF
1413 if (reg->u32_max_value != reg->umax_value &&
1414 reg->u32_max_value != U32_MAX)
7df5072c 1415 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
f1174f77 1416 }
7df5072c
ML
1417#undef verbose_a
1418
61bd5218 1419 verbose(env, ")");
f1174f77 1420 }
17a52670 1421 }
638f5b90 1422 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
1423 char types_buf[BPF_REG_SIZE + 1];
1424 bool valid = false;
1425 int j;
1426
1427 for (j = 0; j < BPF_REG_SIZE; j++) {
1428 if (state->stack[i].slot_type[j] != STACK_INVALID)
1429 valid = true;
d54e0f6c 1430 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
8efea21d
EC
1431 }
1432 types_buf[BPF_REG_SIZE] = 0;
1433 if (!valid)
1434 continue;
0f55f9ed
CL
1435 if (!print_all && !stack_slot_scratched(env, i))
1436 continue;
d54e0f6c
AN
1437 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1438 case STACK_SPILL:
b5dc0163
AS
1439 reg = &state->stack[i].spilled_ptr;
1440 t = reg->type;
d54e0f6c
AN
1441
1442 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1443 print_liveness(env, reg->live);
7df5072c 1444 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
b5dc0163
AS
1445 if (t == SCALAR_VALUE && reg->precise)
1446 verbose(env, "P");
1447 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1448 verbose(env, "%lld", reg->var_off.value + reg->off);
d54e0f6c
AN
1449 break;
1450 case STACK_DYNPTR:
1451 i += BPF_DYNPTR_NR_SLOTS - 1;
1452 reg = &state->stack[i].spilled_ptr;
1453
1454 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1455 print_liveness(env, reg->live);
1456 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1457 if (reg->ref_obj_id)
1458 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1459 break;
06accc87
AN
1460 case STACK_ITER:
1461 /* only main slot has ref_obj_id set; skip others */
1462 reg = &state->stack[i].spilled_ptr;
1463 if (!reg->ref_obj_id)
1464 continue;
1465
1466 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1467 print_liveness(env, reg->live);
1468 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1469 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1470 reg->ref_obj_id, iter_state_str(reg->iter.state),
1471 reg->iter.depth);
1472 break;
d54e0f6c
AN
1473 case STACK_MISC:
1474 case STACK_ZERO:
1475 default:
1476 reg = &state->stack[i].spilled_ptr;
1477
1478 for (j = 0; j < BPF_REG_SIZE; j++)
1479 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1480 types_buf[BPF_REG_SIZE] = 0;
1481
1482 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1483 print_liveness(env, reg->live);
8efea21d 1484 verbose(env, "=%s", types_buf);
d54e0f6c 1485 break;
b5dc0163 1486 }
17a52670 1487 }
fd978bf7
JS
1488 if (state->acquired_refs && state->refs[0].id) {
1489 verbose(env, " refs=%d", state->refs[0].id);
1490 for (i = 1; i < state->acquired_refs; i++)
1491 if (state->refs[i].id)
1492 verbose(env, ",%d", state->refs[i].id);
1493 }
bfc6bb74
AS
1494 if (state->in_callback_fn)
1495 verbose(env, " cb");
1496 if (state->in_async_callback_fn)
1497 verbose(env, " async_cb");
61bd5218 1498 verbose(env, "\n");
0f55f9ed 1499 mark_verifier_state_clean(env);
17a52670
AS
1500}
1501
2e576648
CL
1502static inline u32 vlog_alignment(u32 pos)
1503{
1504 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1505 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1506}
1507
1508static void print_insn_state(struct bpf_verifier_env *env,
1509 const struct bpf_func_state *state)
1510{
1511 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
1512 /* remove new line character */
1513 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1514 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1515 } else {
1516 verbose(env, "%d:", env->insn_idx);
1517 }
1518 print_verifier_state(env, state, false);
17a52670
AS
1519}
1520
c69431aa
LB
1521/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1522 * small to hold src. This is different from krealloc since we don't want to preserve
1523 * the contents of dst.
1524 *
1525 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1526 * not be allocated.
638f5b90 1527 */
c69431aa 1528static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 1529{
45435d8d
KC
1530 size_t alloc_bytes;
1531 void *orig = dst;
c69431aa
LB
1532 size_t bytes;
1533
1534 if (ZERO_OR_NULL_PTR(src))
1535 goto out;
1536
1537 if (unlikely(check_mul_overflow(n, size, &bytes)))
1538 return NULL;
1539
45435d8d
KC
1540 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1541 dst = krealloc(orig, alloc_bytes, flags);
1542 if (!dst) {
1543 kfree(orig);
1544 return NULL;
c69431aa
LB
1545 }
1546
1547 memcpy(dst, src, bytes);
1548out:
1549 return dst ? dst : ZERO_SIZE_PTR;
1550}
1551
1552/* resize an array from old_n items to new_n items. the array is reallocated if it's too
1553 * small to hold new_n items. new items are zeroed out if the array grows.
1554 *
1555 * Contrary to krealloc_array, does not free arr if new_n is zero.
1556 */
1557static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1558{
ceb35b66 1559 size_t alloc_size;
42378a9c
KC
1560 void *new_arr;
1561
c69431aa
LB
1562 if (!new_n || old_n == new_n)
1563 goto out;
1564
ceb35b66
KC
1565 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1566 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
42378a9c
KC
1567 if (!new_arr) {
1568 kfree(arr);
c69431aa 1569 return NULL;
42378a9c
KC
1570 }
1571 arr = new_arr;
c69431aa
LB
1572
1573 if (new_n > old_n)
1574 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1575
1576out:
1577 return arr ? arr : ZERO_SIZE_PTR;
1578}
1579
1580static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1581{
1582 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1583 sizeof(struct bpf_reference_state), GFP_KERNEL);
1584 if (!dst->refs)
1585 return -ENOMEM;
1586
1587 dst->acquired_refs = src->acquired_refs;
1588 return 0;
1589}
1590
1591static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1592{
1593 size_t n = src->allocated_stack / BPF_REG_SIZE;
1594
1595 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1596 GFP_KERNEL);
1597 if (!dst->stack)
1598 return -ENOMEM;
1599
1600 dst->allocated_stack = src->allocated_stack;
1601 return 0;
1602}
1603
1604static int resize_reference_state(struct bpf_func_state *state, size_t n)
1605{
1606 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1607 sizeof(struct bpf_reference_state));
1608 if (!state->refs)
1609 return -ENOMEM;
1610
1611 state->acquired_refs = n;
1612 return 0;
1613}
1614
1615static int grow_stack_state(struct bpf_func_state *state, int size)
1616{
1617 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1618
1619 if (old_n >= n)
1620 return 0;
1621
1622 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1623 if (!state->stack)
1624 return -ENOMEM;
1625
1626 state->allocated_stack = size;
1627 return 0;
fd978bf7
JS
1628}
1629
1630/* Acquire a pointer id from the env and update the state->refs to include
1631 * this new pointer reference.
1632 * On success, returns a valid pointer id to associate with the register
1633 * On failure, returns a negative errno.
638f5b90 1634 */
fd978bf7 1635static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 1636{
fd978bf7
JS
1637 struct bpf_func_state *state = cur_func(env);
1638 int new_ofs = state->acquired_refs;
1639 int id, err;
1640
c69431aa 1641 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
1642 if (err)
1643 return err;
1644 id = ++env->id_gen;
1645 state->refs[new_ofs].id = id;
1646 state->refs[new_ofs].insn_idx = insn_idx;
9d9d00ac 1647 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
638f5b90 1648
fd978bf7
JS
1649 return id;
1650}
1651
1652/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 1653static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
1654{
1655 int i, last_idx;
1656
fd978bf7
JS
1657 last_idx = state->acquired_refs - 1;
1658 for (i = 0; i < state->acquired_refs; i++) {
1659 if (state->refs[i].id == ptr_id) {
9d9d00ac
KKD
1660 /* Cannot release caller references in callbacks */
1661 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1662 return -EINVAL;
fd978bf7
JS
1663 if (last_idx && i != last_idx)
1664 memcpy(&state->refs[i], &state->refs[last_idx],
1665 sizeof(*state->refs));
1666 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1667 state->acquired_refs--;
638f5b90 1668 return 0;
638f5b90 1669 }
638f5b90 1670 }
46f8bc92 1671 return -EINVAL;
fd978bf7
JS
1672}
1673
f4d7e40a
AS
1674static void free_func_state(struct bpf_func_state *state)
1675{
5896351e
AS
1676 if (!state)
1677 return;
fd978bf7 1678 kfree(state->refs);
f4d7e40a
AS
1679 kfree(state->stack);
1680 kfree(state);
1681}
1682
b5dc0163
AS
1683static void clear_jmp_history(struct bpf_verifier_state *state)
1684{
1685 kfree(state->jmp_history);
1686 state->jmp_history = NULL;
1687 state->jmp_history_cnt = 0;
1688}
1689
1969db47
AS
1690static void free_verifier_state(struct bpf_verifier_state *state,
1691 bool free_self)
638f5b90 1692{
f4d7e40a
AS
1693 int i;
1694
1695 for (i = 0; i <= state->curframe; i++) {
1696 free_func_state(state->frame[i]);
1697 state->frame[i] = NULL;
1698 }
b5dc0163 1699 clear_jmp_history(state);
1969db47
AS
1700 if (free_self)
1701 kfree(state);
638f5b90
AS
1702}
1703
1704/* copy verifier state from src to dst growing dst stack space
1705 * when necessary to accommodate larger src stack
1706 */
f4d7e40a
AS
1707static int copy_func_state(struct bpf_func_state *dst,
1708 const struct bpf_func_state *src)
638f5b90
AS
1709{
1710 int err;
1711
fd978bf7
JS
1712 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1713 err = copy_reference_state(dst, src);
638f5b90
AS
1714 if (err)
1715 return err;
638f5b90
AS
1716 return copy_stack_state(dst, src);
1717}
1718
f4d7e40a
AS
1719static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1720 const struct bpf_verifier_state *src)
1721{
1722 struct bpf_func_state *dst;
1723 int i, err;
1724
06ab6a50
LB
1725 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1726 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1727 GFP_USER);
1728 if (!dst_state->jmp_history)
1729 return -ENOMEM;
b5dc0163
AS
1730 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1731
f4d7e40a
AS
1732 /* if dst has more stack frames then src frame, free them */
1733 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1734 free_func_state(dst_state->frame[i]);
1735 dst_state->frame[i] = NULL;
1736 }
979d63d5 1737 dst_state->speculative = src->speculative;
9bb00b28 1738 dst_state->active_rcu_lock = src->active_rcu_lock;
f4d7e40a 1739 dst_state->curframe = src->curframe;
d0d78c1d
KKD
1740 dst_state->active_lock.ptr = src->active_lock.ptr;
1741 dst_state->active_lock.id = src->active_lock.id;
2589726d
AS
1742 dst_state->branches = src->branches;
1743 dst_state->parent = src->parent;
b5dc0163
AS
1744 dst_state->first_insn_idx = src->first_insn_idx;
1745 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
1746 for (i = 0; i <= src->curframe; i++) {
1747 dst = dst_state->frame[i];
1748 if (!dst) {
1749 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1750 if (!dst)
1751 return -ENOMEM;
1752 dst_state->frame[i] = dst;
1753 }
1754 err = copy_func_state(dst, src->frame[i]);
1755 if (err)
1756 return err;
1757 }
1758 return 0;
1759}
1760
2589726d
AS
1761static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1762{
1763 while (st) {
1764 u32 br = --st->branches;
1765
1766 /* WARN_ON(br > 1) technically makes sense here,
1767 * but see comment in push_stack(), hence:
1768 */
1769 WARN_ONCE((int)br < 0,
1770 "BUG update_branch_counts:branches_to_explore=%d\n",
1771 br);
1772 if (br)
1773 break;
1774 st = st->parent;
1775 }
1776}
1777
638f5b90 1778static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 1779 int *insn_idx, bool pop_log)
638f5b90
AS
1780{
1781 struct bpf_verifier_state *cur = env->cur_state;
1782 struct bpf_verifier_stack_elem *elem, *head = env->head;
1783 int err;
17a52670
AS
1784
1785 if (env->head == NULL)
638f5b90 1786 return -ENOENT;
17a52670 1787
638f5b90
AS
1788 if (cur) {
1789 err = copy_verifier_state(cur, &head->st);
1790 if (err)
1791 return err;
1792 }
6f8a57cc
AN
1793 if (pop_log)
1794 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
1795 if (insn_idx)
1796 *insn_idx = head->insn_idx;
17a52670 1797 if (prev_insn_idx)
638f5b90
AS
1798 *prev_insn_idx = head->prev_insn_idx;
1799 elem = head->next;
1969db47 1800 free_verifier_state(&head->st, false);
638f5b90 1801 kfree(head);
17a52670
AS
1802 env->head = elem;
1803 env->stack_size--;
638f5b90 1804 return 0;
17a52670
AS
1805}
1806
58e2af8b 1807static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1808 int insn_idx, int prev_insn_idx,
1809 bool speculative)
17a52670 1810{
638f5b90 1811 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1812 struct bpf_verifier_stack_elem *elem;
638f5b90 1813 int err;
17a52670 1814
638f5b90 1815 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1816 if (!elem)
1817 goto err;
1818
17a52670
AS
1819 elem->insn_idx = insn_idx;
1820 elem->prev_insn_idx = prev_insn_idx;
1821 elem->next = env->head;
6f8a57cc 1822 elem->log_pos = env->log.len_used;
17a52670
AS
1823 env->head = elem;
1824 env->stack_size++;
1969db47
AS
1825 err = copy_verifier_state(&elem->st, cur);
1826 if (err)
1827 goto err;
979d63d5 1828 elem->st.speculative |= speculative;
b285fcb7
AS
1829 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1830 verbose(env, "The sequence of %d jumps is too complex.\n",
1831 env->stack_size);
17a52670
AS
1832 goto err;
1833 }
2589726d
AS
1834 if (elem->st.parent) {
1835 ++elem->st.parent->branches;
1836 /* WARN_ON(branches > 2) technically makes sense here,
1837 * but
1838 * 1. speculative states will bump 'branches' for non-branch
1839 * instructions
1840 * 2. is_state_visited() heuristics may decide not to create
1841 * a new state for a sequence of branches and all such current
1842 * and cloned states will be pointing to a single parent state
1843 * which might have large 'branches' count.
1844 */
1845 }
17a52670
AS
1846 return &elem->st;
1847err:
5896351e
AS
1848 free_verifier_state(env->cur_state, true);
1849 env->cur_state = NULL;
17a52670 1850 /* pop all elements and return */
6f8a57cc 1851 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1852 return NULL;
1853}
1854
1855#define CALLER_SAVED_REGS 6
1856static const int caller_saved[CALLER_SAVED_REGS] = {
1857 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1858};
1859
e688c3db
AS
1860/* This helper doesn't clear reg->id */
1861static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1862{
b03c9f9f
EC
1863 reg->var_off = tnum_const(imm);
1864 reg->smin_value = (s64)imm;
1865 reg->smax_value = (s64)imm;
1866 reg->umin_value = imm;
1867 reg->umax_value = imm;
3f50f132
JF
1868
1869 reg->s32_min_value = (s32)imm;
1870 reg->s32_max_value = (s32)imm;
1871 reg->u32_min_value = (u32)imm;
1872 reg->u32_max_value = (u32)imm;
1873}
1874
e688c3db
AS
1875/* Mark the unknown part of a register (variable offset or scalar value) as
1876 * known to have the value @imm.
1877 */
1878static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1879{
a73bf9f2 1880 /* Clear off and union(map_ptr, range) */
e688c3db
AS
1881 memset(((u8 *)reg) + sizeof(reg->type), 0,
1882 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
a73bf9f2
AN
1883 reg->id = 0;
1884 reg->ref_obj_id = 0;
e688c3db
AS
1885 ___mark_reg_known(reg, imm);
1886}
1887
3f50f132
JF
1888static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1889{
1890 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1891 reg->s32_min_value = (s32)imm;
1892 reg->s32_max_value = (s32)imm;
1893 reg->u32_min_value = (u32)imm;
1894 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1895}
1896
f1174f77
EC
1897/* Mark the 'variable offset' part of a register as zero. This should be
1898 * used only on registers holding a pointer type.
1899 */
1900static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1901{
b03c9f9f 1902 __mark_reg_known(reg, 0);
f1174f77 1903}
a9789ef9 1904
cc2b14d5
AS
1905static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1906{
1907 __mark_reg_known(reg, 0);
cc2b14d5
AS
1908 reg->type = SCALAR_VALUE;
1909}
1910
61bd5218
JK
1911static void mark_reg_known_zero(struct bpf_verifier_env *env,
1912 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1913{
1914 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1915 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1916 /* Something bad happened, let's kill all regs */
1917 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1918 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1919 return;
1920 }
1921 __mark_reg_known_zero(regs + regno);
1922}
1923
27060531 1924static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
f8064ab9 1925 bool first_slot, int dynptr_id)
27060531
KKD
1926{
1927 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1928 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1929 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1930 */
1931 __mark_reg_known_zero(reg);
1932 reg->type = CONST_PTR_TO_DYNPTR;
f8064ab9
KKD
1933 /* Give each dynptr a unique id to uniquely associate slices to it. */
1934 reg->id = dynptr_id;
27060531
KKD
1935 reg->dynptr.type = type;
1936 reg->dynptr.first_slot = first_slot;
1937}
1938
4ddb7416
DB
1939static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1940{
c25b2ae1 1941 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
4ddb7416
DB
1942 const struct bpf_map *map = reg->map_ptr;
1943
1944 if (map->inner_map_meta) {
1945 reg->type = CONST_PTR_TO_MAP;
1946 reg->map_ptr = map->inner_map_meta;
3e8ce298
AS
1947 /* transfer reg's id which is unique for every map_lookup_elem
1948 * as UID of the inner map.
1949 */
db559117 1950 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
34d11a44 1951 reg->map_uid = reg->id;
4ddb7416
DB
1952 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1953 reg->type = PTR_TO_XDP_SOCK;
1954 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1955 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1956 reg->type = PTR_TO_SOCKET;
1957 } else {
1958 reg->type = PTR_TO_MAP_VALUE;
1959 }
c25b2ae1 1960 return;
4ddb7416 1961 }
c25b2ae1
HL
1962
1963 reg->type &= ~PTR_MAYBE_NULL;
4ddb7416
DB
1964}
1965
5d92ddc3
DM
1966static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1967 struct btf_field_graph_root *ds_head)
1968{
1969 __mark_reg_known_zero(&regs[regno]);
1970 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1971 regs[regno].btf = ds_head->btf;
1972 regs[regno].btf_id = ds_head->value_btf_id;
1973 regs[regno].off = ds_head->node_offset;
1974}
1975
de8f3a83
DB
1976static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1977{
1978 return type_is_pkt_pointer(reg->type);
1979}
1980
1981static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1982{
1983 return reg_is_pkt_pointer(reg) ||
1984 reg->type == PTR_TO_PACKET_END;
1985}
1986
66e3a13e
JK
1987static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1988{
1989 return base_type(reg->type) == PTR_TO_MEM &&
1990 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1991}
1992
de8f3a83
DB
1993/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1994static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1995 enum bpf_reg_type which)
1996{
1997 /* The register can already have a range from prior markings.
1998 * This is fine as long as it hasn't been advanced from its
1999 * origin.
2000 */
2001 return reg->type == which &&
2002 reg->id == 0 &&
2003 reg->off == 0 &&
2004 tnum_equals_const(reg->var_off, 0);
2005}
2006
3f50f132
JF
2007/* Reset the min/max bounds of a register */
2008static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2009{
2010 reg->smin_value = S64_MIN;
2011 reg->smax_value = S64_MAX;
2012 reg->umin_value = 0;
2013 reg->umax_value = U64_MAX;
2014
2015 reg->s32_min_value = S32_MIN;
2016 reg->s32_max_value = S32_MAX;
2017 reg->u32_min_value = 0;
2018 reg->u32_max_value = U32_MAX;
2019}
2020
2021static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2022{
2023 reg->smin_value = S64_MIN;
2024 reg->smax_value = S64_MAX;
2025 reg->umin_value = 0;
2026 reg->umax_value = U64_MAX;
2027}
2028
2029static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2030{
2031 reg->s32_min_value = S32_MIN;
2032 reg->s32_max_value = S32_MAX;
2033 reg->u32_min_value = 0;
2034 reg->u32_max_value = U32_MAX;
2035}
2036
2037static void __update_reg32_bounds(struct bpf_reg_state *reg)
2038{
2039 struct tnum var32_off = tnum_subreg(reg->var_off);
2040
2041 /* min signed is max(sign bit) | min(other bits) */
2042 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2043 var32_off.value | (var32_off.mask & S32_MIN));
2044 /* max signed is min(sign bit) | max(other bits) */
2045 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2046 var32_off.value | (var32_off.mask & S32_MAX));
2047 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2048 reg->u32_max_value = min(reg->u32_max_value,
2049 (u32)(var32_off.value | var32_off.mask));
2050}
2051
2052static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
2053{
2054 /* min signed is max(sign bit) | min(other bits) */
2055 reg->smin_value = max_t(s64, reg->smin_value,
2056 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2057 /* max signed is min(sign bit) | max(other bits) */
2058 reg->smax_value = min_t(s64, reg->smax_value,
2059 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2060 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2061 reg->umax_value = min(reg->umax_value,
2062 reg->var_off.value | reg->var_off.mask);
2063}
2064
3f50f132
JF
2065static void __update_reg_bounds(struct bpf_reg_state *reg)
2066{
2067 __update_reg32_bounds(reg);
2068 __update_reg64_bounds(reg);
2069}
2070
b03c9f9f 2071/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
2072static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2073{
2074 /* Learn sign from signed bounds.
2075 * If we cannot cross the sign boundary, then signed and unsigned bounds
2076 * are the same, so combine. This works even in the negative case, e.g.
2077 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2078 */
2079 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2080 reg->s32_min_value = reg->u32_min_value =
2081 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2082 reg->s32_max_value = reg->u32_max_value =
2083 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2084 return;
2085 }
2086 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2087 * boundary, so we must be careful.
2088 */
2089 if ((s32)reg->u32_max_value >= 0) {
2090 /* Positive. We can't learn anything from the smin, but smax
2091 * is positive, hence safe.
2092 */
2093 reg->s32_min_value = reg->u32_min_value;
2094 reg->s32_max_value = reg->u32_max_value =
2095 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2096 } else if ((s32)reg->u32_min_value < 0) {
2097 /* Negative. We can't learn anything from the smax, but smin
2098 * is negative, hence safe.
2099 */
2100 reg->s32_min_value = reg->u32_min_value =
2101 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2102 reg->s32_max_value = reg->u32_max_value;
2103 }
2104}
2105
2106static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
2107{
2108 /* Learn sign from signed bounds.
2109 * If we cannot cross the sign boundary, then signed and unsigned bounds
2110 * are the same, so combine. This works even in the negative case, e.g.
2111 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2112 */
2113 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2114 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2115 reg->umin_value);
2116 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2117 reg->umax_value);
2118 return;
2119 }
2120 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2121 * boundary, so we must be careful.
2122 */
2123 if ((s64)reg->umax_value >= 0) {
2124 /* Positive. We can't learn anything from the smin, but smax
2125 * is positive, hence safe.
2126 */
2127 reg->smin_value = reg->umin_value;
2128 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2129 reg->umax_value);
2130 } else if ((s64)reg->umin_value < 0) {
2131 /* Negative. We can't learn anything from the smax, but smin
2132 * is negative, hence safe.
2133 */
2134 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2135 reg->umin_value);
2136 reg->smax_value = reg->umax_value;
2137 }
2138}
2139
3f50f132
JF
2140static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2141{
2142 __reg32_deduce_bounds(reg);
2143 __reg64_deduce_bounds(reg);
2144}
2145
b03c9f9f
EC
2146/* Attempts to improve var_off based on unsigned min/max information */
2147static void __reg_bound_offset(struct bpf_reg_state *reg)
2148{
3f50f132
JF
2149 struct tnum var64_off = tnum_intersect(reg->var_off,
2150 tnum_range(reg->umin_value,
2151 reg->umax_value));
7be14c1c
DB
2152 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2153 tnum_range(reg->u32_min_value,
2154 reg->u32_max_value));
3f50f132
JF
2155
2156 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
2157}
2158
3844d153
DB
2159static void reg_bounds_sync(struct bpf_reg_state *reg)
2160{
2161 /* We might have learned new bounds from the var_off. */
2162 __update_reg_bounds(reg);
2163 /* We might have learned something about the sign bit. */
2164 __reg_deduce_bounds(reg);
2165 /* We might have learned some bits from the bounds. */
2166 __reg_bound_offset(reg);
2167 /* Intersecting with the old var_off might have improved our bounds
2168 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2169 * then new var_off is (0; 0x7f...fc) which improves our umax.
2170 */
2171 __update_reg_bounds(reg);
2172}
2173
e572ff80
DB
2174static bool __reg32_bound_s64(s32 a)
2175{
2176 return a >= 0 && a <= S32_MAX;
2177}
2178
3f50f132 2179static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 2180{
3f50f132
JF
2181 reg->umin_value = reg->u32_min_value;
2182 reg->umax_value = reg->u32_max_value;
e572ff80
DB
2183
2184 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2185 * be positive otherwise set to worse case bounds and refine later
2186 * from tnum.
3f50f132 2187 */
e572ff80
DB
2188 if (__reg32_bound_s64(reg->s32_min_value) &&
2189 __reg32_bound_s64(reg->s32_max_value)) {
3a71dc36 2190 reg->smin_value = reg->s32_min_value;
e572ff80
DB
2191 reg->smax_value = reg->s32_max_value;
2192 } else {
3a71dc36 2193 reg->smin_value = 0;
e572ff80
DB
2194 reg->smax_value = U32_MAX;
2195 }
3f50f132
JF
2196}
2197
2198static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2199{
2200 /* special case when 64-bit register has upper 32-bit register
2201 * zeroed. Typically happens after zext or <<32, >>32 sequence
2202 * allowing us to use 32-bit bounds directly,
2203 */
2204 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2205 __reg_assign_32_into_64(reg);
2206 } else {
2207 /* Otherwise the best we can do is push lower 32bit known and
2208 * unknown bits into register (var_off set from jmp logic)
2209 * then learn as much as possible from the 64-bit tnum
2210 * known and unknown bits. The previous smin/smax bounds are
2211 * invalid here because of jmp32 compare so mark them unknown
2212 * so they do not impact tnum bounds calculation.
2213 */
2214 __mark_reg64_unbounded(reg);
3f50f132 2215 }
3844d153 2216 reg_bounds_sync(reg);
3f50f132
JF
2217}
2218
2219static bool __reg64_bound_s32(s64 a)
2220{
388e2c0b 2221 return a >= S32_MIN && a <= S32_MAX;
3f50f132
JF
2222}
2223
2224static bool __reg64_bound_u32(u64 a)
2225{
b9979db8 2226 return a >= U32_MIN && a <= U32_MAX;
3f50f132
JF
2227}
2228
2229static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2230{
2231 __mark_reg32_unbounded(reg);
b0270958 2232 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 2233 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 2234 reg->s32_max_value = (s32)reg->smax_value;
b0270958 2235 }
10bf4e83 2236 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 2237 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 2238 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 2239 }
3844d153 2240 reg_bounds_sync(reg);
b03c9f9f
EC
2241}
2242
f1174f77 2243/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
2244static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2245 struct bpf_reg_state *reg)
f1174f77 2246{
a9c676bc 2247 /*
a73bf9f2 2248 * Clear type, off, and union(map_ptr, range) and
a9c676bc
AS
2249 * padding between 'type' and union
2250 */
2251 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 2252 reg->type = SCALAR_VALUE;
a73bf9f2
AN
2253 reg->id = 0;
2254 reg->ref_obj_id = 0;
f1174f77 2255 reg->var_off = tnum_unknown;
f4d7e40a 2256 reg->frameno = 0;
be2ef816 2257 reg->precise = !env->bpf_capable;
b03c9f9f 2258 __mark_reg_unbounded(reg);
f1174f77
EC
2259}
2260
61bd5218
JK
2261static void mark_reg_unknown(struct bpf_verifier_env *env,
2262 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2263{
2264 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2265 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
2266 /* Something bad happened, let's kill all regs except FP */
2267 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 2268 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2269 return;
2270 }
f54c7898 2271 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
2272}
2273
f54c7898
DB
2274static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2275 struct bpf_reg_state *reg)
f1174f77 2276{
f54c7898 2277 __mark_reg_unknown(env, reg);
f1174f77
EC
2278 reg->type = NOT_INIT;
2279}
2280
61bd5218
JK
2281static void mark_reg_not_init(struct bpf_verifier_env *env,
2282 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2283{
2284 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2285 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
2286 /* Something bad happened, let's kill all regs except FP */
2287 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 2288 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2289 return;
2290 }
f54c7898 2291 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
2292}
2293
41c48f3a
AI
2294static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2295 struct bpf_reg_state *regs, u32 regno,
22dc4a0f 2296 enum bpf_reg_type reg_type,
c6f1bfe8
YS
2297 struct btf *btf, u32 btf_id,
2298 enum bpf_type_flag flag)
41c48f3a
AI
2299{
2300 if (reg_type == SCALAR_VALUE) {
2301 mark_reg_unknown(env, regs, regno);
2302 return;
2303 }
2304 mark_reg_known_zero(env, regs, regno);
c6f1bfe8 2305 regs[regno].type = PTR_TO_BTF_ID | flag;
22dc4a0f 2306 regs[regno].btf = btf;
41c48f3a
AI
2307 regs[regno].btf_id = btf_id;
2308}
2309
5327ed3d 2310#define DEF_NOT_SUBREG (0)
61bd5218 2311static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 2312 struct bpf_func_state *state)
17a52670 2313{
f4d7e40a 2314 struct bpf_reg_state *regs = state->regs;
17a52670
AS
2315 int i;
2316
dc503a8a 2317 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 2318 mark_reg_not_init(env, regs, i);
dc503a8a 2319 regs[i].live = REG_LIVE_NONE;
679c782d 2320 regs[i].parent = NULL;
5327ed3d 2321 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 2322 }
17a52670
AS
2323
2324 /* frame pointer */
f1174f77 2325 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 2326 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 2327 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
2328}
2329
f4d7e40a
AS
2330#define BPF_MAIN_FUNC (-1)
2331static void init_func_state(struct bpf_verifier_env *env,
2332 struct bpf_func_state *state,
2333 int callsite, int frameno, int subprogno)
2334{
2335 state->callsite = callsite;
2336 state->frameno = frameno;
2337 state->subprogno = subprogno;
1bfe26fb 2338 state->callback_ret_range = tnum_range(0, 0);
f4d7e40a 2339 init_reg_state(env, state);
0f55f9ed 2340 mark_verifier_state_scratched(env);
f4d7e40a
AS
2341}
2342
bfc6bb74
AS
2343/* Similar to push_stack(), but for async callbacks */
2344static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2345 int insn_idx, int prev_insn_idx,
2346 int subprog)
2347{
2348 struct bpf_verifier_stack_elem *elem;
2349 struct bpf_func_state *frame;
2350
2351 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2352 if (!elem)
2353 goto err;
2354
2355 elem->insn_idx = insn_idx;
2356 elem->prev_insn_idx = prev_insn_idx;
2357 elem->next = env->head;
2358 elem->log_pos = env->log.len_used;
2359 env->head = elem;
2360 env->stack_size++;
2361 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2362 verbose(env,
2363 "The sequence of %d jumps is too complex for async cb.\n",
2364 env->stack_size);
2365 goto err;
2366 }
2367 /* Unlike push_stack() do not copy_verifier_state().
2368 * The caller state doesn't matter.
2369 * This is async callback. It starts in a fresh stack.
2370 * Initialize it similar to do_check_common().
2371 */
2372 elem->st.branches = 1;
2373 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2374 if (!frame)
2375 goto err;
2376 init_func_state(env, frame,
2377 BPF_MAIN_FUNC /* callsite */,
2378 0 /* frameno within this callchain */,
2379 subprog /* subprog number within this prog */);
2380 elem->st.frame[0] = frame;
2381 return &elem->st;
2382err:
2383 free_verifier_state(env->cur_state, true);
2384 env->cur_state = NULL;
2385 /* pop all elements and return */
2386 while (!pop_stack(env, NULL, NULL, false));
2387 return NULL;
2388}
2389
2390
17a52670
AS
2391enum reg_arg_type {
2392 SRC_OP, /* register is used as source operand */
2393 DST_OP, /* register is used as destination operand */
2394 DST_OP_NO_MARK /* same as above, check only, don't mark */
2395};
2396
cc8b0b92
AS
2397static int cmp_subprogs(const void *a, const void *b)
2398{
9c8105bd
JW
2399 return ((struct bpf_subprog_info *)a)->start -
2400 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
2401}
2402
2403static int find_subprog(struct bpf_verifier_env *env, int off)
2404{
9c8105bd 2405 struct bpf_subprog_info *p;
cc8b0b92 2406
9c8105bd
JW
2407 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2408 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
2409 if (!p)
2410 return -ENOENT;
9c8105bd 2411 return p - env->subprog_info;
cc8b0b92
AS
2412
2413}
2414
2415static int add_subprog(struct bpf_verifier_env *env, int off)
2416{
2417 int insn_cnt = env->prog->len;
2418 int ret;
2419
2420 if (off >= insn_cnt || off < 0) {
2421 verbose(env, "call to invalid destination\n");
2422 return -EINVAL;
2423 }
2424 ret = find_subprog(env, off);
2425 if (ret >= 0)
282a0f46 2426 return ret;
4cb3d99c 2427 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
2428 verbose(env, "too many subprograms\n");
2429 return -E2BIG;
2430 }
e6ac2450 2431 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
2432 env->subprog_info[env->subprog_cnt++].start = off;
2433 sort(env->subprog_info, env->subprog_cnt,
2434 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 2435 return env->subprog_cnt - 1;
cc8b0b92
AS
2436}
2437
2357672c
KKD
2438#define MAX_KFUNC_DESCS 256
2439#define MAX_KFUNC_BTFS 256
2440
e6ac2450
MKL
2441struct bpf_kfunc_desc {
2442 struct btf_func_model func_model;
2443 u32 func_id;
2444 s32 imm;
2357672c
KKD
2445 u16 offset;
2446};
2447
2448struct bpf_kfunc_btf {
2449 struct btf *btf;
2450 struct module *module;
2451 u16 offset;
e6ac2450
MKL
2452};
2453
e6ac2450
MKL
2454struct bpf_kfunc_desc_tab {
2455 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2456 u32 nr_descs;
2457};
2458
2357672c
KKD
2459struct bpf_kfunc_btf_tab {
2460 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2461 u32 nr_descs;
2462};
2463
2464static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
e6ac2450
MKL
2465{
2466 const struct bpf_kfunc_desc *d0 = a;
2467 const struct bpf_kfunc_desc *d1 = b;
2468
2469 /* func_id is not greater than BTF_MAX_TYPE */
2357672c
KKD
2470 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2471}
2472
2473static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2474{
2475 const struct bpf_kfunc_btf *d0 = a;
2476 const struct bpf_kfunc_btf *d1 = b;
2477
2478 return d0->offset - d1->offset;
e6ac2450
MKL
2479}
2480
2481static const struct bpf_kfunc_desc *
2357672c 2482find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
e6ac2450
MKL
2483{
2484 struct bpf_kfunc_desc desc = {
2485 .func_id = func_id,
2357672c 2486 .offset = offset,
e6ac2450
MKL
2487 };
2488 struct bpf_kfunc_desc_tab *tab;
2489
2490 tab = prog->aux->kfunc_tab;
2491 return bsearch(&desc, tab->descs, tab->nr_descs,
2357672c
KKD
2492 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2493}
2494
2495static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
b202d844 2496 s16 offset)
2357672c
KKD
2497{
2498 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2499 struct bpf_kfunc_btf_tab *tab;
2500 struct bpf_kfunc_btf *b;
2501 struct module *mod;
2502 struct btf *btf;
2503 int btf_fd;
2504
2505 tab = env->prog->aux->kfunc_btf_tab;
2506 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2507 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2508 if (!b) {
2509 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2510 verbose(env, "too many different module BTFs\n");
2511 return ERR_PTR(-E2BIG);
2512 }
2513
2514 if (bpfptr_is_null(env->fd_array)) {
2515 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2516 return ERR_PTR(-EPROTO);
2517 }
2518
2519 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2520 offset * sizeof(btf_fd),
2521 sizeof(btf_fd)))
2522 return ERR_PTR(-EFAULT);
2523
2524 btf = btf_get_by_fd(btf_fd);
588cd7ef
KKD
2525 if (IS_ERR(btf)) {
2526 verbose(env, "invalid module BTF fd specified\n");
2357672c 2527 return btf;
588cd7ef 2528 }
2357672c
KKD
2529
2530 if (!btf_is_module(btf)) {
2531 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2532 btf_put(btf);
2533 return ERR_PTR(-EINVAL);
2534 }
2535
2536 mod = btf_try_get_module(btf);
2537 if (!mod) {
2538 btf_put(btf);
2539 return ERR_PTR(-ENXIO);
2540 }
2541
2542 b = &tab->descs[tab->nr_descs++];
2543 b->btf = btf;
2544 b->module = mod;
2545 b->offset = offset;
2546
2547 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2548 kfunc_btf_cmp_by_off, NULL);
2549 }
2357672c 2550 return b->btf;
e6ac2450
MKL
2551}
2552
2357672c
KKD
2553void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2554{
2555 if (!tab)
2556 return;
2557
2558 while (tab->nr_descs--) {
2559 module_put(tab->descs[tab->nr_descs].module);
2560 btf_put(tab->descs[tab->nr_descs].btf);
2561 }
2562 kfree(tab);
2563}
2564
43bf0878 2565static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2357672c 2566{
2357672c
KKD
2567 if (offset) {
2568 if (offset < 0) {
2569 /* In the future, this can be allowed to increase limit
2570 * of fd index into fd_array, interpreted as u16.
2571 */
2572 verbose(env, "negative offset disallowed for kernel module function call\n");
2573 return ERR_PTR(-EINVAL);
2574 }
2575
b202d844 2576 return __find_kfunc_desc_btf(env, offset);
2357672c
KKD
2577 }
2578 return btf_vmlinux ?: ERR_PTR(-ENOENT);
e6ac2450
MKL
2579}
2580
2357672c 2581static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
e6ac2450
MKL
2582{
2583 const struct btf_type *func, *func_proto;
2357672c 2584 struct bpf_kfunc_btf_tab *btf_tab;
e6ac2450
MKL
2585 struct bpf_kfunc_desc_tab *tab;
2586 struct bpf_prog_aux *prog_aux;
2587 struct bpf_kfunc_desc *desc;
2588 const char *func_name;
2357672c 2589 struct btf *desc_btf;
8cbf062a 2590 unsigned long call_imm;
e6ac2450
MKL
2591 unsigned long addr;
2592 int err;
2593
2594 prog_aux = env->prog->aux;
2595 tab = prog_aux->kfunc_tab;
2357672c 2596 btf_tab = prog_aux->kfunc_btf_tab;
e6ac2450
MKL
2597 if (!tab) {
2598 if (!btf_vmlinux) {
2599 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2600 return -ENOTSUPP;
2601 }
2602
2603 if (!env->prog->jit_requested) {
2604 verbose(env, "JIT is required for calling kernel function\n");
2605 return -ENOTSUPP;
2606 }
2607
2608 if (!bpf_jit_supports_kfunc_call()) {
2609 verbose(env, "JIT does not support calling kernel function\n");
2610 return -ENOTSUPP;
2611 }
2612
2613 if (!env->prog->gpl_compatible) {
2614 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2615 return -EINVAL;
2616 }
2617
2618 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2619 if (!tab)
2620 return -ENOMEM;
2621 prog_aux->kfunc_tab = tab;
2622 }
2623
a5d82727
KKD
2624 /* func_id == 0 is always invalid, but instead of returning an error, be
2625 * conservative and wait until the code elimination pass before returning
2626 * error, so that invalid calls that get pruned out can be in BPF programs
2627 * loaded from userspace. It is also required that offset be untouched
2628 * for such calls.
2629 */
2630 if (!func_id && !offset)
2631 return 0;
2632
2357672c
KKD
2633 if (!btf_tab && offset) {
2634 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2635 if (!btf_tab)
2636 return -ENOMEM;
2637 prog_aux->kfunc_btf_tab = btf_tab;
2638 }
2639
43bf0878 2640 desc_btf = find_kfunc_desc_btf(env, offset);
2357672c
KKD
2641 if (IS_ERR(desc_btf)) {
2642 verbose(env, "failed to find BTF for kernel function\n");
2643 return PTR_ERR(desc_btf);
2644 }
2645
2646 if (find_kfunc_desc(env->prog, func_id, offset))
e6ac2450
MKL
2647 return 0;
2648
2649 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2650 verbose(env, "too many different kernel function calls\n");
2651 return -E2BIG;
2652 }
2653
2357672c 2654 func = btf_type_by_id(desc_btf, func_id);
e6ac2450
MKL
2655 if (!func || !btf_type_is_func(func)) {
2656 verbose(env, "kernel btf_id %u is not a function\n",
2657 func_id);
2658 return -EINVAL;
2659 }
2357672c 2660 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450
MKL
2661 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2662 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2663 func_id);
2664 return -EINVAL;
2665 }
2666
2357672c 2667 func_name = btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
2668 addr = kallsyms_lookup_name(func_name);
2669 if (!addr) {
2670 verbose(env, "cannot find address for kernel function %s\n",
2671 func_name);
2672 return -EINVAL;
2673 }
2674
8cbf062a
HT
2675 call_imm = BPF_CALL_IMM(addr);
2676 /* Check whether or not the relative offset overflows desc->imm */
2677 if ((unsigned long)(s32)call_imm != call_imm) {
2678 verbose(env, "address of kernel function %s is out of range\n",
2679 func_name);
2680 return -EINVAL;
2681 }
2682
3d76a4d3
SF
2683 if (bpf_dev_bound_kfunc_id(func_id)) {
2684 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2685 if (err)
2686 return err;
2687 }
2688
e6ac2450
MKL
2689 desc = &tab->descs[tab->nr_descs++];
2690 desc->func_id = func_id;
8cbf062a 2691 desc->imm = call_imm;
2357672c
KKD
2692 desc->offset = offset;
2693 err = btf_distill_func_proto(&env->log, desc_btf,
e6ac2450
MKL
2694 func_proto, func_name,
2695 &desc->func_model);
2696 if (!err)
2697 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2357672c 2698 kfunc_desc_cmp_by_id_off, NULL);
e6ac2450
MKL
2699 return err;
2700}
2701
2702static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2703{
2704 const struct bpf_kfunc_desc *d0 = a;
2705 const struct bpf_kfunc_desc *d1 = b;
2706
2707 if (d0->imm > d1->imm)
2708 return 1;
2709 else if (d0->imm < d1->imm)
2710 return -1;
2711 return 0;
2712}
2713
2714static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2715{
2716 struct bpf_kfunc_desc_tab *tab;
2717
2718 tab = prog->aux->kfunc_tab;
2719 if (!tab)
2720 return;
2721
2722 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2723 kfunc_desc_cmp_by_imm, NULL);
2724}
2725
2726bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2727{
2728 return !!prog->aux->kfunc_tab;
2729}
2730
2731const struct btf_func_model *
2732bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2733 const struct bpf_insn *insn)
2734{
2735 const struct bpf_kfunc_desc desc = {
2736 .imm = insn->imm,
2737 };
2738 const struct bpf_kfunc_desc *res;
2739 struct bpf_kfunc_desc_tab *tab;
2740
2741 tab = prog->aux->kfunc_tab;
2742 res = bsearch(&desc, tab->descs, tab->nr_descs,
2743 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2744
2745 return res ? &res->func_model : NULL;
2746}
2747
2748static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 2749{
9c8105bd 2750 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 2751 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 2752 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 2753
f910cefa
JW
2754 /* Add entry function. */
2755 ret = add_subprog(env, 0);
e6ac2450 2756 if (ret)
f910cefa
JW
2757 return ret;
2758
e6ac2450
MKL
2759 for (i = 0; i < insn_cnt; i++, insn++) {
2760 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2761 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 2762 continue;
e6ac2450 2763
2c78ee89 2764 if (!env->bpf_capable) {
e6ac2450 2765 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
2766 return -EPERM;
2767 }
e6ac2450 2768
3990ed4c 2769 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
e6ac2450 2770 ret = add_subprog(env, i + insn->imm + 1);
3990ed4c 2771 else
2357672c 2772 ret = add_kfunc_call(env, insn->imm, insn->off);
e6ac2450 2773
cc8b0b92
AS
2774 if (ret < 0)
2775 return ret;
2776 }
2777
4cb3d99c
JW
2778 /* Add a fake 'exit' subprog which could simplify subprog iteration
2779 * logic. 'subprog_cnt' should not be increased.
2780 */
2781 subprog[env->subprog_cnt].start = insn_cnt;
2782
06ee7115 2783 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 2784 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 2785 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 2786
e6ac2450
MKL
2787 return 0;
2788}
2789
2790static int check_subprogs(struct bpf_verifier_env *env)
2791{
2792 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2793 struct bpf_subprog_info *subprog = env->subprog_info;
2794 struct bpf_insn *insn = env->prog->insnsi;
2795 int insn_cnt = env->prog->len;
2796
cc8b0b92 2797 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
2798 subprog_start = subprog[cur_subprog].start;
2799 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2800 for (i = 0; i < insn_cnt; i++) {
2801 u8 code = insn[i].code;
2802
7f6e4312 2803 if (code == (BPF_JMP | BPF_CALL) &&
df2ccc18
IL
2804 insn[i].src_reg == 0 &&
2805 insn[i].imm == BPF_FUNC_tail_call)
7f6e4312 2806 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
2807 if (BPF_CLASS(code) == BPF_LD &&
2808 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2809 subprog[cur_subprog].has_ld_abs = true;
092ed096 2810 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
2811 goto next;
2812 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2813 goto next;
2814 off = i + insn[i].off + 1;
2815 if (off < subprog_start || off >= subprog_end) {
2816 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2817 return -EINVAL;
2818 }
2819next:
2820 if (i == subprog_end - 1) {
2821 /* to avoid fall-through from one subprog into another
2822 * the last insn of the subprog should be either exit
2823 * or unconditional jump back
2824 */
2825 if (code != (BPF_JMP | BPF_EXIT) &&
2826 code != (BPF_JMP | BPF_JA)) {
2827 verbose(env, "last insn is not an exit or jmp\n");
2828 return -EINVAL;
2829 }
2830 subprog_start = subprog_end;
4cb3d99c
JW
2831 cur_subprog++;
2832 if (cur_subprog < env->subprog_cnt)
9c8105bd 2833 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2834 }
2835 }
2836 return 0;
2837}
2838
679c782d
EC
2839/* Parentage chain of this register (or stack slot) should take care of all
2840 * issues like callee-saved registers, stack slot allocation time, etc.
2841 */
f4d7e40a 2842static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 2843 const struct bpf_reg_state *state,
5327ed3d 2844 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
2845{
2846 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 2847 int cnt = 0;
dc503a8a
EC
2848
2849 while (parent) {
2850 /* if read wasn't screened by an earlier write ... */
679c782d 2851 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 2852 break;
9242b5f5
AS
2853 if (parent->live & REG_LIVE_DONE) {
2854 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
c25b2ae1 2855 reg_type_str(env, parent->type),
9242b5f5
AS
2856 parent->var_off.value, parent->off);
2857 return -EFAULT;
2858 }
5327ed3d
JW
2859 /* The first condition is more likely to be true than the
2860 * second, checked it first.
2861 */
2862 if ((parent->live & REG_LIVE_READ) == flag ||
2863 parent->live & REG_LIVE_READ64)
25af32da
AS
2864 /* The parentage chain never changes and
2865 * this parent was already marked as LIVE_READ.
2866 * There is no need to keep walking the chain again and
2867 * keep re-marking all parents as LIVE_READ.
2868 * This case happens when the same register is read
2869 * multiple times without writes into it in-between.
5327ed3d
JW
2870 * Also, if parent has the stronger REG_LIVE_READ64 set,
2871 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
2872 */
2873 break;
dc503a8a 2874 /* ... then we depend on parent's value */
5327ed3d
JW
2875 parent->live |= flag;
2876 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2877 if (flag == REG_LIVE_READ64)
2878 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
2879 state = parent;
2880 parent = state->parent;
f4d7e40a 2881 writes = true;
06ee7115 2882 cnt++;
dc503a8a 2883 }
06ee7115
AS
2884
2885 if (env->longest_mark_read_walk < cnt)
2886 env->longest_mark_read_walk = cnt;
f4d7e40a 2887 return 0;
dc503a8a
EC
2888}
2889
d6fefa11
KKD
2890static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2891{
2892 struct bpf_func_state *state = func(env, reg);
2893 int spi, ret;
2894
2895 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2896 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2897 * check_kfunc_call.
2898 */
2899 if (reg->type == CONST_PTR_TO_DYNPTR)
2900 return 0;
79168a66
KKD
2901 spi = dynptr_get_spi(env, reg);
2902 if (spi < 0)
2903 return spi;
d6fefa11
KKD
2904 /* Caller ensures dynptr is valid and initialized, which means spi is in
2905 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2906 * read.
2907 */
2908 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2909 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2910 if (ret)
2911 return ret;
2912 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2913 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2914}
2915
06accc87
AN
2916static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2917 int spi, int nr_slots)
2918{
2919 struct bpf_func_state *state = func(env, reg);
2920 int err, i;
2921
2922 for (i = 0; i < nr_slots; i++) {
2923 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2924
2925 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2926 if (err)
2927 return err;
2928
2929 mark_stack_slot_scratched(env, spi - i);
2930 }
2931
2932 return 0;
2933}
2934
5327ed3d
JW
2935/* This function is supposed to be used by the following 32-bit optimization
2936 * code only. It returns TRUE if the source or destination register operates
2937 * on 64-bit, otherwise return FALSE.
2938 */
2939static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2940 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2941{
2942 u8 code, class, op;
2943
2944 code = insn->code;
2945 class = BPF_CLASS(code);
2946 op = BPF_OP(code);
2947 if (class == BPF_JMP) {
2948 /* BPF_EXIT for "main" will reach here. Return TRUE
2949 * conservatively.
2950 */
2951 if (op == BPF_EXIT)
2952 return true;
2953 if (op == BPF_CALL) {
2954 /* BPF to BPF call will reach here because of marking
2955 * caller saved clobber with DST_OP_NO_MARK for which we
2956 * don't care the register def because they are anyway
2957 * marked as NOT_INIT already.
2958 */
2959 if (insn->src_reg == BPF_PSEUDO_CALL)
2960 return false;
2961 /* Helper call will reach here because of arg type
2962 * check, conservatively return TRUE.
2963 */
2964 if (t == SRC_OP)
2965 return true;
2966
2967 return false;
2968 }
2969 }
2970
2971 if (class == BPF_ALU64 || class == BPF_JMP ||
2972 /* BPF_END always use BPF_ALU class. */
2973 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2974 return true;
2975
2976 if (class == BPF_ALU || class == BPF_JMP32)
2977 return false;
2978
2979 if (class == BPF_LDX) {
2980 if (t != SRC_OP)
2981 return BPF_SIZE(code) == BPF_DW;
2982 /* LDX source must be ptr. */
2983 return true;
2984 }
2985
2986 if (class == BPF_STX) {
83a28819
IL
2987 /* BPF_STX (including atomic variants) has multiple source
2988 * operands, one of which is a ptr. Check whether the caller is
2989 * asking about it.
2990 */
2991 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
2992 return true;
2993 return BPF_SIZE(code) == BPF_DW;
2994 }
2995
2996 if (class == BPF_LD) {
2997 u8 mode = BPF_MODE(code);
2998
2999 /* LD_IMM64 */
3000 if (mode == BPF_IMM)
3001 return true;
3002
3003 /* Both LD_IND and LD_ABS return 32-bit data. */
3004 if (t != SRC_OP)
3005 return false;
3006
3007 /* Implicit ctx ptr. */
3008 if (regno == BPF_REG_6)
3009 return true;
3010
3011 /* Explicit source could be any width. */
3012 return true;
3013 }
3014
3015 if (class == BPF_ST)
3016 /* The only source register for BPF_ST is a ptr. */
3017 return true;
3018
3019 /* Conservatively return true at default. */
3020 return true;
3021}
3022
83a28819
IL
3023/* Return the regno defined by the insn, or -1. */
3024static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 3025{
83a28819
IL
3026 switch (BPF_CLASS(insn->code)) {
3027 case BPF_JMP:
3028 case BPF_JMP32:
3029 case BPF_ST:
3030 return -1;
3031 case BPF_STX:
3032 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3033 (insn->imm & BPF_FETCH)) {
3034 if (insn->imm == BPF_CMPXCHG)
3035 return BPF_REG_0;
3036 else
3037 return insn->src_reg;
3038 } else {
3039 return -1;
3040 }
3041 default:
3042 return insn->dst_reg;
3043 }
b325fbca
JW
3044}
3045
3046/* Return TRUE if INSN has defined any 32-bit value explicitly. */
3047static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3048{
83a28819
IL
3049 int dst_reg = insn_def_regno(insn);
3050
3051 if (dst_reg == -1)
b325fbca
JW
3052 return false;
3053
83a28819 3054 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
3055}
3056
5327ed3d
JW
3057static void mark_insn_zext(struct bpf_verifier_env *env,
3058 struct bpf_reg_state *reg)
3059{
3060 s32 def_idx = reg->subreg_def;
3061
3062 if (def_idx == DEF_NOT_SUBREG)
3063 return;
3064
3065 env->insn_aux_data[def_idx - 1].zext_dst = true;
3066 /* The dst will be zero extended, so won't be sub-register anymore. */
3067 reg->subreg_def = DEF_NOT_SUBREG;
3068}
3069
dc503a8a 3070static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
3071 enum reg_arg_type t)
3072{
f4d7e40a
AS
3073 struct bpf_verifier_state *vstate = env->cur_state;
3074 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 3075 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 3076 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 3077 bool rw64;
dc503a8a 3078
17a52670 3079 if (regno >= MAX_BPF_REG) {
61bd5218 3080 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
3081 return -EINVAL;
3082 }
3083
0f55f9ed
CL
3084 mark_reg_scratched(env, regno);
3085
c342dc10 3086 reg = &regs[regno];
5327ed3d 3087 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
3088 if (t == SRC_OP) {
3089 /* check whether register used as source operand can be read */
c342dc10 3090 if (reg->type == NOT_INIT) {
61bd5218 3091 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
3092 return -EACCES;
3093 }
679c782d 3094 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
3095 if (regno == BPF_REG_FP)
3096 return 0;
3097
5327ed3d
JW
3098 if (rw64)
3099 mark_insn_zext(env, reg);
3100
3101 return mark_reg_read(env, reg, reg->parent,
3102 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
3103 } else {
3104 /* check whether register used as dest operand can be written to */
3105 if (regno == BPF_REG_FP) {
61bd5218 3106 verbose(env, "frame pointer is read only\n");
17a52670
AS
3107 return -EACCES;
3108 }
c342dc10 3109 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 3110 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 3111 if (t == DST_OP)
61bd5218 3112 mark_reg_unknown(env, regs, regno);
17a52670
AS
3113 }
3114 return 0;
3115}
3116
bffdeaa8
AN
3117static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3118{
3119 env->insn_aux_data[idx].jmp_point = true;
3120}
3121
3122static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3123{
3124 return env->insn_aux_data[insn_idx].jmp_point;
3125}
3126
b5dc0163
AS
3127/* for any branch, call, exit record the history of jmps in the given state */
3128static int push_jmp_history(struct bpf_verifier_env *env,
3129 struct bpf_verifier_state *cur)
3130{
3131 u32 cnt = cur->jmp_history_cnt;
3132 struct bpf_idx_pair *p;
ceb35b66 3133 size_t alloc_size;
b5dc0163 3134
bffdeaa8
AN
3135 if (!is_jmp_point(env, env->insn_idx))
3136 return 0;
3137
b5dc0163 3138 cnt++;
ceb35b66
KC
3139 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3140 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
b5dc0163
AS
3141 if (!p)
3142 return -ENOMEM;
3143 p[cnt - 1].idx = env->insn_idx;
3144 p[cnt - 1].prev_idx = env->prev_insn_idx;
3145 cur->jmp_history = p;
3146 cur->jmp_history_cnt = cnt;
3147 return 0;
3148}
3149
3150/* Backtrack one insn at a time. If idx is not at the top of recorded
3151 * history then previous instruction came from straight line execution.
3152 */
3153static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3154 u32 *history)
3155{
3156 u32 cnt = *history;
3157
3158 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3159 i = st->jmp_history[cnt - 1].prev_idx;
3160 (*history)--;
3161 } else {
3162 i--;
3163 }
3164 return i;
3165}
3166
e6ac2450
MKL
3167static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3168{
3169 const struct btf_type *func;
2357672c 3170 struct btf *desc_btf;
e6ac2450
MKL
3171
3172 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3173 return NULL;
3174
43bf0878 3175 desc_btf = find_kfunc_desc_btf(data, insn->off);
2357672c
KKD
3176 if (IS_ERR(desc_btf))
3177 return "<error>";
3178
3179 func = btf_type_by_id(desc_btf, insn->imm);
3180 return btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
3181}
3182
b5dc0163
AS
3183/* For given verifier state backtrack_insn() is called from the last insn to
3184 * the first insn. Its purpose is to compute a bitmask of registers and
3185 * stack slots that needs precision in the parent verifier state.
3186 */
3187static int backtrack_insn(struct bpf_verifier_env *env, int idx,
3188 u32 *reg_mask, u64 *stack_mask)
3189{
3190 const struct bpf_insn_cbs cbs = {
e6ac2450 3191 .cb_call = disasm_kfunc_name,
b5dc0163
AS
3192 .cb_print = verbose,
3193 .private_data = env,
3194 };
3195 struct bpf_insn *insn = env->prog->insnsi + idx;
3196 u8 class = BPF_CLASS(insn->code);
3197 u8 opcode = BPF_OP(insn->code);
3198 u8 mode = BPF_MODE(insn->code);
3199 u32 dreg = 1u << insn->dst_reg;
3200 u32 sreg = 1u << insn->src_reg;
3201 u32 spi;
3202
3203 if (insn->code == 0)
3204 return 0;
496f3324 3205 if (env->log.level & BPF_LOG_LEVEL2) {
b5dc0163
AS
3206 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
3207 verbose(env, "%d: ", idx);
3208 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3209 }
3210
3211 if (class == BPF_ALU || class == BPF_ALU64) {
3212 if (!(*reg_mask & dreg))
3213 return 0;
3214 if (opcode == BPF_MOV) {
3215 if (BPF_SRC(insn->code) == BPF_X) {
3216 /* dreg = sreg
3217 * dreg needs precision after this insn
3218 * sreg needs precision before this insn
3219 */
3220 *reg_mask &= ~dreg;
3221 *reg_mask |= sreg;
3222 } else {
3223 /* dreg = K
3224 * dreg needs precision after this insn.
3225 * Corresponding register is already marked
3226 * as precise=true in this verifier state.
3227 * No further markings in parent are necessary
3228 */
3229 *reg_mask &= ~dreg;
3230 }
3231 } else {
3232 if (BPF_SRC(insn->code) == BPF_X) {
3233 /* dreg += sreg
3234 * both dreg and sreg need precision
3235 * before this insn
3236 */
3237 *reg_mask |= sreg;
3238 } /* else dreg += K
3239 * dreg still needs precision before this insn
3240 */
3241 }
3242 } else if (class == BPF_LDX) {
3243 if (!(*reg_mask & dreg))
3244 return 0;
3245 *reg_mask &= ~dreg;
3246
3247 /* scalars can only be spilled into stack w/o losing precision.
3248 * Load from any other memory can be zero extended.
3249 * The desire to keep that precision is already indicated
3250 * by 'precise' mark in corresponding register of this state.
3251 * No further tracking necessary.
3252 */
3253 if (insn->src_reg != BPF_REG_FP)
3254 return 0;
b5dc0163
AS
3255
3256 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3257 * that [fp - off] slot contains scalar that needs to be
3258 * tracked with precision
3259 */
3260 spi = (-insn->off - 1) / BPF_REG_SIZE;
3261 if (spi >= 64) {
3262 verbose(env, "BUG spi %d\n", spi);
3263 WARN_ONCE(1, "verifier backtracking bug");
3264 return -EFAULT;
3265 }
3266 *stack_mask |= 1ull << spi;
b3b50f05 3267 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 3268 if (*reg_mask & dreg)
b3b50f05 3269 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
3270 * to access memory. It means backtracking
3271 * encountered a case of pointer subtraction.
3272 */
3273 return -ENOTSUPP;
3274 /* scalars can only be spilled into stack */
3275 if (insn->dst_reg != BPF_REG_FP)
3276 return 0;
b5dc0163
AS
3277 spi = (-insn->off - 1) / BPF_REG_SIZE;
3278 if (spi >= 64) {
3279 verbose(env, "BUG spi %d\n", spi);
3280 WARN_ONCE(1, "verifier backtracking bug");
3281 return -EFAULT;
3282 }
3283 if (!(*stack_mask & (1ull << spi)))
3284 return 0;
3285 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
3286 if (class == BPF_STX)
3287 *reg_mask |= sreg;
b5dc0163
AS
3288 } else if (class == BPF_JMP || class == BPF_JMP32) {
3289 if (opcode == BPF_CALL) {
3290 if (insn->src_reg == BPF_PSEUDO_CALL)
3291 return -ENOTSUPP;
be2ef816
AN
3292 /* BPF helpers that invoke callback subprogs are
3293 * equivalent to BPF_PSEUDO_CALL above
3294 */
3295 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3296 return -ENOTSUPP;
d3178e8a
HS
3297 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3298 * catch this error later. Make backtracking conservative
3299 * with ENOTSUPP.
3300 */
3301 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3302 return -ENOTSUPP;
b5dc0163
AS
3303 /* regular helper call sets R0 */
3304 *reg_mask &= ~1;
3305 if (*reg_mask & 0x3f) {
3306 /* if backtracing was looking for registers R1-R5
3307 * they should have been found already.
3308 */
3309 verbose(env, "BUG regs %x\n", *reg_mask);
3310 WARN_ONCE(1, "verifier backtracking bug");
3311 return -EFAULT;
3312 }
3313 } else if (opcode == BPF_EXIT) {
3314 return -ENOTSUPP;
3315 }
3316 } else if (class == BPF_LD) {
3317 if (!(*reg_mask & dreg))
3318 return 0;
3319 *reg_mask &= ~dreg;
3320 /* It's ld_imm64 or ld_abs or ld_ind.
3321 * For ld_imm64 no further tracking of precision
3322 * into parent is necessary
3323 */
3324 if (mode == BPF_IND || mode == BPF_ABS)
3325 /* to be analyzed */
3326 return -ENOTSUPP;
b5dc0163
AS
3327 }
3328 return 0;
3329}
3330
3331/* the scalar precision tracking algorithm:
3332 * . at the start all registers have precise=false.
3333 * . scalar ranges are tracked as normal through alu and jmp insns.
3334 * . once precise value of the scalar register is used in:
3335 * . ptr + scalar alu
3336 * . if (scalar cond K|scalar)
3337 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3338 * backtrack through the verifier states and mark all registers and
3339 * stack slots with spilled constants that these scalar regisers
3340 * should be precise.
3341 * . during state pruning two registers (or spilled stack slots)
3342 * are equivalent if both are not precise.
3343 *
3344 * Note the verifier cannot simply walk register parentage chain,
3345 * since many different registers and stack slots could have been
3346 * used to compute single precise scalar.
3347 *
3348 * The approach of starting with precise=true for all registers and then
3349 * backtrack to mark a register as not precise when the verifier detects
3350 * that program doesn't care about specific value (e.g., when helper
3351 * takes register as ARG_ANYTHING parameter) is not safe.
3352 *
3353 * It's ok to walk single parentage chain of the verifier states.
3354 * It's possible that this backtracking will go all the way till 1st insn.
3355 * All other branches will be explored for needing precision later.
3356 *
3357 * The backtracking needs to deal with cases like:
3358 * 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)
3359 * r9 -= r8
3360 * r5 = r9
3361 * if r5 > 0x79f goto pc+7
3362 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3363 * r5 += 1
3364 * ...
3365 * call bpf_perf_event_output#25
3366 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3367 *
3368 * and this case:
3369 * r6 = 1
3370 * call foo // uses callee's r6 inside to compute r0
3371 * r0 += r6
3372 * if r0 == 0 goto
3373 *
3374 * to track above reg_mask/stack_mask needs to be independent for each frame.
3375 *
3376 * Also if parent's curframe > frame where backtracking started,
3377 * the verifier need to mark registers in both frames, otherwise callees
3378 * may incorrectly prune callers. This is similar to
3379 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3380 *
3381 * For now backtracking falls back into conservative marking.
3382 */
3383static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3384 struct bpf_verifier_state *st)
3385{
3386 struct bpf_func_state *func;
3387 struct bpf_reg_state *reg;
3388 int i, j;
3389
3390 /* big hammer: mark all scalars precise in this path.
3391 * pop_stack may still get !precise scalars.
f63181b6
AN
3392 * We also skip current state and go straight to first parent state,
3393 * because precision markings in current non-checkpointed state are
3394 * not needed. See why in the comment in __mark_chain_precision below.
b5dc0163 3395 */
f63181b6 3396 for (st = st->parent; st; st = st->parent) {
b5dc0163
AS
3397 for (i = 0; i <= st->curframe; i++) {
3398 func = st->frame[i];
3399 for (j = 0; j < BPF_REG_FP; j++) {
3400 reg = &func->regs[j];
3401 if (reg->type != SCALAR_VALUE)
3402 continue;
3403 reg->precise = true;
3404 }
3405 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
27113c59 3406 if (!is_spilled_reg(&func->stack[j]))
b5dc0163
AS
3407 continue;
3408 reg = &func->stack[j].spilled_ptr;
3409 if (reg->type != SCALAR_VALUE)
3410 continue;
3411 reg->precise = true;
3412 }
3413 }
f63181b6 3414 }
b5dc0163
AS
3415}
3416
7a830b53
AN
3417static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3418{
3419 struct bpf_func_state *func;
3420 struct bpf_reg_state *reg;
3421 int i, j;
3422
3423 for (i = 0; i <= st->curframe; i++) {
3424 func = st->frame[i];
3425 for (j = 0; j < BPF_REG_FP; j++) {
3426 reg = &func->regs[j];
3427 if (reg->type != SCALAR_VALUE)
3428 continue;
3429 reg->precise = false;
3430 }
3431 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3432 if (!is_spilled_reg(&func->stack[j]))
3433 continue;
3434 reg = &func->stack[j].spilled_ptr;
3435 if (reg->type != SCALAR_VALUE)
3436 continue;
3437 reg->precise = false;
3438 }
3439 }
3440}
3441
f63181b6
AN
3442/*
3443 * __mark_chain_precision() backtracks BPF program instruction sequence and
3444 * chain of verifier states making sure that register *regno* (if regno >= 0)
3445 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3446 * SCALARS, as well as any other registers and slots that contribute to
3447 * a tracked state of given registers/stack slots, depending on specific BPF
3448 * assembly instructions (see backtrack_insns() for exact instruction handling
3449 * logic). This backtracking relies on recorded jmp_history and is able to
3450 * traverse entire chain of parent states. This process ends only when all the
3451 * necessary registers/slots and their transitive dependencies are marked as
3452 * precise.
3453 *
3454 * One important and subtle aspect is that precise marks *do not matter* in
3455 * the currently verified state (current state). It is important to understand
3456 * why this is the case.
3457 *
3458 * First, note that current state is the state that is not yet "checkpointed",
3459 * i.e., it is not yet put into env->explored_states, and it has no children
3460 * states as well. It's ephemeral, and can end up either a) being discarded if
3461 * compatible explored state is found at some point or BPF_EXIT instruction is
3462 * reached or b) checkpointed and put into env->explored_states, branching out
3463 * into one or more children states.
3464 *
3465 * In the former case, precise markings in current state are completely
3466 * ignored by state comparison code (see regsafe() for details). Only
3467 * checkpointed ("old") state precise markings are important, and if old
3468 * state's register/slot is precise, regsafe() assumes current state's
3469 * register/slot as precise and checks value ranges exactly and precisely. If
3470 * states turn out to be compatible, current state's necessary precise
3471 * markings and any required parent states' precise markings are enforced
3472 * after the fact with propagate_precision() logic, after the fact. But it's
3473 * important to realize that in this case, even after marking current state
3474 * registers/slots as precise, we immediately discard current state. So what
3475 * actually matters is any of the precise markings propagated into current
3476 * state's parent states, which are always checkpointed (due to b) case above).
3477 * As such, for scenario a) it doesn't matter if current state has precise
3478 * markings set or not.
3479 *
3480 * Now, for the scenario b), checkpointing and forking into child(ren)
3481 * state(s). Note that before current state gets to checkpointing step, any
3482 * processed instruction always assumes precise SCALAR register/slot
3483 * knowledge: if precise value or range is useful to prune jump branch, BPF
3484 * verifier takes this opportunity enthusiastically. Similarly, when
3485 * register's value is used to calculate offset or memory address, exact
3486 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3487 * what we mentioned above about state comparison ignoring precise markings
3488 * during state comparison, BPF verifier ignores and also assumes precise
3489 * markings *at will* during instruction verification process. But as verifier
3490 * assumes precision, it also propagates any precision dependencies across
3491 * parent states, which are not yet finalized, so can be further restricted
3492 * based on new knowledge gained from restrictions enforced by their children
3493 * states. This is so that once those parent states are finalized, i.e., when
3494 * they have no more active children state, state comparison logic in
3495 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3496 * required for correctness.
3497 *
3498 * To build a bit more intuition, note also that once a state is checkpointed,
3499 * the path we took to get to that state is not important. This is crucial
3500 * property for state pruning. When state is checkpointed and finalized at
3501 * some instruction index, it can be correctly and safely used to "short
3502 * circuit" any *compatible* state that reaches exactly the same instruction
3503 * index. I.e., if we jumped to that instruction from a completely different
3504 * code path than original finalized state was derived from, it doesn't
3505 * matter, current state can be discarded because from that instruction
3506 * forward having a compatible state will ensure we will safely reach the
3507 * exit. States describe preconditions for further exploration, but completely
3508 * forget the history of how we got here.
3509 *
3510 * This also means that even if we needed precise SCALAR range to get to
3511 * finalized state, but from that point forward *that same* SCALAR register is
3512 * never used in a precise context (i.e., it's precise value is not needed for
3513 * correctness), it's correct and safe to mark such register as "imprecise"
3514 * (i.e., precise marking set to false). This is what we rely on when we do
3515 * not set precise marking in current state. If no child state requires
3516 * precision for any given SCALAR register, it's safe to dictate that it can
3517 * be imprecise. If any child state does require this register to be precise,
3518 * we'll mark it precise later retroactively during precise markings
3519 * propagation from child state to parent states.
7a830b53
AN
3520 *
3521 * Skipping precise marking setting in current state is a mild version of
3522 * relying on the above observation. But we can utilize this property even
3523 * more aggressively by proactively forgetting any precise marking in the
3524 * current state (which we inherited from the parent state), right before we
3525 * checkpoint it and branch off into new child state. This is done by
3526 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3527 * finalized states which help in short circuiting more future states.
f63181b6 3528 */
529409ea 3529static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
a3ce685d 3530 int spi)
b5dc0163
AS
3531{
3532 struct bpf_verifier_state *st = env->cur_state;
3533 int first_idx = st->first_insn_idx;
3534 int last_idx = env->insn_idx;
3535 struct bpf_func_state *func;
3536 struct bpf_reg_state *reg;
a3ce685d
AS
3537 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3538 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 3539 bool skip_first = true;
a3ce685d 3540 bool new_marks = false;
b5dc0163
AS
3541 int i, err;
3542
2c78ee89 3543 if (!env->bpf_capable)
b5dc0163
AS
3544 return 0;
3545
f63181b6
AN
3546 /* Do sanity checks against current state of register and/or stack
3547 * slot, but don't set precise flag in current state, as precision
3548 * tracking in the current state is unnecessary.
3549 */
529409ea 3550 func = st->frame[frame];
a3ce685d
AS
3551 if (regno >= 0) {
3552 reg = &func->regs[regno];
3553 if (reg->type != SCALAR_VALUE) {
3554 WARN_ONCE(1, "backtracing misuse");
3555 return -EFAULT;
3556 }
f63181b6 3557 new_marks = true;
b5dc0163 3558 }
b5dc0163 3559
a3ce685d 3560 while (spi >= 0) {
27113c59 3561 if (!is_spilled_reg(&func->stack[spi])) {
a3ce685d
AS
3562 stack_mask = 0;
3563 break;
3564 }
3565 reg = &func->stack[spi].spilled_ptr;
3566 if (reg->type != SCALAR_VALUE) {
3567 stack_mask = 0;
3568 break;
3569 }
f63181b6 3570 new_marks = true;
a3ce685d
AS
3571 break;
3572 }
3573
3574 if (!new_marks)
3575 return 0;
3576 if (!reg_mask && !stack_mask)
3577 return 0;
be2ef816 3578
b5dc0163
AS
3579 for (;;) {
3580 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
3581 u32 history = st->jmp_history_cnt;
3582
496f3324 3583 if (env->log.level & BPF_LOG_LEVEL2)
b5dc0163 3584 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
be2ef816
AN
3585
3586 if (last_idx < 0) {
3587 /* we are at the entry into subprog, which
3588 * is expected for global funcs, but only if
3589 * requested precise registers are R1-R5
3590 * (which are global func's input arguments)
3591 */
3592 if (st->curframe == 0 &&
3593 st->frame[0]->subprogno > 0 &&
3594 st->frame[0]->callsite == BPF_MAIN_FUNC &&
3595 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3596 bitmap_from_u64(mask, reg_mask);
3597 for_each_set_bit(i, mask, 32) {
3598 reg = &st->frame[0]->regs[i];
3599 if (reg->type != SCALAR_VALUE) {
3600 reg_mask &= ~(1u << i);
3601 continue;
3602 }
3603 reg->precise = true;
3604 }
3605 return 0;
3606 }
3607
3608 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3609 st->frame[0]->subprogno, reg_mask, stack_mask);
3610 WARN_ONCE(1, "verifier backtracking bug");
3611 return -EFAULT;
3612 }
3613
b5dc0163
AS
3614 for (i = last_idx;;) {
3615 if (skip_first) {
3616 err = 0;
3617 skip_first = false;
3618 } else {
3619 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3620 }
3621 if (err == -ENOTSUPP) {
3622 mark_all_scalars_precise(env, st);
3623 return 0;
3624 } else if (err) {
3625 return err;
3626 }
3627 if (!reg_mask && !stack_mask)
3628 /* Found assignment(s) into tracked register in this state.
3629 * Since this state is already marked, just return.
3630 * Nothing to be tracked further in the parent state.
3631 */
3632 return 0;
3633 if (i == first_idx)
3634 break;
3635 i = get_prev_insn_idx(st, i, &history);
3636 if (i >= env->prog->len) {
3637 /* This can happen if backtracking reached insn 0
3638 * and there are still reg_mask or stack_mask
3639 * to backtrack.
3640 * It means the backtracking missed the spot where
3641 * particular register was initialized with a constant.
3642 */
3643 verbose(env, "BUG backtracking idx %d\n", i);
3644 WARN_ONCE(1, "verifier backtracking bug");
3645 return -EFAULT;
3646 }
3647 }
3648 st = st->parent;
3649 if (!st)
3650 break;
3651
a3ce685d 3652 new_marks = false;
529409ea 3653 func = st->frame[frame];
b5dc0163
AS
3654 bitmap_from_u64(mask, reg_mask);
3655 for_each_set_bit(i, mask, 32) {
3656 reg = &func->regs[i];
a3ce685d
AS
3657 if (reg->type != SCALAR_VALUE) {
3658 reg_mask &= ~(1u << i);
b5dc0163 3659 continue;
a3ce685d 3660 }
b5dc0163
AS
3661 if (!reg->precise)
3662 new_marks = true;
3663 reg->precise = true;
3664 }
3665
3666 bitmap_from_u64(mask, stack_mask);
3667 for_each_set_bit(i, mask, 64) {
3668 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
3669 /* the sequence of instructions:
3670 * 2: (bf) r3 = r10
3671 * 3: (7b) *(u64 *)(r3 -8) = r0
3672 * 4: (79) r4 = *(u64 *)(r10 -8)
3673 * doesn't contain jmps. It's backtracked
3674 * as a single block.
3675 * During backtracking insn 3 is not recognized as
3676 * stack access, so at the end of backtracking
3677 * stack slot fp-8 is still marked in stack_mask.
3678 * However the parent state may not have accessed
3679 * fp-8 and it's "unallocated" stack space.
3680 * In such case fallback to conservative.
b5dc0163 3681 */
2339cd6c
AS
3682 mark_all_scalars_precise(env, st);
3683 return 0;
b5dc0163
AS
3684 }
3685
27113c59 3686 if (!is_spilled_reg(&func->stack[i])) {
a3ce685d 3687 stack_mask &= ~(1ull << i);
b5dc0163 3688 continue;
a3ce685d 3689 }
b5dc0163 3690 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
3691 if (reg->type != SCALAR_VALUE) {
3692 stack_mask &= ~(1ull << i);
b5dc0163 3693 continue;
a3ce685d 3694 }
b5dc0163
AS
3695 if (!reg->precise)
3696 new_marks = true;
3697 reg->precise = true;
3698 }
496f3324 3699 if (env->log.level & BPF_LOG_LEVEL2) {
2e576648 3700 verbose(env, "parent %s regs=%x stack=%llx marks:",
b5dc0163
AS
3701 new_marks ? "didn't have" : "already had",
3702 reg_mask, stack_mask);
2e576648 3703 print_verifier_state(env, func, true);
b5dc0163
AS
3704 }
3705
a3ce685d
AS
3706 if (!reg_mask && !stack_mask)
3707 break;
b5dc0163
AS
3708 if (!new_marks)
3709 break;
3710
3711 last_idx = st->last_insn_idx;
3712 first_idx = st->first_insn_idx;
3713 }
3714 return 0;
3715}
3716
eb1f7f71 3717int mark_chain_precision(struct bpf_verifier_env *env, int regno)
a3ce685d 3718{
529409ea 3719 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
a3ce685d
AS
3720}
3721
529409ea 3722static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
a3ce685d 3723{
529409ea 3724 return __mark_chain_precision(env, frame, regno, -1);
a3ce685d
AS
3725}
3726
529409ea 3727static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
a3ce685d 3728{
529409ea 3729 return __mark_chain_precision(env, frame, -1, spi);
a3ce685d 3730}
b5dc0163 3731
1be7f75d
AS
3732static bool is_spillable_regtype(enum bpf_reg_type type)
3733{
c25b2ae1 3734 switch (base_type(type)) {
1be7f75d 3735 case PTR_TO_MAP_VALUE:
1be7f75d
AS
3736 case PTR_TO_STACK:
3737 case PTR_TO_CTX:
969bf05e 3738 case PTR_TO_PACKET:
de8f3a83 3739 case PTR_TO_PACKET_META:
969bf05e 3740 case PTR_TO_PACKET_END:
d58e468b 3741 case PTR_TO_FLOW_KEYS:
1be7f75d 3742 case CONST_PTR_TO_MAP:
c64b7983 3743 case PTR_TO_SOCKET:
46f8bc92 3744 case PTR_TO_SOCK_COMMON:
655a51e5 3745 case PTR_TO_TCP_SOCK:
fada7fdc 3746 case PTR_TO_XDP_SOCK:
65726b5b 3747 case PTR_TO_BTF_ID:
20b2aff4 3748 case PTR_TO_BUF:
744ea4e3 3749 case PTR_TO_MEM:
69c087ba
YS
3750 case PTR_TO_FUNC:
3751 case PTR_TO_MAP_KEY:
1be7f75d
AS
3752 return true;
3753 default:
3754 return false;
3755 }
3756}
3757
cc2b14d5
AS
3758/* Does this register contain a constant zero? */
3759static bool register_is_null(struct bpf_reg_state *reg)
3760{
3761 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3762}
3763
f7cf25b2
AS
3764static bool register_is_const(struct bpf_reg_state *reg)
3765{
3766 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3767}
3768
5689d49b
YS
3769static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3770{
3771 return tnum_is_unknown(reg->var_off) &&
3772 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3773 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3774 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3775 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3776}
3777
3778static bool register_is_bounded(struct bpf_reg_state *reg)
3779{
3780 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3781}
3782
6e7e63cb
JH
3783static bool __is_pointer_value(bool allow_ptr_leaks,
3784 const struct bpf_reg_state *reg)
3785{
3786 if (allow_ptr_leaks)
3787 return false;
3788
3789 return reg->type != SCALAR_VALUE;
3790}
3791
71f656a5
EZ
3792/* Copy src state preserving dst->parent and dst->live fields */
3793static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3794{
3795 struct bpf_reg_state *parent = dst->parent;
3796 enum bpf_reg_liveness live = dst->live;
3797
3798 *dst = *src;
3799 dst->parent = parent;
3800 dst->live = live;
3801}
3802
f7cf25b2 3803static void save_register_state(struct bpf_func_state *state,
354e8f19
MKL
3804 int spi, struct bpf_reg_state *reg,
3805 int size)
f7cf25b2
AS
3806{
3807 int i;
3808
71f656a5 3809 copy_register_state(&state->stack[spi].spilled_ptr, reg);
354e8f19
MKL
3810 if (size == BPF_REG_SIZE)
3811 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
f7cf25b2 3812
354e8f19
MKL
3813 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3814 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
f7cf25b2 3815
354e8f19
MKL
3816 /* size < 8 bytes spill */
3817 for (; i; i--)
3818 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
f7cf25b2
AS
3819}
3820
ecdf985d
EZ
3821static bool is_bpf_st_mem(struct bpf_insn *insn)
3822{
3823 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3824}
3825
01f810ac 3826/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
3827 * stack boundary and alignment are checked in check_mem_access()
3828 */
01f810ac
AM
3829static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3830 /* stack frame we're writing to */
3831 struct bpf_func_state *state,
3832 int off, int size, int value_regno,
3833 int insn_idx)
17a52670 3834{
f4d7e40a 3835 struct bpf_func_state *cur; /* state of the current function */
638f5b90 3836 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
ecdf985d 3837 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
f7cf25b2 3838 struct bpf_reg_state *reg = NULL;
ecdf985d 3839 u32 dst_reg = insn->dst_reg;
638f5b90 3840
c69431aa 3841 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
3842 if (err)
3843 return err;
9c399760
AS
3844 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3845 * so it's aligned access and [off, off + size) are within stack limits
3846 */
638f5b90
AS
3847 if (!env->allow_ptr_leaks &&
3848 state->stack[spi].slot_type[0] == STACK_SPILL &&
3849 size != BPF_REG_SIZE) {
3850 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3851 return -EACCES;
3852 }
17a52670 3853
f4d7e40a 3854 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
3855 if (value_regno >= 0)
3856 reg = &cur->regs[value_regno];
2039f26f
DB
3857 if (!env->bypass_spec_v4) {
3858 bool sanitize = reg && is_spillable_regtype(reg->type);
3859
3860 for (i = 0; i < size; i++) {
e4f4db47
LG
3861 u8 type = state->stack[spi].slot_type[i];
3862
3863 if (type != STACK_MISC && type != STACK_ZERO) {
2039f26f
DB
3864 sanitize = true;
3865 break;
3866 }
3867 }
3868
3869 if (sanitize)
3870 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3871 }
17a52670 3872
ef8fc7a0
KKD
3873 err = destroy_if_dynptr_stack_slot(env, state, spi);
3874 if (err)
3875 return err;
3876
0f55f9ed 3877 mark_stack_slot_scratched(env, spi);
354e8f19 3878 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2c78ee89 3879 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
3880 if (dst_reg != BPF_REG_FP) {
3881 /* The backtracking logic can only recognize explicit
3882 * stack slot address like [fp - 8]. Other spill of
8fb33b60 3883 * scalar via different register has to be conservative.
b5dc0163
AS
3884 * Backtrack from here and mark all registers as precise
3885 * that contributed into 'reg' being a constant.
3886 */
3887 err = mark_chain_precision(env, value_regno);
3888 if (err)
3889 return err;
3890 }
354e8f19 3891 save_register_state(state, spi, reg, size);
ecdf985d
EZ
3892 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3893 insn->imm != 0 && env->bpf_capable) {
3894 struct bpf_reg_state fake_reg = {};
3895
3896 __mark_reg_known(&fake_reg, (u32)insn->imm);
3897 fake_reg.type = SCALAR_VALUE;
3898 save_register_state(state, spi, &fake_reg, size);
f7cf25b2 3899 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 3900 /* register containing pointer is being spilled into stack */
9c399760 3901 if (size != BPF_REG_SIZE) {
f7cf25b2 3902 verbose_linfo(env, insn_idx, "; ");
61bd5218 3903 verbose(env, "invalid size of register spill\n");
17a52670
AS
3904 return -EACCES;
3905 }
f7cf25b2 3906 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
3907 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3908 return -EINVAL;
3909 }
354e8f19 3910 save_register_state(state, spi, reg, size);
9c399760 3911 } else {
cc2b14d5
AS
3912 u8 type = STACK_MISC;
3913
679c782d
EC
3914 /* regular write of data into stack destroys any spilled ptr */
3915 state->stack[spi].spilled_ptr.type = NOT_INIT;
06accc87
AN
3916 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3917 if (is_stack_slot_special(&state->stack[spi]))
0bae2d4d 3918 for (i = 0; i < BPF_REG_SIZE; i++)
354e8f19 3919 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
9c399760 3920
cc2b14d5
AS
3921 /* only mark the slot as written if all 8 bytes were written
3922 * otherwise read propagation may incorrectly stop too soon
3923 * when stack slots are partially written.
3924 * This heuristic means that read propagation will be
3925 * conservative, since it will add reg_live_read marks
3926 * to stack slots all the way to first state when programs
3927 * writes+reads less than 8 bytes
3928 */
3929 if (size == BPF_REG_SIZE)
3930 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3931
3932 /* when we zero initialize stack slots mark them as such */
ecdf985d
EZ
3933 if ((reg && register_is_null(reg)) ||
3934 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
b5dc0163
AS
3935 /* backtracking doesn't work for STACK_ZERO yet. */
3936 err = mark_chain_precision(env, value_regno);
3937 if (err)
3938 return err;
cc2b14d5 3939 type = STACK_ZERO;
b5dc0163 3940 }
cc2b14d5 3941
0bae2d4d 3942 /* Mark slots affected by this stack write. */
9c399760 3943 for (i = 0; i < size; i++)
638f5b90 3944 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 3945 type;
17a52670
AS
3946 }
3947 return 0;
3948}
3949
01f810ac
AM
3950/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3951 * known to contain a variable offset.
3952 * This function checks whether the write is permitted and conservatively
3953 * tracks the effects of the write, considering that each stack slot in the
3954 * dynamic range is potentially written to.
3955 *
3956 * 'off' includes 'regno->off'.
3957 * 'value_regno' can be -1, meaning that an unknown value is being written to
3958 * the stack.
3959 *
3960 * Spilled pointers in range are not marked as written because we don't know
3961 * what's going to be actually written. This means that read propagation for
3962 * future reads cannot be terminated by this write.
3963 *
3964 * For privileged programs, uninitialized stack slots are considered
3965 * initialized by this write (even though we don't know exactly what offsets
3966 * are going to be written to). The idea is that we don't want the verifier to
3967 * reject future reads that access slots written to through variable offsets.
3968 */
3969static int check_stack_write_var_off(struct bpf_verifier_env *env,
3970 /* func where register points to */
3971 struct bpf_func_state *state,
3972 int ptr_regno, int off, int size,
3973 int value_regno, int insn_idx)
3974{
3975 struct bpf_func_state *cur; /* state of the current function */
3976 int min_off, max_off;
3977 int i, err;
3978 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
31ff2135 3979 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
01f810ac
AM
3980 bool writing_zero = false;
3981 /* set if the fact that we're writing a zero is used to let any
3982 * stack slots remain STACK_ZERO
3983 */
3984 bool zero_used = false;
3985
3986 cur = env->cur_state->frame[env->cur_state->curframe];
3987 ptr_reg = &cur->regs[ptr_regno];
3988 min_off = ptr_reg->smin_value + off;
3989 max_off = ptr_reg->smax_value + off + size;
3990 if (value_regno >= 0)
3991 value_reg = &cur->regs[value_regno];
31ff2135
EZ
3992 if ((value_reg && register_is_null(value_reg)) ||
3993 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
01f810ac
AM
3994 writing_zero = true;
3995
c69431aa 3996 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
3997 if (err)
3998 return err;
3999
ef8fc7a0
KKD
4000 for (i = min_off; i < max_off; i++) {
4001 int spi;
4002
4003 spi = __get_spi(i);
4004 err = destroy_if_dynptr_stack_slot(env, state, spi);
4005 if (err)
4006 return err;
4007 }
01f810ac
AM
4008
4009 /* Variable offset writes destroy any spilled pointers in range. */
4010 for (i = min_off; i < max_off; i++) {
4011 u8 new_type, *stype;
4012 int slot, spi;
4013
4014 slot = -i - 1;
4015 spi = slot / BPF_REG_SIZE;
4016 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
0f55f9ed 4017 mark_stack_slot_scratched(env, spi);
01f810ac 4018
f5e477a8
KKD
4019 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4020 /* Reject the write if range we may write to has not
4021 * been initialized beforehand. If we didn't reject
4022 * here, the ptr status would be erased below (even
4023 * though not all slots are actually overwritten),
4024 * possibly opening the door to leaks.
4025 *
4026 * We do however catch STACK_INVALID case below, and
4027 * only allow reading possibly uninitialized memory
4028 * later for CAP_PERFMON, as the write may not happen to
4029 * that slot.
01f810ac
AM
4030 */
4031 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4032 insn_idx, i);
4033 return -EINVAL;
4034 }
4035
4036 /* Erase all spilled pointers. */
4037 state->stack[spi].spilled_ptr.type = NOT_INIT;
4038
4039 /* Update the slot type. */
4040 new_type = STACK_MISC;
4041 if (writing_zero && *stype == STACK_ZERO) {
4042 new_type = STACK_ZERO;
4043 zero_used = true;
4044 }
4045 /* If the slot is STACK_INVALID, we check whether it's OK to
4046 * pretend that it will be initialized by this write. The slot
4047 * might not actually be written to, and so if we mark it as
4048 * initialized future reads might leak uninitialized memory.
4049 * For privileged programs, we will accept such reads to slots
4050 * that may or may not be written because, if we're reject
4051 * them, the error would be too confusing.
4052 */
4053 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4054 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4055 insn_idx, i);
4056 return -EINVAL;
4057 }
4058 *stype = new_type;
4059 }
4060 if (zero_used) {
4061 /* backtracking doesn't work for STACK_ZERO yet. */
4062 err = mark_chain_precision(env, value_regno);
4063 if (err)
4064 return err;
4065 }
4066 return 0;
4067}
4068
4069/* When register 'dst_regno' is assigned some values from stack[min_off,
4070 * max_off), we set the register's type according to the types of the
4071 * respective stack slots. If all the stack values are known to be zeros, then
4072 * so is the destination reg. Otherwise, the register is considered to be
4073 * SCALAR. This function does not deal with register filling; the caller must
4074 * ensure that all spilled registers in the stack range have been marked as
4075 * read.
4076 */
4077static void mark_reg_stack_read(struct bpf_verifier_env *env,
4078 /* func where src register points to */
4079 struct bpf_func_state *ptr_state,
4080 int min_off, int max_off, int dst_regno)
4081{
4082 struct bpf_verifier_state *vstate = env->cur_state;
4083 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4084 int i, slot, spi;
4085 u8 *stype;
4086 int zeros = 0;
4087
4088 for (i = min_off; i < max_off; i++) {
4089 slot = -i - 1;
4090 spi = slot / BPF_REG_SIZE;
4091 stype = ptr_state->stack[spi].slot_type;
4092 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4093 break;
4094 zeros++;
4095 }
4096 if (zeros == max_off - min_off) {
4097 /* any access_size read into register is zero extended,
4098 * so the whole register == const_zero
4099 */
4100 __mark_reg_const_zero(&state->regs[dst_regno]);
4101 /* backtracking doesn't support STACK_ZERO yet,
4102 * so mark it precise here, so that later
4103 * backtracking can stop here.
4104 * Backtracking may not need this if this register
4105 * doesn't participate in pointer adjustment.
4106 * Forward propagation of precise flag is not
4107 * necessary either. This mark is only to stop
4108 * backtracking. Any register that contributed
4109 * to const 0 was marked precise before spill.
4110 */
4111 state->regs[dst_regno].precise = true;
4112 } else {
4113 /* have read misc data from the stack */
4114 mark_reg_unknown(env, state->regs, dst_regno);
4115 }
4116 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4117}
4118
4119/* Read the stack at 'off' and put the results into the register indicated by
4120 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4121 * spilled reg.
4122 *
4123 * 'dst_regno' can be -1, meaning that the read value is not going to a
4124 * register.
4125 *
4126 * The access is assumed to be within the current stack bounds.
4127 */
4128static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4129 /* func where src register points to */
4130 struct bpf_func_state *reg_state,
4131 int off, int size, int dst_regno)
17a52670 4132{
f4d7e40a
AS
4133 struct bpf_verifier_state *vstate = env->cur_state;
4134 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 4135 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 4136 struct bpf_reg_state *reg;
354e8f19 4137 u8 *stype, type;
17a52670 4138
f4d7e40a 4139 stype = reg_state->stack[spi].slot_type;
f7cf25b2 4140 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 4141
27113c59 4142 if (is_spilled_reg(&reg_state->stack[spi])) {
f30d4968
MKL
4143 u8 spill_size = 1;
4144
4145 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4146 spill_size++;
354e8f19 4147
f30d4968 4148 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
f7cf25b2
AS
4149 if (reg->type != SCALAR_VALUE) {
4150 verbose_linfo(env, env->insn_idx, "; ");
4151 verbose(env, "invalid size of register fill\n");
4152 return -EACCES;
4153 }
354e8f19
MKL
4154
4155 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4156 if (dst_regno < 0)
4157 return 0;
4158
f30d4968 4159 if (!(off % BPF_REG_SIZE) && size == spill_size) {
354e8f19
MKL
4160 /* The earlier check_reg_arg() has decided the
4161 * subreg_def for this insn. Save it first.
4162 */
4163 s32 subreg_def = state->regs[dst_regno].subreg_def;
4164
71f656a5 4165 copy_register_state(&state->regs[dst_regno], reg);
354e8f19
MKL
4166 state->regs[dst_regno].subreg_def = subreg_def;
4167 } else {
4168 for (i = 0; i < size; i++) {
4169 type = stype[(slot - i) % BPF_REG_SIZE];
4170 if (type == STACK_SPILL)
4171 continue;
4172 if (type == STACK_MISC)
4173 continue;
6715df8d
EZ
4174 if (type == STACK_INVALID && env->allow_uninit_stack)
4175 continue;
354e8f19
MKL
4176 verbose(env, "invalid read from stack off %d+%d size %d\n",
4177 off, i, size);
4178 return -EACCES;
4179 }
01f810ac 4180 mark_reg_unknown(env, state->regs, dst_regno);
f7cf25b2 4181 }
354e8f19 4182 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2 4183 return 0;
17a52670 4184 }
17a52670 4185
01f810ac 4186 if (dst_regno >= 0) {
17a52670 4187 /* restore register state from stack */
71f656a5 4188 copy_register_state(&state->regs[dst_regno], reg);
2f18f62e
AS
4189 /* mark reg as written since spilled pointer state likely
4190 * has its liveness marks cleared by is_state_visited()
4191 * which resets stack/reg liveness for state transitions
4192 */
01f810ac 4193 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 4194 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 4195 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
4196 * it is acceptable to use this value as a SCALAR_VALUE
4197 * (e.g. for XADD).
4198 * We must not allow unprivileged callers to do that
4199 * with spilled pointers.
4200 */
4201 verbose(env, "leaking pointer from stack off %d\n",
4202 off);
4203 return -EACCES;
dc503a8a 4204 }
f7cf25b2 4205 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670
AS
4206 } else {
4207 for (i = 0; i < size; i++) {
01f810ac
AM
4208 type = stype[(slot - i) % BPF_REG_SIZE];
4209 if (type == STACK_MISC)
cc2b14d5 4210 continue;
01f810ac 4211 if (type == STACK_ZERO)
cc2b14d5 4212 continue;
6715df8d
EZ
4213 if (type == STACK_INVALID && env->allow_uninit_stack)
4214 continue;
cc2b14d5
AS
4215 verbose(env, "invalid read from stack off %d+%d size %d\n",
4216 off, i, size);
4217 return -EACCES;
4218 }
f7cf25b2 4219 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
4220 if (dst_regno >= 0)
4221 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 4222 }
f7cf25b2 4223 return 0;
17a52670
AS
4224}
4225
61df10c7 4226enum bpf_access_src {
01f810ac
AM
4227 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4228 ACCESS_HELPER = 2, /* the access is performed by a helper */
4229};
4230
4231static int check_stack_range_initialized(struct bpf_verifier_env *env,
4232 int regno, int off, int access_size,
4233 bool zero_size_allowed,
61df10c7 4234 enum bpf_access_src type,
01f810ac
AM
4235 struct bpf_call_arg_meta *meta);
4236
4237static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4238{
4239 return cur_regs(env) + regno;
4240}
4241
4242/* Read the stack at 'ptr_regno + off' and put the result into the register
4243 * 'dst_regno'.
4244 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4245 * but not its variable offset.
4246 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4247 *
4248 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4249 * filling registers (i.e. reads of spilled register cannot be detected when
4250 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4251 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4252 * offset; for a fixed offset check_stack_read_fixed_off should be used
4253 * instead.
4254 */
4255static int check_stack_read_var_off(struct bpf_verifier_env *env,
4256 int ptr_regno, int off, int size, int dst_regno)
e4298d25 4257{
01f810ac
AM
4258 /* The state of the source register. */
4259 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4260 struct bpf_func_state *ptr_state = func(env, reg);
4261 int err;
4262 int min_off, max_off;
4263
4264 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 4265 */
01f810ac
AM
4266 err = check_stack_range_initialized(env, ptr_regno, off, size,
4267 false, ACCESS_DIRECT, NULL);
4268 if (err)
4269 return err;
4270
4271 min_off = reg->smin_value + off;
4272 max_off = reg->smax_value + off;
4273 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4274 return 0;
4275}
4276
4277/* check_stack_read dispatches to check_stack_read_fixed_off or
4278 * check_stack_read_var_off.
4279 *
4280 * The caller must ensure that the offset falls within the allocated stack
4281 * bounds.
4282 *
4283 * 'dst_regno' is a register which will receive the value from the stack. It
4284 * can be -1, meaning that the read value is not going to a register.
4285 */
4286static int check_stack_read(struct bpf_verifier_env *env,
4287 int ptr_regno, int off, int size,
4288 int dst_regno)
4289{
4290 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4291 struct bpf_func_state *state = func(env, reg);
4292 int err;
4293 /* Some accesses are only permitted with a static offset. */
4294 bool var_off = !tnum_is_const(reg->var_off);
4295
4296 /* The offset is required to be static when reads don't go to a
4297 * register, in order to not leak pointers (see
4298 * check_stack_read_fixed_off).
4299 */
4300 if (dst_regno < 0 && var_off) {
e4298d25
DB
4301 char tn_buf[48];
4302
4303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 4304 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
4305 tn_buf, off, size);
4306 return -EACCES;
4307 }
01f810ac
AM
4308 /* Variable offset is prohibited for unprivileged mode for simplicity
4309 * since it requires corresponding support in Spectre masking for stack
082cdc69
LG
4310 * ALU. See also retrieve_ptr_limit(). The check in
4311 * check_stack_access_for_ptr_arithmetic() called by
4312 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4313 * with variable offsets, therefore no check is required here. Further,
4314 * just checking it here would be insufficient as speculative stack
4315 * writes could still lead to unsafe speculative behaviour.
01f810ac 4316 */
01f810ac
AM
4317 if (!var_off) {
4318 off += reg->var_off.value;
4319 err = check_stack_read_fixed_off(env, state, off, size,
4320 dst_regno);
4321 } else {
4322 /* Variable offset stack reads need more conservative handling
4323 * than fixed offset ones. Note that dst_regno >= 0 on this
4324 * branch.
4325 */
4326 err = check_stack_read_var_off(env, ptr_regno, off, size,
4327 dst_regno);
4328 }
4329 return err;
4330}
4331
4332
4333/* check_stack_write dispatches to check_stack_write_fixed_off or
4334 * check_stack_write_var_off.
4335 *
4336 * 'ptr_regno' is the register used as a pointer into the stack.
4337 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4338 * 'value_regno' is the register whose value we're writing to the stack. It can
4339 * be -1, meaning that we're not writing from a register.
4340 *
4341 * The caller must ensure that the offset falls within the maximum stack size.
4342 */
4343static int check_stack_write(struct bpf_verifier_env *env,
4344 int ptr_regno, int off, int size,
4345 int value_regno, int insn_idx)
4346{
4347 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4348 struct bpf_func_state *state = func(env, reg);
4349 int err;
4350
4351 if (tnum_is_const(reg->var_off)) {
4352 off += reg->var_off.value;
4353 err = check_stack_write_fixed_off(env, state, off, size,
4354 value_regno, insn_idx);
4355 } else {
4356 /* Variable offset stack reads need more conservative handling
4357 * than fixed offset ones.
4358 */
4359 err = check_stack_write_var_off(env, state,
4360 ptr_regno, off, size,
4361 value_regno, insn_idx);
4362 }
4363 return err;
e4298d25
DB
4364}
4365
591fe988
DB
4366static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4367 int off, int size, enum bpf_access_type type)
4368{
4369 struct bpf_reg_state *regs = cur_regs(env);
4370 struct bpf_map *map = regs[regno].map_ptr;
4371 u32 cap = bpf_map_flags_to_cap(map);
4372
4373 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4374 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4375 map->value_size, off, size);
4376 return -EACCES;
4377 }
4378
4379 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4380 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4381 map->value_size, off, size);
4382 return -EACCES;
4383 }
4384
4385 return 0;
4386}
4387
457f4436
AN
4388/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4389static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4390 int off, int size, u32 mem_size,
4391 bool zero_size_allowed)
17a52670 4392{
457f4436
AN
4393 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4394 struct bpf_reg_state *reg;
4395
4396 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4397 return 0;
17a52670 4398
457f4436
AN
4399 reg = &cur_regs(env)[regno];
4400 switch (reg->type) {
69c087ba
YS
4401 case PTR_TO_MAP_KEY:
4402 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4403 mem_size, off, size);
4404 break;
457f4436 4405 case PTR_TO_MAP_VALUE:
61bd5218 4406 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
4407 mem_size, off, size);
4408 break;
4409 case PTR_TO_PACKET:
4410 case PTR_TO_PACKET_META:
4411 case PTR_TO_PACKET_END:
4412 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4413 off, size, regno, reg->id, off, mem_size);
4414 break;
4415 case PTR_TO_MEM:
4416 default:
4417 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4418 mem_size, off, size);
17a52670 4419 }
457f4436
AN
4420
4421 return -EACCES;
17a52670
AS
4422}
4423
457f4436
AN
4424/* check read/write into a memory region with possible variable offset */
4425static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4426 int off, int size, u32 mem_size,
4427 bool zero_size_allowed)
dbcfe5f7 4428{
f4d7e40a
AS
4429 struct bpf_verifier_state *vstate = env->cur_state;
4430 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
4431 struct bpf_reg_state *reg = &state->regs[regno];
4432 int err;
4433
457f4436 4434 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
4435 * need to try adding each of min_value and max_value to off
4436 * to make sure our theoretical access will be safe.
2e576648
CL
4437 *
4438 * The minimum value is only important with signed
dbcfe5f7
GB
4439 * comparisons where we can't assume the floor of a
4440 * value is 0. If we are using signed variables for our
4441 * index'es we need to make sure that whatever we use
4442 * will have a set floor within our range.
4443 */
b7137c4e
DB
4444 if (reg->smin_value < 0 &&
4445 (reg->smin_value == S64_MIN ||
4446 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4447 reg->smin_value + off < 0)) {
61bd5218 4448 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
4449 regno);
4450 return -EACCES;
4451 }
457f4436
AN
4452 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4453 mem_size, zero_size_allowed);
dbcfe5f7 4454 if (err) {
457f4436 4455 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 4456 regno);
dbcfe5f7
GB
4457 return err;
4458 }
4459
b03c9f9f
EC
4460 /* If we haven't set a max value then we need to bail since we can't be
4461 * sure we won't do bad things.
4462 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 4463 */
b03c9f9f 4464 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 4465 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
4466 regno);
4467 return -EACCES;
4468 }
457f4436
AN
4469 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4470 mem_size, zero_size_allowed);
4471 if (err) {
4472 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 4473 regno);
457f4436
AN
4474 return err;
4475 }
4476
4477 return 0;
4478}
d83525ca 4479
e9147b44
KKD
4480static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4481 const struct bpf_reg_state *reg, int regno,
4482 bool fixed_off_ok)
4483{
4484 /* Access to this pointer-typed register or passing it to a helper
4485 * is only allowed in its original, unmodified form.
4486 */
4487
4488 if (reg->off < 0) {
4489 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4490 reg_type_str(env, reg->type), regno, reg->off);
4491 return -EACCES;
4492 }
4493
4494 if (!fixed_off_ok && reg->off) {
4495 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4496 reg_type_str(env, reg->type), regno, reg->off);
4497 return -EACCES;
4498 }
4499
4500 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4501 char tn_buf[48];
4502
4503 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4504 verbose(env, "variable %s access var_off=%s disallowed\n",
4505 reg_type_str(env, reg->type), tn_buf);
4506 return -EACCES;
4507 }
4508
4509 return 0;
4510}
4511
4512int check_ptr_off_reg(struct bpf_verifier_env *env,
4513 const struct bpf_reg_state *reg, int regno)
4514{
4515 return __check_ptr_off_reg(env, reg, regno, false);
4516}
4517
61df10c7 4518static int map_kptr_match_type(struct bpf_verifier_env *env,
aa3496ac 4519 struct btf_field *kptr_field,
61df10c7
KKD
4520 struct bpf_reg_state *reg, u32 regno)
4521{
b32a5dae 4522 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
20c09d92 4523 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
61df10c7
KKD
4524 const char *reg_name = "";
4525
6efe152d 4526 /* Only unreferenced case accepts untrusted pointers */
aa3496ac 4527 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
4528 perm_flags |= PTR_UNTRUSTED;
4529
4530 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
61df10c7
KKD
4531 goto bad_type;
4532
4533 if (!btf_is_kernel(reg->btf)) {
4534 verbose(env, "R%d must point to kernel BTF\n", regno);
4535 return -EINVAL;
4536 }
4537 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
b32a5dae 4538 reg_name = btf_type_name(reg->btf, reg->btf_id);
61df10c7 4539
c0a5a21c
KKD
4540 /* For ref_ptr case, release function check should ensure we get one
4541 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4542 * normal store of unreferenced kptr, we must ensure var_off is zero.
4543 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4544 * reg->off and reg->ref_obj_id are not needed here.
4545 */
61df10c7
KKD
4546 if (__check_ptr_off_reg(env, reg, regno, true))
4547 return -EACCES;
4548
4549 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
4550 * we also need to take into account the reg->off.
4551 *
4552 * We want to support cases like:
4553 *
4554 * struct foo {
4555 * struct bar br;
4556 * struct baz bz;
4557 * };
4558 *
4559 * struct foo *v;
4560 * v = func(); // PTR_TO_BTF_ID
4561 * val->foo = v; // reg->off is zero, btf and btf_id match type
4562 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4563 * // first member type of struct after comparison fails
4564 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4565 * // to match type
4566 *
4567 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
2ab3b380
KKD
4568 * is zero. We must also ensure that btf_struct_ids_match does not walk
4569 * the struct to match type against first member of struct, i.e. reject
4570 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4571 * strict mode to true for type match.
61df10c7
KKD
4572 */
4573 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
aa3496ac
KKD
4574 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4575 kptr_field->type == BPF_KPTR_REF))
61df10c7
KKD
4576 goto bad_type;
4577 return 0;
4578bad_type:
4579 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4580 reg_type_str(env, reg->type), reg_name);
6efe152d 4581 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
aa3496ac 4582 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
4583 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4584 targ_name);
4585 else
4586 verbose(env, "\n");
61df10c7
KKD
4587 return -EINVAL;
4588}
4589
20c09d92
AS
4590/* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4591 * can dereference RCU protected pointers and result is PTR_TRUSTED.
4592 */
4593static bool in_rcu_cs(struct bpf_verifier_env *env)
4594{
4595 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4596}
4597
4598/* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4599BTF_SET_START(rcu_protected_types)
4600BTF_ID(struct, prog_test_ref_kfunc)
4601BTF_ID(struct, cgroup)
63d2d83d 4602BTF_ID(struct, bpf_cpumask)
d02c48fa 4603BTF_ID(struct, task_struct)
20c09d92
AS
4604BTF_SET_END(rcu_protected_types)
4605
4606static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4607{
4608 if (!btf_is_kernel(btf))
4609 return false;
4610 return btf_id_set_contains(&rcu_protected_types, btf_id);
4611}
4612
4613static bool rcu_safe_kptr(const struct btf_field *field)
4614{
4615 const struct btf_field_kptr *kptr = &field->kptr;
4616
4617 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4618}
4619
61df10c7
KKD
4620static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4621 int value_regno, int insn_idx,
aa3496ac 4622 struct btf_field *kptr_field)
61df10c7
KKD
4623{
4624 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4625 int class = BPF_CLASS(insn->code);
4626 struct bpf_reg_state *val_reg;
4627
4628 /* Things we already checked for in check_map_access and caller:
4629 * - Reject cases where variable offset may touch kptr
4630 * - size of access (must be BPF_DW)
4631 * - tnum_is_const(reg->var_off)
aa3496ac 4632 * - kptr_field->offset == off + reg->var_off.value
61df10c7
KKD
4633 */
4634 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4635 if (BPF_MODE(insn->code) != BPF_MEM) {
4636 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4637 return -EACCES;
4638 }
4639
6efe152d
KKD
4640 /* We only allow loading referenced kptr, since it will be marked as
4641 * untrusted, similar to unreferenced kptr.
4642 */
aa3496ac 4643 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
6efe152d 4644 verbose(env, "store to referenced kptr disallowed\n");
c0a5a21c
KKD
4645 return -EACCES;
4646 }
4647
61df10c7
KKD
4648 if (class == BPF_LDX) {
4649 val_reg = reg_state(env, value_regno);
4650 /* We can simply mark the value_regno receiving the pointer
4651 * value from map as PTR_TO_BTF_ID, with the correct type.
4652 */
aa3496ac 4653 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
20c09d92
AS
4654 kptr_field->kptr.btf_id,
4655 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4656 PTR_MAYBE_NULL | MEM_RCU :
4657 PTR_MAYBE_NULL | PTR_UNTRUSTED);
61df10c7
KKD
4658 /* For mark_ptr_or_null_reg */
4659 val_reg->id = ++env->id_gen;
4660 } else if (class == BPF_STX) {
4661 val_reg = reg_state(env, value_regno);
4662 if (!register_is_null(val_reg) &&
aa3496ac 4663 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
61df10c7
KKD
4664 return -EACCES;
4665 } else if (class == BPF_ST) {
4666 if (insn->imm) {
4667 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
aa3496ac 4668 kptr_field->offset);
61df10c7
KKD
4669 return -EACCES;
4670 }
4671 } else {
4672 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4673 return -EACCES;
4674 }
4675 return 0;
4676}
4677
457f4436
AN
4678/* check read/write into a map element with possible variable offset */
4679static int check_map_access(struct bpf_verifier_env *env, u32 regno,
61df10c7
KKD
4680 int off, int size, bool zero_size_allowed,
4681 enum bpf_access_src src)
457f4436
AN
4682{
4683 struct bpf_verifier_state *vstate = env->cur_state;
4684 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4685 struct bpf_reg_state *reg = &state->regs[regno];
4686 struct bpf_map *map = reg->map_ptr;
aa3496ac
KKD
4687 struct btf_record *rec;
4688 int err, i;
457f4436
AN
4689
4690 err = check_mem_region_access(env, regno, off, size, map->value_size,
4691 zero_size_allowed);
4692 if (err)
4693 return err;
4694
aa3496ac
KKD
4695 if (IS_ERR_OR_NULL(map->record))
4696 return 0;
4697 rec = map->record;
4698 for (i = 0; i < rec->cnt; i++) {
4699 struct btf_field *field = &rec->fields[i];
4700 u32 p = field->offset;
d83525ca 4701
db559117
KKD
4702 /* If any part of a field can be touched by load/store, reject
4703 * this program. To check that [x1, x2) overlaps with [y1, y2),
d83525ca
AS
4704 * it is sufficient to check x1 < y2 && y1 < x2.
4705 */
aa3496ac
KKD
4706 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4707 p < reg->umax_value + off + size) {
4708 switch (field->type) {
4709 case BPF_KPTR_UNREF:
4710 case BPF_KPTR_REF:
61df10c7
KKD
4711 if (src != ACCESS_DIRECT) {
4712 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4713 return -EACCES;
4714 }
4715 if (!tnum_is_const(reg->var_off)) {
4716 verbose(env, "kptr access cannot have variable offset\n");
4717 return -EACCES;
4718 }
4719 if (p != off + reg->var_off.value) {
4720 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4721 p, off + reg->var_off.value);
4722 return -EACCES;
4723 }
4724 if (size != bpf_size_to_bytes(BPF_DW)) {
4725 verbose(env, "kptr access size must be BPF_DW\n");
4726 return -EACCES;
4727 }
4728 break;
aa3496ac 4729 default:
db559117
KKD
4730 verbose(env, "%s cannot be accessed directly by load/store\n",
4731 btf_field_type_name(field->type));
aa3496ac 4732 return -EACCES;
61df10c7
KKD
4733 }
4734 }
4735 }
aa3496ac 4736 return 0;
dbcfe5f7
GB
4737}
4738
969bf05e
AS
4739#define MAX_PACKET_OFF 0xffff
4740
58e2af8b 4741static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
4742 const struct bpf_call_arg_meta *meta,
4743 enum bpf_access_type t)
4acf6c0b 4744{
7e40781c
UP
4745 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4746
4747 switch (prog_type) {
5d66fa7d 4748 /* Program types only with direct read access go here! */
3a0af8fd
TG
4749 case BPF_PROG_TYPE_LWT_IN:
4750 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 4751 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 4752 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 4753 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 4754 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
4755 if (t == BPF_WRITE)
4756 return false;
8731745e 4757 fallthrough;
5d66fa7d
DB
4758
4759 /* Program types with direct read + write access go here! */
36bbef52
DB
4760 case BPF_PROG_TYPE_SCHED_CLS:
4761 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 4762 case BPF_PROG_TYPE_XDP:
3a0af8fd 4763 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 4764 case BPF_PROG_TYPE_SK_SKB:
4f738adb 4765 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
4766 if (meta)
4767 return meta->pkt_access;
4768
4769 env->seen_direct_write = true;
4acf6c0b 4770 return true;
0d01da6a
SF
4771
4772 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4773 if (t == BPF_WRITE)
4774 env->seen_direct_write = true;
4775
4776 return true;
4777
4acf6c0b
BB
4778 default:
4779 return false;
4780 }
4781}
4782
f1174f77 4783static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 4784 int size, bool zero_size_allowed)
f1174f77 4785{
638f5b90 4786 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
4787 struct bpf_reg_state *reg = &regs[regno];
4788 int err;
4789
4790 /* We may have added a variable offset to the packet pointer; but any
4791 * reg->range we have comes after that. We are only checking the fixed
4792 * offset.
4793 */
4794
4795 /* We don't allow negative numbers, because we aren't tracking enough
4796 * detail to prove they're safe.
4797 */
b03c9f9f 4798 if (reg->smin_value < 0) {
61bd5218 4799 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
4800 regno);
4801 return -EACCES;
4802 }
6d94e741
AS
4803
4804 err = reg->range < 0 ? -EINVAL :
4805 __check_mem_access(env, regno, off, size, reg->range,
457f4436 4806 zero_size_allowed);
f1174f77 4807 if (err) {
61bd5218 4808 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
4809 return err;
4810 }
e647815a 4811
457f4436 4812 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
4813 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4814 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 4815 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
4816 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4817 */
4818 env->prog->aux->max_pkt_offset =
4819 max_t(u32, env->prog->aux->max_pkt_offset,
4820 off + reg->umax_value + size - 1);
4821
f1174f77
EC
4822 return err;
4823}
4824
4825/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 4826static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 4827 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 4828 struct btf **btf, u32 *btf_id)
17a52670 4829{
f96da094
DB
4830 struct bpf_insn_access_aux info = {
4831 .reg_type = *reg_type,
9e15db66 4832 .log = &env->log,
f96da094 4833 };
31fd8581 4834
4f9218aa 4835 if (env->ops->is_valid_access &&
5e43f899 4836 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
4837 /* A non zero info.ctx_field_size indicates that this field is a
4838 * candidate for later verifier transformation to load the whole
4839 * field and then apply a mask when accessed with a narrower
4840 * access than actual ctx access size. A zero info.ctx_field_size
4841 * will only allow for whole field access and rejects any other
4842 * type of narrower access.
31fd8581 4843 */
23994631 4844 *reg_type = info.reg_type;
31fd8581 4845
c25b2ae1 4846 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 4847 *btf = info.btf;
9e15db66 4848 *btf_id = info.btf_id;
22dc4a0f 4849 } else {
9e15db66 4850 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 4851 }
32bbe007
AS
4852 /* remember the offset of last byte accessed in ctx */
4853 if (env->prog->aux->max_ctx_offset < off + size)
4854 env->prog->aux->max_ctx_offset = off + size;
17a52670 4855 return 0;
32bbe007 4856 }
17a52670 4857
61bd5218 4858 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
4859 return -EACCES;
4860}
4861
d58e468b
PP
4862static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4863 int size)
4864{
4865 if (size < 0 || off < 0 ||
4866 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4867 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4868 off, size);
4869 return -EACCES;
4870 }
4871 return 0;
4872}
4873
5f456649
MKL
4874static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4875 u32 regno, int off, int size,
4876 enum bpf_access_type t)
c64b7983
JS
4877{
4878 struct bpf_reg_state *regs = cur_regs(env);
4879 struct bpf_reg_state *reg = &regs[regno];
5f456649 4880 struct bpf_insn_access_aux info = {};
46f8bc92 4881 bool valid;
c64b7983
JS
4882
4883 if (reg->smin_value < 0) {
4884 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4885 regno);
4886 return -EACCES;
4887 }
4888
46f8bc92
MKL
4889 switch (reg->type) {
4890 case PTR_TO_SOCK_COMMON:
4891 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4892 break;
4893 case PTR_TO_SOCKET:
4894 valid = bpf_sock_is_valid_access(off, size, t, &info);
4895 break;
655a51e5
MKL
4896 case PTR_TO_TCP_SOCK:
4897 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4898 break;
fada7fdc
JL
4899 case PTR_TO_XDP_SOCK:
4900 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4901 break;
46f8bc92
MKL
4902 default:
4903 valid = false;
c64b7983
JS
4904 }
4905
5f456649 4906
46f8bc92
MKL
4907 if (valid) {
4908 env->insn_aux_data[insn_idx].ctx_field_size =
4909 info.ctx_field_size;
4910 return 0;
4911 }
4912
4913 verbose(env, "R%d invalid %s access off=%d size=%d\n",
c25b2ae1 4914 regno, reg_type_str(env, reg->type), off, size);
46f8bc92
MKL
4915
4916 return -EACCES;
c64b7983
JS
4917}
4918
4cabc5b1
DB
4919static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4920{
2a159c6f 4921 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
4922}
4923
f37a8cb8
DB
4924static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4925{
2a159c6f 4926 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 4927
46f8bc92
MKL
4928 return reg->type == PTR_TO_CTX;
4929}
4930
4931static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4932{
4933 const struct bpf_reg_state *reg = reg_state(env, regno);
4934
4935 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
4936}
4937
ca369602
DB
4938static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4939{
2a159c6f 4940 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
4941
4942 return type_is_pkt_pointer(reg->type);
4943}
4944
4b5defde
DB
4945static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4946{
4947 const struct bpf_reg_state *reg = reg_state(env, regno);
4948
4949 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4950 return reg->type == PTR_TO_FLOW_KEYS;
4951}
4952
9bb00b28
YS
4953static bool is_trusted_reg(const struct bpf_reg_state *reg)
4954{
4955 /* A referenced register is always trusted. */
4956 if (reg->ref_obj_id)
4957 return true;
4958
4959 /* If a register is not referenced, it is trusted if it has the
fca1aa75 4960 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
9bb00b28
YS
4961 * other type modifiers may be safe, but we elect to take an opt-in
4962 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4963 * not.
4964 *
4965 * Eventually, we should make PTR_TRUSTED the single source of truth
4966 * for whether a register is trusted.
4967 */
4968 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4969 !bpf_type_has_unsafe_modifiers(reg->type);
4970}
4971
fca1aa75
YS
4972static bool is_rcu_reg(const struct bpf_reg_state *reg)
4973{
4974 return reg->type & MEM_RCU;
4975}
4976
61bd5218
JK
4977static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4978 const struct bpf_reg_state *reg,
d1174416 4979 int off, int size, bool strict)
969bf05e 4980{
f1174f77 4981 struct tnum reg_off;
e07b98d9 4982 int ip_align;
d1174416
DM
4983
4984 /* Byte size accesses are always allowed. */
4985 if (!strict || size == 1)
4986 return 0;
4987
e4eda884
DM
4988 /* For platforms that do not have a Kconfig enabling
4989 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4990 * NET_IP_ALIGN is universally set to '2'. And on platforms
4991 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4992 * to this code only in strict mode where we want to emulate
4993 * the NET_IP_ALIGN==2 checking. Therefore use an
4994 * unconditional IP align value of '2'.
e07b98d9 4995 */
e4eda884 4996 ip_align = 2;
f1174f77
EC
4997
4998 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4999 if (!tnum_is_aligned(reg_off, size)) {
5000 char tn_buf[48];
5001
5002 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
5003 verbose(env,
5004 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 5005 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
5006 return -EACCES;
5007 }
79adffcd 5008
969bf05e
AS
5009 return 0;
5010}
5011
61bd5218
JK
5012static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5013 const struct bpf_reg_state *reg,
f1174f77
EC
5014 const char *pointer_desc,
5015 int off, int size, bool strict)
79adffcd 5016{
f1174f77
EC
5017 struct tnum reg_off;
5018
5019 /* Byte size accesses are always allowed. */
5020 if (!strict || size == 1)
5021 return 0;
5022
5023 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5024 if (!tnum_is_aligned(reg_off, size)) {
5025 char tn_buf[48];
5026
5027 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 5028 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 5029 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
5030 return -EACCES;
5031 }
5032
969bf05e
AS
5033 return 0;
5034}
5035
e07b98d9 5036static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
5037 const struct bpf_reg_state *reg, int off,
5038 int size, bool strict_alignment_once)
79adffcd 5039{
ca369602 5040 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 5041 const char *pointer_desc = "";
d1174416 5042
79adffcd
DB
5043 switch (reg->type) {
5044 case PTR_TO_PACKET:
de8f3a83
DB
5045 case PTR_TO_PACKET_META:
5046 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5047 * right in front, treat it the very same way.
5048 */
61bd5218 5049 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
5050 case PTR_TO_FLOW_KEYS:
5051 pointer_desc = "flow keys ";
5052 break;
69c087ba
YS
5053 case PTR_TO_MAP_KEY:
5054 pointer_desc = "key ";
5055 break;
f1174f77
EC
5056 case PTR_TO_MAP_VALUE:
5057 pointer_desc = "value ";
5058 break;
5059 case PTR_TO_CTX:
5060 pointer_desc = "context ";
5061 break;
5062 case PTR_TO_STACK:
5063 pointer_desc = "stack ";
01f810ac
AM
5064 /* The stack spill tracking logic in check_stack_write_fixed_off()
5065 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
5066 * aligned.
5067 */
5068 strict = true;
f1174f77 5069 break;
c64b7983
JS
5070 case PTR_TO_SOCKET:
5071 pointer_desc = "sock ";
5072 break;
46f8bc92
MKL
5073 case PTR_TO_SOCK_COMMON:
5074 pointer_desc = "sock_common ";
5075 break;
655a51e5
MKL
5076 case PTR_TO_TCP_SOCK:
5077 pointer_desc = "tcp_sock ";
5078 break;
fada7fdc
JL
5079 case PTR_TO_XDP_SOCK:
5080 pointer_desc = "xdp_sock ";
5081 break;
79adffcd 5082 default:
f1174f77 5083 break;
79adffcd 5084 }
61bd5218
JK
5085 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5086 strict);
79adffcd
DB
5087}
5088
f4d7e40a
AS
5089static int update_stack_depth(struct bpf_verifier_env *env,
5090 const struct bpf_func_state *func,
5091 int off)
5092{
9c8105bd 5093 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
5094
5095 if (stack >= -off)
5096 return 0;
5097
5098 /* update known max for given subprogram */
9c8105bd 5099 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
5100 return 0;
5101}
f4d7e40a 5102
70a87ffe
AS
5103/* starting from main bpf function walk all instructions of the function
5104 * and recursively walk all callees that given function can call.
5105 * Ignore jump and exit insns.
5106 * Since recursion is prevented by check_cfg() this algorithm
5107 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5108 */
5109static int check_max_stack_depth(struct bpf_verifier_env *env)
5110{
9c8105bd
JW
5111 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5112 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 5113 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 5114 bool tail_call_reachable = false;
70a87ffe
AS
5115 int ret_insn[MAX_CALL_FRAMES];
5116 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 5117 int j;
f4d7e40a 5118
70a87ffe 5119process_func:
7f6e4312
MF
5120 /* protect against potential stack overflow that might happen when
5121 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5122 * depth for such case down to 256 so that the worst case scenario
5123 * would result in 8k stack size (32 which is tailcall limit * 256 =
5124 * 8k).
5125 *
5126 * To get the idea what might happen, see an example:
5127 * func1 -> sub rsp, 128
5128 * subfunc1 -> sub rsp, 256
5129 * tailcall1 -> add rsp, 256
5130 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5131 * subfunc2 -> sub rsp, 64
5132 * subfunc22 -> sub rsp, 128
5133 * tailcall2 -> add rsp, 128
5134 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5135 *
5136 * tailcall will unwind the current stack frame but it will not get rid
5137 * of caller's stack as shown on the example above.
5138 */
5139 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5140 verbose(env,
5141 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5142 depth);
5143 return -EACCES;
5144 }
70a87ffe
AS
5145 /* round up to 32-bytes, since this is granularity
5146 * of interpreter stack size
5147 */
9c8105bd 5148 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 5149 if (depth > MAX_BPF_STACK) {
f4d7e40a 5150 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 5151 frame + 1, depth);
f4d7e40a
AS
5152 return -EACCES;
5153 }
70a87ffe 5154continue_func:
4cb3d99c 5155 subprog_end = subprog[idx + 1].start;
70a87ffe 5156 for (; i < subprog_end; i++) {
7ddc80a4
AS
5157 int next_insn;
5158
69c087ba 5159 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
5160 continue;
5161 /* remember insn and function to return to */
5162 ret_insn[frame] = i + 1;
9c8105bd 5163 ret_prog[frame] = idx;
70a87ffe
AS
5164
5165 /* find the callee */
7ddc80a4
AS
5166 next_insn = i + insn[i].imm + 1;
5167 idx = find_subprog(env, next_insn);
9c8105bd 5168 if (idx < 0) {
70a87ffe 5169 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7ddc80a4 5170 next_insn);
70a87ffe
AS
5171 return -EFAULT;
5172 }
7ddc80a4
AS
5173 if (subprog[idx].is_async_cb) {
5174 if (subprog[idx].has_tail_call) {
5175 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5176 return -EFAULT;
5177 }
5178 /* async callbacks don't increase bpf prog stack size */
5179 continue;
5180 }
5181 i = next_insn;
ebf7d1f5
MF
5182
5183 if (subprog[idx].has_tail_call)
5184 tail_call_reachable = true;
5185
70a87ffe
AS
5186 frame++;
5187 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
5188 verbose(env, "the call stack of %d frames is too deep !\n",
5189 frame);
5190 return -E2BIG;
70a87ffe
AS
5191 }
5192 goto process_func;
5193 }
ebf7d1f5
MF
5194 /* if tail call got detected across bpf2bpf calls then mark each of the
5195 * currently present subprog frames as tail call reachable subprogs;
5196 * this info will be utilized by JIT so that we will be preserving the
5197 * tail call counter throughout bpf2bpf calls combined with tailcalls
5198 */
5199 if (tail_call_reachable)
5200 for (j = 0; j < frame; j++)
5201 subprog[ret_prog[j]].tail_call_reachable = true;
5dd0a6b8
DB
5202 if (subprog[0].tail_call_reachable)
5203 env->prog->aux->tail_call_reachable = true;
ebf7d1f5 5204
70a87ffe
AS
5205 /* end of for() loop means the last insn of the 'subprog'
5206 * was reached. Doesn't matter whether it was JA or EXIT
5207 */
5208 if (frame == 0)
5209 return 0;
9c8105bd 5210 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
5211 frame--;
5212 i = ret_insn[frame];
9c8105bd 5213 idx = ret_prog[frame];
70a87ffe 5214 goto continue_func;
f4d7e40a
AS
5215}
5216
19d28fbd 5217#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
5218static int get_callee_stack_depth(struct bpf_verifier_env *env,
5219 const struct bpf_insn *insn, int idx)
5220{
5221 int start = idx + insn->imm + 1, subprog;
5222
5223 subprog = find_subprog(env, start);
5224 if (subprog < 0) {
5225 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5226 start);
5227 return -EFAULT;
5228 }
9c8105bd 5229 return env->subprog_info[subprog].stack_depth;
1ea47e01 5230}
19d28fbd 5231#endif
1ea47e01 5232
afbf21dc
YS
5233static int __check_buffer_access(struct bpf_verifier_env *env,
5234 const char *buf_info,
5235 const struct bpf_reg_state *reg,
5236 int regno, int off, int size)
9df1c28b
MM
5237{
5238 if (off < 0) {
5239 verbose(env,
4fc00b79 5240 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 5241 regno, buf_info, off, size);
9df1c28b
MM
5242 return -EACCES;
5243 }
5244 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5245 char tn_buf[48];
5246
5247 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5248 verbose(env,
4fc00b79 5249 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
5250 regno, off, tn_buf);
5251 return -EACCES;
5252 }
afbf21dc
YS
5253
5254 return 0;
5255}
5256
5257static int check_tp_buffer_access(struct bpf_verifier_env *env,
5258 const struct bpf_reg_state *reg,
5259 int regno, int off, int size)
5260{
5261 int err;
5262
5263 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5264 if (err)
5265 return err;
5266
9df1c28b
MM
5267 if (off + size > env->prog->aux->max_tp_access)
5268 env->prog->aux->max_tp_access = off + size;
5269
5270 return 0;
5271}
5272
afbf21dc
YS
5273static int check_buffer_access(struct bpf_verifier_env *env,
5274 const struct bpf_reg_state *reg,
5275 int regno, int off, int size,
5276 bool zero_size_allowed,
afbf21dc
YS
5277 u32 *max_access)
5278{
44e9a741 5279 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
afbf21dc
YS
5280 int err;
5281
5282 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5283 if (err)
5284 return err;
5285
5286 if (off + size > *max_access)
5287 *max_access = off + size;
5288
5289 return 0;
5290}
5291
3f50f132
JF
5292/* BPF architecture zero extends alu32 ops into 64-bit registesr */
5293static void zext_32_to_64(struct bpf_reg_state *reg)
5294{
5295 reg->var_off = tnum_subreg(reg->var_off);
5296 __reg_assign_32_into_64(reg);
5297}
9df1c28b 5298
0c17d1d2
JH
5299/* truncate register to smaller size (in bytes)
5300 * must be called with size < BPF_REG_SIZE
5301 */
5302static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5303{
5304 u64 mask;
5305
5306 /* clear high bits in bit representation */
5307 reg->var_off = tnum_cast(reg->var_off, size);
5308
5309 /* fix arithmetic bounds */
5310 mask = ((u64)1 << (size * 8)) - 1;
5311 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5312 reg->umin_value &= mask;
5313 reg->umax_value &= mask;
5314 } else {
5315 reg->umin_value = 0;
5316 reg->umax_value = mask;
5317 }
5318 reg->smin_value = reg->umin_value;
5319 reg->smax_value = reg->umax_value;
3f50f132
JF
5320
5321 /* If size is smaller than 32bit register the 32bit register
5322 * values are also truncated so we push 64-bit bounds into
5323 * 32-bit bounds. Above were truncated < 32-bits already.
5324 */
5325 if (size >= 4)
5326 return;
5327 __reg_combine_64_into_32(reg);
0c17d1d2
JH
5328}
5329
a23740ec
AN
5330static bool bpf_map_is_rdonly(const struct bpf_map *map)
5331{
353050be
DB
5332 /* A map is considered read-only if the following condition are true:
5333 *
5334 * 1) BPF program side cannot change any of the map content. The
5335 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5336 * and was set at map creation time.
5337 * 2) The map value(s) have been initialized from user space by a
5338 * loader and then "frozen", such that no new map update/delete
5339 * operations from syscall side are possible for the rest of
5340 * the map's lifetime from that point onwards.
5341 * 3) Any parallel/pending map update/delete operations from syscall
5342 * side have been completed. Only after that point, it's safe to
5343 * assume that map value(s) are immutable.
5344 */
5345 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5346 READ_ONCE(map->frozen) &&
5347 !bpf_map_write_active(map);
a23740ec
AN
5348}
5349
5350static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5351{
5352 void *ptr;
5353 u64 addr;
5354 int err;
5355
5356 err = map->ops->map_direct_value_addr(map, &addr, off);
5357 if (err)
5358 return err;
2dedd7d2 5359 ptr = (void *)(long)addr + off;
a23740ec
AN
5360
5361 switch (size) {
5362 case sizeof(u8):
5363 *val = (u64)*(u8 *)ptr;
5364 break;
5365 case sizeof(u16):
5366 *val = (u64)*(u16 *)ptr;
5367 break;
5368 case sizeof(u32):
5369 *val = (u64)*(u32 *)ptr;
5370 break;
5371 case sizeof(u64):
5372 *val = *(u64 *)ptr;
5373 break;
5374 default:
5375 return -EINVAL;
5376 }
5377 return 0;
5378}
5379
6fcd486b
AS
5380#define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
5381#define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
57539b1c 5382
6fcd486b
AS
5383/*
5384 * Allow list few fields as RCU trusted or full trusted.
5385 * This logic doesn't allow mix tagging and will be removed once GCC supports
5386 * btf_type_tag.
5387 */
5388
5389/* RCU trusted: these fields are trusted in RCU CS and never NULL */
5390BTF_TYPE_SAFE_RCU(struct task_struct) {
57539b1c 5391 const cpumask_t *cpus_ptr;
8d093b4e 5392 struct css_set __rcu *cgroups;
6fcd486b
AS
5393 struct task_struct __rcu *real_parent;
5394 struct task_struct *group_leader;
8d093b4e
AS
5395};
5396
6fcd486b 5397BTF_TYPE_SAFE_RCU(struct css_set) {
8d093b4e 5398 struct cgroup *dfl_cgrp;
57539b1c
DV
5399};
5400
6fcd486b
AS
5401/* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5402BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
63260df1 5403 struct seq_file *seq;
6fcd486b
AS
5404};
5405
5406BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
63260df1
AS
5407 struct bpf_iter_meta *meta;
5408 struct task_struct *task;
6fcd486b
AS
5409};
5410
5411BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5412 struct file *file;
5413};
5414
5415BTF_TYPE_SAFE_TRUSTED(struct file) {
5416 struct inode *f_inode;
5417};
5418
5419BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5420 /* no negative dentry-s in places where bpf can see it */
5421 struct inode *d_inode;
5422};
5423
5424BTF_TYPE_SAFE_TRUSTED(struct socket) {
5425 struct sock *sk;
5426};
5427
5428static bool type_is_rcu(struct bpf_verifier_env *env,
5429 struct bpf_reg_state *reg,
63260df1 5430 const char *field_name, u32 btf_id)
57539b1c 5431{
6fcd486b
AS
5432 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5433 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
57539b1c 5434
63260df1 5435 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6fcd486b 5436}
57539b1c 5437
6fcd486b
AS
5438static bool type_is_trusted(struct bpf_verifier_env *env,
5439 struct bpf_reg_state *reg,
63260df1 5440 const char *field_name, u32 btf_id)
6fcd486b
AS
5441{
5442 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5443 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5444 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5445 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5446 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5447 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5448
63260df1 5449 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
57539b1c
DV
5450}
5451
9e15db66
AS
5452static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5453 struct bpf_reg_state *regs,
5454 int regno, int off, int size,
5455 enum bpf_access_type atype,
5456 int value_regno)
5457{
5458 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
5459 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5460 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
63260df1 5461 const char *field_name = NULL;
c6f1bfe8 5462 enum bpf_type_flag flag = 0;
b7e852a9 5463 u32 btf_id = 0;
9e15db66
AS
5464 int ret;
5465
c67cae55
AS
5466 if (!env->allow_ptr_leaks) {
5467 verbose(env,
5468 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5469 tname);
5470 return -EPERM;
5471 }
5472 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5473 verbose(env,
5474 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5475 tname);
5476 return -EINVAL;
5477 }
9e15db66
AS
5478 if (off < 0) {
5479 verbose(env,
5480 "R%d is ptr_%s invalid negative access: off=%d\n",
5481 regno, tname, off);
5482 return -EACCES;
5483 }
5484 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5485 char tn_buf[48];
5486
5487 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5488 verbose(env,
5489 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5490 regno, tname, off, tn_buf);
5491 return -EACCES;
5492 }
5493
c6f1bfe8
YS
5494 if (reg->type & MEM_USER) {
5495 verbose(env,
5496 "R%d is ptr_%s access user memory: off=%d\n",
5497 regno, tname, off);
5498 return -EACCES;
5499 }
5500
5844101a
HL
5501 if (reg->type & MEM_PERCPU) {
5502 verbose(env,
5503 "R%d is ptr_%s access percpu memory: off=%d\n",
5504 regno, tname, off);
5505 return -EACCES;
5506 }
5507
7d64c513 5508 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
282de143
KKD
5509 if (!btf_is_kernel(reg->btf)) {
5510 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5511 return -EFAULT;
5512 }
b7e852a9 5513 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
27ae7997 5514 } else {
282de143
KKD
5515 /* Writes are permitted with default btf_struct_access for
5516 * program allocated objects (which always have ref_obj_id > 0),
5517 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5518 */
5519 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
27ae7997
MKL
5520 verbose(env, "only read is supported\n");
5521 return -EACCES;
5522 }
5523
6a3cd331
DM
5524 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5525 !reg->ref_obj_id) {
282de143
KKD
5526 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5527 return -EFAULT;
5528 }
5529
63260df1 5530 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
27ae7997
MKL
5531 }
5532
9e15db66
AS
5533 if (ret < 0)
5534 return ret;
5535
6fcd486b
AS
5536 if (ret != PTR_TO_BTF_ID) {
5537 /* just mark; */
6efe152d 5538
6fcd486b
AS
5539 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5540 /* If this is an untrusted pointer, all pointers formed by walking it
5541 * also inherit the untrusted flag.
5542 */
5543 flag = PTR_UNTRUSTED;
5544
5545 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5546 /* By default any pointer obtained from walking a trusted pointer is no
5547 * longer trusted, unless the field being accessed has explicitly been
5548 * marked as inheriting its parent's state of trust (either full or RCU).
5549 * For example:
5550 * 'cgroups' pointer is untrusted if task->cgroups dereference
5551 * happened in a sleepable program outside of bpf_rcu_read_lock()
5552 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5553 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5554 *
5555 * A regular RCU-protected pointer with __rcu tag can also be deemed
5556 * trusted if we are in an RCU CS. Such pointer can be NULL.
20c09d92 5557 */
63260df1 5558 if (type_is_trusted(env, reg, field_name, btf_id)) {
6fcd486b
AS
5559 flag |= PTR_TRUSTED;
5560 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
63260df1 5561 if (type_is_rcu(env, reg, field_name, btf_id)) {
6fcd486b
AS
5562 /* ignore __rcu tag and mark it MEM_RCU */
5563 flag |= MEM_RCU;
5564 } else if (flag & MEM_RCU) {
5565 /* __rcu tagged pointers can be NULL */
5566 flag |= PTR_MAYBE_NULL;
5567 } else if (flag & (MEM_PERCPU | MEM_USER)) {
5568 /* keep as-is */
5569 } else {
5570 /* walking unknown pointers yields untrusted pointer */
5571 flag = PTR_UNTRUSTED;
5572 }
5573 } else {
5574 /*
5575 * If not in RCU CS or MEM_RCU pointer can be NULL then
5576 * aggressively mark as untrusted otherwise such
5577 * pointers will be plain PTR_TO_BTF_ID without flags
5578 * and will be allowed to be passed into helpers for
5579 * compat reasons.
5580 */
5581 flag = PTR_UNTRUSTED;
5582 }
20c09d92 5583 } else {
6fcd486b 5584 /* Old compat. Deprecated */
57539b1c 5585 flag &= ~PTR_TRUSTED;
20c09d92 5586 }
3f00c523 5587
41c48f3a 5588 if (atype == BPF_READ && value_regno >= 0)
c6f1bfe8 5589 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
41c48f3a
AI
5590
5591 return 0;
5592}
5593
5594static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5595 struct bpf_reg_state *regs,
5596 int regno, int off, int size,
5597 enum bpf_access_type atype,
5598 int value_regno)
5599{
5600 struct bpf_reg_state *reg = regs + regno;
5601 struct bpf_map *map = reg->map_ptr;
6728aea7 5602 struct bpf_reg_state map_reg;
c6f1bfe8 5603 enum bpf_type_flag flag = 0;
41c48f3a
AI
5604 const struct btf_type *t;
5605 const char *tname;
5606 u32 btf_id;
5607 int ret;
5608
5609 if (!btf_vmlinux) {
5610 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5611 return -ENOTSUPP;
5612 }
5613
5614 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5615 verbose(env, "map_ptr access not supported for map type %d\n",
5616 map->map_type);
5617 return -ENOTSUPP;
5618 }
5619
5620 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5621 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5622
c67cae55 5623 if (!env->allow_ptr_leaks) {
41c48f3a 5624 verbose(env,
c67cae55 5625 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
41c48f3a
AI
5626 tname);
5627 return -EPERM;
9e15db66 5628 }
27ae7997 5629
41c48f3a
AI
5630 if (off < 0) {
5631 verbose(env, "R%d is %s invalid negative access: off=%d\n",
5632 regno, tname, off);
5633 return -EACCES;
5634 }
5635
5636 if (atype != BPF_READ) {
5637 verbose(env, "only read from %s is supported\n", tname);
5638 return -EACCES;
5639 }
5640
6728aea7
KKD
5641 /* Simulate access to a PTR_TO_BTF_ID */
5642 memset(&map_reg, 0, sizeof(map_reg));
5643 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
63260df1 5644 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
41c48f3a
AI
5645 if (ret < 0)
5646 return ret;
5647
5648 if (value_regno >= 0)
c6f1bfe8 5649 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
41c48f3a 5650
9e15db66
AS
5651 return 0;
5652}
5653
01f810ac
AM
5654/* Check that the stack access at the given offset is within bounds. The
5655 * maximum valid offset is -1.
5656 *
5657 * The minimum valid offset is -MAX_BPF_STACK for writes, and
5658 * -state->allocated_stack for reads.
5659 */
5660static int check_stack_slot_within_bounds(int off,
5661 struct bpf_func_state *state,
5662 enum bpf_access_type t)
5663{
5664 int min_valid_off;
5665
5666 if (t == BPF_WRITE)
5667 min_valid_off = -MAX_BPF_STACK;
5668 else
5669 min_valid_off = -state->allocated_stack;
5670
5671 if (off < min_valid_off || off > -1)
5672 return -EACCES;
5673 return 0;
5674}
5675
5676/* Check that the stack access at 'regno + off' falls within the maximum stack
5677 * bounds.
5678 *
5679 * 'off' includes `regno->offset`, but not its dynamic part (if any).
5680 */
5681static int check_stack_access_within_bounds(
5682 struct bpf_verifier_env *env,
5683 int regno, int off, int access_size,
61df10c7 5684 enum bpf_access_src src, enum bpf_access_type type)
01f810ac
AM
5685{
5686 struct bpf_reg_state *regs = cur_regs(env);
5687 struct bpf_reg_state *reg = regs + regno;
5688 struct bpf_func_state *state = func(env, reg);
5689 int min_off, max_off;
5690 int err;
5691 char *err_extra;
5692
5693 if (src == ACCESS_HELPER)
5694 /* We don't know if helpers are reading or writing (or both). */
5695 err_extra = " indirect access to";
5696 else if (type == BPF_READ)
5697 err_extra = " read from";
5698 else
5699 err_extra = " write to";
5700
5701 if (tnum_is_const(reg->var_off)) {
5702 min_off = reg->var_off.value + off;
5703 if (access_size > 0)
5704 max_off = min_off + access_size - 1;
5705 else
5706 max_off = min_off;
5707 } else {
5708 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5709 reg->smin_value <= -BPF_MAX_VAR_OFF) {
5710 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5711 err_extra, regno);
5712 return -EACCES;
5713 }
5714 min_off = reg->smin_value + off;
5715 if (access_size > 0)
5716 max_off = reg->smax_value + off + access_size - 1;
5717 else
5718 max_off = min_off;
5719 }
5720
5721 err = check_stack_slot_within_bounds(min_off, state, type);
5722 if (!err)
5723 err = check_stack_slot_within_bounds(max_off, state, type);
5724
5725 if (err) {
5726 if (tnum_is_const(reg->var_off)) {
5727 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5728 err_extra, regno, off, access_size);
5729 } else {
5730 char tn_buf[48];
5731
5732 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5733 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5734 err_extra, regno, tn_buf, access_size);
5735 }
5736 }
5737 return err;
5738}
41c48f3a 5739
17a52670
AS
5740/* check whether memory at (regno + off) is accessible for t = (read | write)
5741 * if t==write, value_regno is a register which value is stored into memory
5742 * if t==read, value_regno is a register which will receive the value from memory
5743 * if t==write && value_regno==-1, some unknown value is stored into memory
5744 * if t==read && value_regno==-1, don't care what we read from memory
5745 */
ca369602
DB
5746static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5747 int off, int bpf_size, enum bpf_access_type t,
5748 int value_regno, bool strict_alignment_once)
17a52670 5749{
638f5b90
AS
5750 struct bpf_reg_state *regs = cur_regs(env);
5751 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 5752 struct bpf_func_state *state;
17a52670
AS
5753 int size, err = 0;
5754
5755 size = bpf_size_to_bytes(bpf_size);
5756 if (size < 0)
5757 return size;
5758
f1174f77 5759 /* alignment checks will add in reg->off themselves */
ca369602 5760 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
5761 if (err)
5762 return err;
17a52670 5763
f1174f77
EC
5764 /* for access checks, reg->off is just part of off */
5765 off += reg->off;
5766
69c087ba
YS
5767 if (reg->type == PTR_TO_MAP_KEY) {
5768 if (t == BPF_WRITE) {
5769 verbose(env, "write to change key R%d not allowed\n", regno);
5770 return -EACCES;
5771 }
5772
5773 err = check_mem_region_access(env, regno, off, size,
5774 reg->map_ptr->key_size, false);
5775 if (err)
5776 return err;
5777 if (value_regno >= 0)
5778 mark_reg_unknown(env, regs, value_regno);
5779 } else if (reg->type == PTR_TO_MAP_VALUE) {
aa3496ac 5780 struct btf_field *kptr_field = NULL;
61df10c7 5781
1be7f75d
AS
5782 if (t == BPF_WRITE && value_regno >= 0 &&
5783 is_pointer_value(env, value_regno)) {
61bd5218 5784 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
5785 return -EACCES;
5786 }
591fe988
DB
5787 err = check_map_access_type(env, regno, off, size, t);
5788 if (err)
5789 return err;
61df10c7
KKD
5790 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5791 if (err)
5792 return err;
5793 if (tnum_is_const(reg->var_off))
aa3496ac
KKD
5794 kptr_field = btf_record_find(reg->map_ptr->record,
5795 off + reg->var_off.value, BPF_KPTR);
5796 if (kptr_field) {
5797 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
61df10c7 5798 } else if (t == BPF_READ && value_regno >= 0) {
a23740ec
AN
5799 struct bpf_map *map = reg->map_ptr;
5800
5801 /* if map is read-only, track its contents as scalars */
5802 if (tnum_is_const(reg->var_off) &&
5803 bpf_map_is_rdonly(map) &&
5804 map->ops->map_direct_value_addr) {
5805 int map_off = off + reg->var_off.value;
5806 u64 val = 0;
5807
5808 err = bpf_map_direct_read(map, map_off, size,
5809 &val);
5810 if (err)
5811 return err;
5812
5813 regs[value_regno].type = SCALAR_VALUE;
5814 __mark_reg_known(&regs[value_regno], val);
5815 } else {
5816 mark_reg_unknown(env, regs, value_regno);
5817 }
5818 }
34d3a78c
HL
5819 } else if (base_type(reg->type) == PTR_TO_MEM) {
5820 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5821
5822 if (type_may_be_null(reg->type)) {
5823 verbose(env, "R%d invalid mem access '%s'\n", regno,
5824 reg_type_str(env, reg->type));
5825 return -EACCES;
5826 }
5827
5828 if (t == BPF_WRITE && rdonly_mem) {
5829 verbose(env, "R%d cannot write into %s\n",
5830 regno, reg_type_str(env, reg->type));
5831 return -EACCES;
5832 }
5833
457f4436
AN
5834 if (t == BPF_WRITE && value_regno >= 0 &&
5835 is_pointer_value(env, value_regno)) {
5836 verbose(env, "R%d leaks addr into mem\n", value_regno);
5837 return -EACCES;
5838 }
34d3a78c 5839
457f4436
AN
5840 err = check_mem_region_access(env, regno, off, size,
5841 reg->mem_size, false);
34d3a78c 5842 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
457f4436 5843 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 5844 } else if (reg->type == PTR_TO_CTX) {
f1174f77 5845 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 5846 struct btf *btf = NULL;
9e15db66 5847 u32 btf_id = 0;
19de99f7 5848
1be7f75d
AS
5849 if (t == BPF_WRITE && value_regno >= 0 &&
5850 is_pointer_value(env, value_regno)) {
61bd5218 5851 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
5852 return -EACCES;
5853 }
f1174f77 5854
be80a1d3 5855 err = check_ptr_off_reg(env, reg, regno);
58990d1f
DB
5856 if (err < 0)
5857 return err;
5858
c6f1bfe8
YS
5859 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5860 &btf_id);
9e15db66
AS
5861 if (err)
5862 verbose_linfo(env, insn_idx, "; ");
969bf05e 5863 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 5864 /* ctx access returns either a scalar, or a
de8f3a83
DB
5865 * PTR_TO_PACKET[_META,_END]. In the latter
5866 * case, we know the offset is zero.
f1174f77 5867 */
46f8bc92 5868 if (reg_type == SCALAR_VALUE) {
638f5b90 5869 mark_reg_unknown(env, regs, value_regno);
46f8bc92 5870 } else {
638f5b90 5871 mark_reg_known_zero(env, regs,
61bd5218 5872 value_regno);
c25b2ae1 5873 if (type_may_be_null(reg_type))
46f8bc92 5874 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
5875 /* A load of ctx field could have different
5876 * actual load size with the one encoded in the
5877 * insn. When the dst is PTR, it is for sure not
5878 * a sub-register.
5879 */
5880 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
c25b2ae1 5881 if (base_type(reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 5882 regs[value_regno].btf = btf;
9e15db66 5883 regs[value_regno].btf_id = btf_id;
22dc4a0f 5884 }
46f8bc92 5885 }
638f5b90 5886 regs[value_regno].type = reg_type;
969bf05e 5887 }
17a52670 5888
f1174f77 5889 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
5890 /* Basic bounds checks. */
5891 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
5892 if (err)
5893 return err;
8726679a 5894
f4d7e40a
AS
5895 state = func(env, reg);
5896 err = update_stack_depth(env, state, off);
5897 if (err)
5898 return err;
8726679a 5899
01f810ac
AM
5900 if (t == BPF_READ)
5901 err = check_stack_read(env, regno, off, size,
61bd5218 5902 value_regno);
01f810ac
AM
5903 else
5904 err = check_stack_write(env, regno, off, size,
5905 value_regno, insn_idx);
de8f3a83 5906 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 5907 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 5908 verbose(env, "cannot write into packet\n");
969bf05e
AS
5909 return -EACCES;
5910 }
4acf6c0b
BB
5911 if (t == BPF_WRITE && value_regno >= 0 &&
5912 is_pointer_value(env, value_regno)) {
61bd5218
JK
5913 verbose(env, "R%d leaks addr into packet\n",
5914 value_regno);
4acf6c0b
BB
5915 return -EACCES;
5916 }
9fd29c08 5917 err = check_packet_access(env, regno, off, size, false);
969bf05e 5918 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 5919 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
5920 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5921 if (t == BPF_WRITE && value_regno >= 0 &&
5922 is_pointer_value(env, value_regno)) {
5923 verbose(env, "R%d leaks addr into flow keys\n",
5924 value_regno);
5925 return -EACCES;
5926 }
5927
5928 err = check_flow_keys_access(env, off, size);
5929 if (!err && t == BPF_READ && value_regno >= 0)
5930 mark_reg_unknown(env, regs, value_regno);
46f8bc92 5931 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 5932 if (t == BPF_WRITE) {
46f8bc92 5933 verbose(env, "R%d cannot write into %s\n",
c25b2ae1 5934 regno, reg_type_str(env, reg->type));
c64b7983
JS
5935 return -EACCES;
5936 }
5f456649 5937 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
5938 if (!err && value_regno >= 0)
5939 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
5940 } else if (reg->type == PTR_TO_TP_BUFFER) {
5941 err = check_tp_buffer_access(env, reg, regno, off, size);
5942 if (!err && t == BPF_READ && value_regno >= 0)
5943 mark_reg_unknown(env, regs, value_regno);
bff61f6f
HL
5944 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5945 !type_may_be_null(reg->type)) {
9e15db66
AS
5946 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5947 value_regno);
41c48f3a
AI
5948 } else if (reg->type == CONST_PTR_TO_MAP) {
5949 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5950 value_regno);
20b2aff4
HL
5951 } else if (base_type(reg->type) == PTR_TO_BUF) {
5952 bool rdonly_mem = type_is_rdonly_mem(reg->type);
20b2aff4
HL
5953 u32 *max_access;
5954
5955 if (rdonly_mem) {
5956 if (t == BPF_WRITE) {
5957 verbose(env, "R%d cannot write into %s\n",
5958 regno, reg_type_str(env, reg->type));
5959 return -EACCES;
5960 }
20b2aff4
HL
5961 max_access = &env->prog->aux->max_rdonly_access;
5962 } else {
20b2aff4 5963 max_access = &env->prog->aux->max_rdwr_access;
afbf21dc 5964 }
20b2aff4 5965
f6dfbe31 5966 err = check_buffer_access(env, reg, regno, off, size, false,
44e9a741 5967 max_access);
20b2aff4
HL
5968
5969 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
afbf21dc 5970 mark_reg_unknown(env, regs, value_regno);
17a52670 5971 } else {
61bd5218 5972 verbose(env, "R%d invalid mem access '%s'\n", regno,
c25b2ae1 5973 reg_type_str(env, reg->type));
17a52670
AS
5974 return -EACCES;
5975 }
969bf05e 5976
f1174f77 5977 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 5978 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 5979 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 5980 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 5981 }
17a52670
AS
5982 return err;
5983}
5984
91c960b0 5985static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 5986{
5ffa2550 5987 int load_reg;
17a52670
AS
5988 int err;
5989
5ca419f2
BJ
5990 switch (insn->imm) {
5991 case BPF_ADD:
5992 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
5993 case BPF_AND:
5994 case BPF_AND | BPF_FETCH:
5995 case BPF_OR:
5996 case BPF_OR | BPF_FETCH:
5997 case BPF_XOR:
5998 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
5999 case BPF_XCHG:
6000 case BPF_CMPXCHG:
5ca419f2
BJ
6001 break;
6002 default:
91c960b0
BJ
6003 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6004 return -EINVAL;
6005 }
6006
6007 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6008 verbose(env, "invalid atomic operand size\n");
17a52670
AS
6009 return -EINVAL;
6010 }
6011
6012 /* check src1 operand */
dc503a8a 6013 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6014 if (err)
6015 return err;
6016
6017 /* check src2 operand */
dc503a8a 6018 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6019 if (err)
6020 return err;
6021
5ffa2550
BJ
6022 if (insn->imm == BPF_CMPXCHG) {
6023 /* Check comparison of R0 with memory location */
a82fe085
DB
6024 const u32 aux_reg = BPF_REG_0;
6025
6026 err = check_reg_arg(env, aux_reg, SRC_OP);
5ffa2550
BJ
6027 if (err)
6028 return err;
a82fe085
DB
6029
6030 if (is_pointer_value(env, aux_reg)) {
6031 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6032 return -EACCES;
6033 }
5ffa2550
BJ
6034 }
6035
6bdf6abc 6036 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 6037 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
6038 return -EACCES;
6039 }
6040
ca369602 6041 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 6042 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
6043 is_flow_key_reg(env, insn->dst_reg) ||
6044 is_sk_reg(env, insn->dst_reg)) {
91c960b0 6045 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f 6046 insn->dst_reg,
c25b2ae1 6047 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
6048 return -EACCES;
6049 }
6050
37086bfd
BJ
6051 if (insn->imm & BPF_FETCH) {
6052 if (insn->imm == BPF_CMPXCHG)
6053 load_reg = BPF_REG_0;
6054 else
6055 load_reg = insn->src_reg;
6056
6057 /* check and record load of old value */
6058 err = check_reg_arg(env, load_reg, DST_OP);
6059 if (err)
6060 return err;
6061 } else {
6062 /* This instruction accesses a memory location but doesn't
6063 * actually load it into a register.
6064 */
6065 load_reg = -1;
6066 }
6067
7d3baf0a
DB
6068 /* Check whether we can read the memory, with second call for fetch
6069 * case to simulate the register fill.
6070 */
31fd8581 6071 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7d3baf0a
DB
6072 BPF_SIZE(insn->code), BPF_READ, -1, true);
6073 if (!err && load_reg >= 0)
6074 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6075 BPF_SIZE(insn->code), BPF_READ, load_reg,
6076 true);
17a52670
AS
6077 if (err)
6078 return err;
6079
7d3baf0a 6080 /* Check whether we can write into the same memory. */
5ca419f2
BJ
6081 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6082 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6083 if (err)
6084 return err;
6085
5ca419f2 6086 return 0;
17a52670
AS
6087}
6088
01f810ac
AM
6089/* When register 'regno' is used to read the stack (either directly or through
6090 * a helper function) make sure that it's within stack boundary and, depending
6091 * on the access type, that all elements of the stack are initialized.
6092 *
6093 * 'off' includes 'regno->off', but not its dynamic part (if any).
6094 *
6095 * All registers that have been spilled on the stack in the slots within the
6096 * read offsets are marked as read.
6097 */
6098static int check_stack_range_initialized(
6099 struct bpf_verifier_env *env, int regno, int off,
6100 int access_size, bool zero_size_allowed,
61df10c7 6101 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
6102{
6103 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
6104 struct bpf_func_state *state = func(env, reg);
6105 int err, min_off, max_off, i, j, slot, spi;
6106 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6107 enum bpf_access_type bounds_check_type;
6108 /* Some accesses can write anything into the stack, others are
6109 * read-only.
6110 */
6111 bool clobber = false;
2011fccf 6112
01f810ac
AM
6113 if (access_size == 0 && !zero_size_allowed) {
6114 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
6115 return -EACCES;
6116 }
2011fccf 6117
01f810ac
AM
6118 if (type == ACCESS_HELPER) {
6119 /* The bounds checks for writes are more permissive than for
6120 * reads. However, if raw_mode is not set, we'll do extra
6121 * checks below.
6122 */
6123 bounds_check_type = BPF_WRITE;
6124 clobber = true;
6125 } else {
6126 bounds_check_type = BPF_READ;
6127 }
6128 err = check_stack_access_within_bounds(env, regno, off, access_size,
6129 type, bounds_check_type);
6130 if (err)
6131 return err;
6132
17a52670 6133
2011fccf 6134 if (tnum_is_const(reg->var_off)) {
01f810ac 6135 min_off = max_off = reg->var_off.value + off;
2011fccf 6136 } else {
088ec26d
AI
6137 /* Variable offset is prohibited for unprivileged mode for
6138 * simplicity since it requires corresponding support in
6139 * Spectre masking for stack ALU.
6140 * See also retrieve_ptr_limit().
6141 */
2c78ee89 6142 if (!env->bypass_spec_v1) {
088ec26d 6143 char tn_buf[48];
f1174f77 6144
088ec26d 6145 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
6146 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6147 regno, err_extra, tn_buf);
088ec26d
AI
6148 return -EACCES;
6149 }
f2bcd05e
AI
6150 /* Only initialized buffer on stack is allowed to be accessed
6151 * with variable offset. With uninitialized buffer it's hard to
6152 * guarantee that whole memory is marked as initialized on
6153 * helper return since specific bounds are unknown what may
6154 * cause uninitialized stack leaking.
6155 */
6156 if (meta && meta->raw_mode)
6157 meta = NULL;
6158
01f810ac
AM
6159 min_off = reg->smin_value + off;
6160 max_off = reg->smax_value + off;
17a52670
AS
6161 }
6162
435faee1 6163 if (meta && meta->raw_mode) {
ef8fc7a0
KKD
6164 /* Ensure we won't be overwriting dynptrs when simulating byte
6165 * by byte access in check_helper_call using meta.access_size.
6166 * This would be a problem if we have a helper in the future
6167 * which takes:
6168 *
6169 * helper(uninit_mem, len, dynptr)
6170 *
6171 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6172 * may end up writing to dynptr itself when touching memory from
6173 * arg 1. This can be relaxed on a case by case basis for known
6174 * safe cases, but reject due to the possibilitiy of aliasing by
6175 * default.
6176 */
6177 for (i = min_off; i < max_off + access_size; i++) {
6178 int stack_off = -i - 1;
6179
6180 spi = __get_spi(i);
6181 /* raw_mode may write past allocated_stack */
6182 if (state->allocated_stack <= stack_off)
6183 continue;
6184 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6185 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6186 return -EACCES;
6187 }
6188 }
435faee1
DB
6189 meta->access_size = access_size;
6190 meta->regno = regno;
6191 return 0;
6192 }
6193
2011fccf 6194 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
6195 u8 *stype;
6196
2011fccf 6197 slot = -i - 1;
638f5b90 6198 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
6199 if (state->allocated_stack <= slot)
6200 goto err;
6201 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6202 if (*stype == STACK_MISC)
6203 goto mark;
6715df8d
EZ
6204 if ((*stype == STACK_ZERO) ||
6205 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
01f810ac
AM
6206 if (clobber) {
6207 /* helper can write anything into the stack */
6208 *stype = STACK_MISC;
6209 }
cc2b14d5 6210 goto mark;
17a52670 6211 }
1d68f22b 6212
27113c59 6213 if (is_spilled_reg(&state->stack[spi]) &&
cd17d38f
YS
6214 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6215 env->allow_ptr_leaks)) {
01f810ac
AM
6216 if (clobber) {
6217 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6218 for (j = 0; j < BPF_REG_SIZE; j++)
354e8f19 6219 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
01f810ac 6220 }
f7cf25b2
AS
6221 goto mark;
6222 }
6223
cc2b14d5 6224err:
2011fccf 6225 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
6226 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6227 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
6228 } else {
6229 char tn_buf[48];
6230
6231 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
6232 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6233 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 6234 }
cc2b14d5
AS
6235 return -EACCES;
6236mark:
6237 /* reading any byte out of 8-byte 'spill_slot' will cause
6238 * the whole slot to be marked as 'read'
6239 */
679c782d 6240 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
6241 state->stack[spi].spilled_ptr.parent,
6242 REG_LIVE_READ64);
261f4664
KKD
6243 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6244 * be sure that whether stack slot is written to or not. Hence,
6245 * we must still conservatively propagate reads upwards even if
6246 * helper may write to the entire memory range.
6247 */
17a52670 6248 }
2011fccf 6249 return update_stack_depth(env, state, min_off);
17a52670
AS
6250}
6251
06c1c049
GB
6252static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6253 int access_size, bool zero_size_allowed,
6254 struct bpf_call_arg_meta *meta)
6255{
638f5b90 6256 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
20b2aff4 6257 u32 *max_access;
06c1c049 6258
20b2aff4 6259 switch (base_type(reg->type)) {
06c1c049 6260 case PTR_TO_PACKET:
de8f3a83 6261 case PTR_TO_PACKET_META:
9fd29c08
YS
6262 return check_packet_access(env, regno, reg->off, access_size,
6263 zero_size_allowed);
69c087ba 6264 case PTR_TO_MAP_KEY:
7b3552d3
KKD
6265 if (meta && meta->raw_mode) {
6266 verbose(env, "R%d cannot write into %s\n", regno,
6267 reg_type_str(env, reg->type));
6268 return -EACCES;
6269 }
69c087ba
YS
6270 return check_mem_region_access(env, regno, reg->off, access_size,
6271 reg->map_ptr->key_size, false);
06c1c049 6272 case PTR_TO_MAP_VALUE:
591fe988
DB
6273 if (check_map_access_type(env, regno, reg->off, access_size,
6274 meta && meta->raw_mode ? BPF_WRITE :
6275 BPF_READ))
6276 return -EACCES;
9fd29c08 6277 return check_map_access(env, regno, reg->off, access_size,
61df10c7 6278 zero_size_allowed, ACCESS_HELPER);
457f4436 6279 case PTR_TO_MEM:
97e6d7da
KKD
6280 if (type_is_rdonly_mem(reg->type)) {
6281 if (meta && meta->raw_mode) {
6282 verbose(env, "R%d cannot write into %s\n", regno,
6283 reg_type_str(env, reg->type));
6284 return -EACCES;
6285 }
6286 }
457f4436
AN
6287 return check_mem_region_access(env, regno, reg->off,
6288 access_size, reg->mem_size,
6289 zero_size_allowed);
20b2aff4
HL
6290 case PTR_TO_BUF:
6291 if (type_is_rdonly_mem(reg->type)) {
97e6d7da
KKD
6292 if (meta && meta->raw_mode) {
6293 verbose(env, "R%d cannot write into %s\n", regno,
6294 reg_type_str(env, reg->type));
20b2aff4 6295 return -EACCES;
97e6d7da 6296 }
20b2aff4 6297
20b2aff4
HL
6298 max_access = &env->prog->aux->max_rdonly_access;
6299 } else {
20b2aff4
HL
6300 max_access = &env->prog->aux->max_rdwr_access;
6301 }
afbf21dc
YS
6302 return check_buffer_access(env, reg, regno, reg->off,
6303 access_size, zero_size_allowed,
44e9a741 6304 max_access);
0d004c02 6305 case PTR_TO_STACK:
01f810ac
AM
6306 return check_stack_range_initialized(
6307 env,
6308 regno, reg->off, access_size,
6309 zero_size_allowed, ACCESS_HELPER, meta);
3e30be42
AS
6310 case PTR_TO_BTF_ID:
6311 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6312 access_size, BPF_READ, -1);
15baa55f
BT
6313 case PTR_TO_CTX:
6314 /* in case the function doesn't know how to access the context,
6315 * (because we are in a program of type SYSCALL for example), we
6316 * can not statically check its size.
6317 * Dynamically check it now.
6318 */
6319 if (!env->ops->convert_ctx_access) {
6320 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6321 int offset = access_size - 1;
6322
6323 /* Allow zero-byte read from PTR_TO_CTX */
6324 if (access_size == 0)
6325 return zero_size_allowed ? 0 : -EACCES;
6326
6327 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6328 atype, -1, false);
6329 }
6330
6331 fallthrough;
0d004c02
LB
6332 default: /* scalar_value or invalid ptr */
6333 /* Allow zero-byte read from NULL, regardless of pointer type */
6334 if (zero_size_allowed && access_size == 0 &&
6335 register_is_null(reg))
6336 return 0;
6337
c25b2ae1
HL
6338 verbose(env, "R%d type=%s ", regno,
6339 reg_type_str(env, reg->type));
6340 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
0d004c02 6341 return -EACCES;
06c1c049
GB
6342 }
6343}
6344
d583691c
KKD
6345static int check_mem_size_reg(struct bpf_verifier_env *env,
6346 struct bpf_reg_state *reg, u32 regno,
6347 bool zero_size_allowed,
6348 struct bpf_call_arg_meta *meta)
6349{
6350 int err;
6351
6352 /* This is used to refine r0 return value bounds for helpers
6353 * that enforce this value as an upper bound on return values.
6354 * See do_refine_retval_range() for helpers that can refine
6355 * the return value. C type of helper is u32 so we pull register
6356 * bound from umax_value however, if negative verifier errors
6357 * out. Only upper bounds can be learned because retval is an
6358 * int type and negative retvals are allowed.
6359 */
be77354a 6360 meta->msize_max_value = reg->umax_value;
d583691c
KKD
6361
6362 /* The register is SCALAR_VALUE; the access check
6363 * happens using its boundaries.
6364 */
6365 if (!tnum_is_const(reg->var_off))
6366 /* For unprivileged variable accesses, disable raw
6367 * mode so that the program is required to
6368 * initialize all the memory that the helper could
6369 * just partially fill up.
6370 */
6371 meta = NULL;
6372
6373 if (reg->smin_value < 0) {
6374 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6375 regno);
6376 return -EACCES;
6377 }
6378
6379 if (reg->umin_value == 0) {
6380 err = check_helper_mem_access(env, regno - 1, 0,
6381 zero_size_allowed,
6382 meta);
6383 if (err)
6384 return err;
6385 }
6386
6387 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6388 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6389 regno);
6390 return -EACCES;
6391 }
6392 err = check_helper_mem_access(env, regno - 1,
6393 reg->umax_value,
6394 zero_size_allowed, meta);
6395 if (!err)
6396 err = mark_chain_precision(env, regno);
6397 return err;
6398}
6399
e5069b9c
DB
6400int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6401 u32 regno, u32 mem_size)
6402{
be77354a
KKD
6403 bool may_be_null = type_may_be_null(reg->type);
6404 struct bpf_reg_state saved_reg;
6405 struct bpf_call_arg_meta meta;
6406 int err;
6407
e5069b9c
DB
6408 if (register_is_null(reg))
6409 return 0;
6410
be77354a
KKD
6411 memset(&meta, 0, sizeof(meta));
6412 /* Assuming that the register contains a value check if the memory
6413 * access is safe. Temporarily save and restore the register's state as
6414 * the conversion shouldn't be visible to a caller.
6415 */
6416 if (may_be_null) {
6417 saved_reg = *reg;
e5069b9c 6418 mark_ptr_not_null_reg(reg);
e5069b9c
DB
6419 }
6420
be77354a
KKD
6421 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6422 /* Check access for BPF_WRITE */
6423 meta.raw_mode = true;
6424 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6425
6426 if (may_be_null)
6427 *reg = saved_reg;
6428
6429 return err;
e5069b9c
DB
6430}
6431
00b85860
KKD
6432static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6433 u32 regno)
d583691c
KKD
6434{
6435 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6436 bool may_be_null = type_may_be_null(mem_reg->type);
6437 struct bpf_reg_state saved_reg;
be77354a 6438 struct bpf_call_arg_meta meta;
d583691c
KKD
6439 int err;
6440
6441 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6442
be77354a
KKD
6443 memset(&meta, 0, sizeof(meta));
6444
d583691c
KKD
6445 if (may_be_null) {
6446 saved_reg = *mem_reg;
6447 mark_ptr_not_null_reg(mem_reg);
6448 }
6449
be77354a
KKD
6450 err = check_mem_size_reg(env, reg, regno, true, &meta);
6451 /* Check access for BPF_WRITE */
6452 meta.raw_mode = true;
6453 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
d583691c
KKD
6454
6455 if (may_be_null)
6456 *mem_reg = saved_reg;
6457 return err;
6458}
6459
d83525ca 6460/* Implementation details:
4e814da0
KKD
6461 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6462 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
d83525ca 6463 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4e814da0
KKD
6464 * Two separate bpf_obj_new will also have different reg->id.
6465 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6466 * clears reg->id after value_or_null->value transition, since the verifier only
6467 * cares about the range of access to valid map value pointer and doesn't care
6468 * about actual address of the map element.
d83525ca
AS
6469 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6470 * reg->id > 0 after value_or_null->value transition. By doing so
6471 * two bpf_map_lookups will be considered two different pointers that
4e814da0
KKD
6472 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6473 * returned from bpf_obj_new.
d83525ca
AS
6474 * The verifier allows taking only one bpf_spin_lock at a time to avoid
6475 * dead-locks.
6476 * Since only one bpf_spin_lock is allowed the checks are simpler than
6477 * reg_is_refcounted() logic. The verifier needs to remember only
6478 * one spin_lock instead of array of acquired_refs.
d0d78c1d 6479 * cur_state->active_lock remembers which map value element or allocated
4e814da0 6480 * object got locked and clears it after bpf_spin_unlock.
d83525ca
AS
6481 */
6482static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6483 bool is_lock)
6484{
6485 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6486 struct bpf_verifier_state *cur = env->cur_state;
6487 bool is_const = tnum_is_const(reg->var_off);
d83525ca 6488 u64 val = reg->var_off.value;
4e814da0
KKD
6489 struct bpf_map *map = NULL;
6490 struct btf *btf = NULL;
6491 struct btf_record *rec;
d83525ca 6492
d83525ca
AS
6493 if (!is_const) {
6494 verbose(env,
6495 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6496 regno);
6497 return -EINVAL;
6498 }
4e814da0
KKD
6499 if (reg->type == PTR_TO_MAP_VALUE) {
6500 map = reg->map_ptr;
6501 if (!map->btf) {
6502 verbose(env,
6503 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
6504 map->name);
6505 return -EINVAL;
6506 }
6507 } else {
6508 btf = reg->btf;
d83525ca 6509 }
4e814da0
KKD
6510
6511 rec = reg_btf_record(reg);
6512 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6513 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6514 map ? map->name : "kptr");
d83525ca
AS
6515 return -EINVAL;
6516 }
4e814da0 6517 if (rec->spin_lock_off != val + reg->off) {
db559117 6518 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
4e814da0 6519 val + reg->off, rec->spin_lock_off);
d83525ca
AS
6520 return -EINVAL;
6521 }
6522 if (is_lock) {
d0d78c1d 6523 if (cur->active_lock.ptr) {
d83525ca
AS
6524 verbose(env,
6525 "Locking two bpf_spin_locks are not allowed\n");
6526 return -EINVAL;
6527 }
d0d78c1d
KKD
6528 if (map)
6529 cur->active_lock.ptr = map;
6530 else
6531 cur->active_lock.ptr = btf;
6532 cur->active_lock.id = reg->id;
d83525ca 6533 } else {
d0d78c1d
KKD
6534 void *ptr;
6535
6536 if (map)
6537 ptr = map;
6538 else
6539 ptr = btf;
6540
6541 if (!cur->active_lock.ptr) {
d83525ca
AS
6542 verbose(env, "bpf_spin_unlock without taking a lock\n");
6543 return -EINVAL;
6544 }
d0d78c1d
KKD
6545 if (cur->active_lock.ptr != ptr ||
6546 cur->active_lock.id != reg->id) {
d83525ca
AS
6547 verbose(env, "bpf_spin_unlock of different lock\n");
6548 return -EINVAL;
6549 }
534e86bc 6550
6a3cd331 6551 invalidate_non_owning_refs(env);
534e86bc 6552
6a3cd331
DM
6553 cur->active_lock.ptr = NULL;
6554 cur->active_lock.id = 0;
d83525ca
AS
6555 }
6556 return 0;
6557}
6558
b00628b1
AS
6559static int process_timer_func(struct bpf_verifier_env *env, int regno,
6560 struct bpf_call_arg_meta *meta)
6561{
6562 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6563 bool is_const = tnum_is_const(reg->var_off);
6564 struct bpf_map *map = reg->map_ptr;
6565 u64 val = reg->var_off.value;
6566
6567 if (!is_const) {
6568 verbose(env,
6569 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6570 regno);
6571 return -EINVAL;
6572 }
6573 if (!map->btf) {
6574 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6575 map->name);
6576 return -EINVAL;
6577 }
db559117
KKD
6578 if (!btf_record_has_field(map->record, BPF_TIMER)) {
6579 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
68134668
AS
6580 return -EINVAL;
6581 }
db559117 6582 if (map->record->timer_off != val + reg->off) {
68134668 6583 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
db559117 6584 val + reg->off, map->record->timer_off);
b00628b1
AS
6585 return -EINVAL;
6586 }
6587 if (meta->map_ptr) {
6588 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6589 return -EFAULT;
6590 }
3e8ce298 6591 meta->map_uid = reg->map_uid;
b00628b1
AS
6592 meta->map_ptr = map;
6593 return 0;
6594}
6595
c0a5a21c
KKD
6596static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6597 struct bpf_call_arg_meta *meta)
6598{
6599 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
c0a5a21c 6600 struct bpf_map *map_ptr = reg->map_ptr;
aa3496ac 6601 struct btf_field *kptr_field;
c0a5a21c 6602 u32 kptr_off;
c0a5a21c
KKD
6603
6604 if (!tnum_is_const(reg->var_off)) {
6605 verbose(env,
6606 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6607 regno);
6608 return -EINVAL;
6609 }
6610 if (!map_ptr->btf) {
6611 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6612 map_ptr->name);
6613 return -EINVAL;
6614 }
aa3496ac
KKD
6615 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6616 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
c0a5a21c
KKD
6617 return -EINVAL;
6618 }
6619
6620 meta->map_ptr = map_ptr;
6621 kptr_off = reg->off + reg->var_off.value;
aa3496ac
KKD
6622 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6623 if (!kptr_field) {
c0a5a21c
KKD
6624 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6625 return -EACCES;
6626 }
aa3496ac 6627 if (kptr_field->type != BPF_KPTR_REF) {
c0a5a21c
KKD
6628 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6629 return -EACCES;
6630 }
aa3496ac 6631 meta->kptr_field = kptr_field;
c0a5a21c
KKD
6632 return 0;
6633}
6634
27060531
KKD
6635/* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6636 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6637 *
6638 * In both cases we deal with the first 8 bytes, but need to mark the next 8
6639 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6640 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6641 *
6642 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6643 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6644 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6645 * mutate the view of the dynptr and also possibly destroy it. In the latter
6646 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6647 * memory that dynptr points to.
6648 *
6649 * The verifier will keep track both levels of mutation (bpf_dynptr's in
6650 * reg->type and the memory's in reg->dynptr.type), but there is no support for
6651 * readonly dynptr view yet, hence only the first case is tracked and checked.
6652 *
6653 * This is consistent with how C applies the const modifier to a struct object,
6654 * where the pointer itself inside bpf_dynptr becomes const but not what it
6655 * points to.
6656 *
6657 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6658 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6659 */
1d18feb2
JK
6660static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6661 enum bpf_arg_type arg_type)
6b75bd3d
KKD
6662{
6663 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1d18feb2 6664 int err;
6b75bd3d 6665
27060531
KKD
6666 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6667 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6668 */
6669 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6670 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6671 return -EFAULT;
6672 }
79168a66 6673
27060531
KKD
6674 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
6675 * constructing a mutable bpf_dynptr object.
6676 *
6677 * Currently, this is only possible with PTR_TO_STACK
6678 * pointing to a region of at least 16 bytes which doesn't
6679 * contain an existing bpf_dynptr.
6680 *
6681 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6682 * mutated or destroyed. However, the memory it points to
6683 * may be mutated.
6684 *
6685 * None - Points to a initialized dynptr that can be mutated and
6686 * destroyed, including mutation of the memory it points
6687 * to.
6b75bd3d 6688 */
6b75bd3d 6689 if (arg_type & MEM_UNINIT) {
1d18feb2
JK
6690 int i;
6691
7e0dac28 6692 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6b75bd3d
KKD
6693 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6694 return -EINVAL;
6695 }
6696
1d18feb2
JK
6697 /* we write BPF_DW bits (8 bytes) at a time */
6698 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6699 err = check_mem_access(env, insn_idx, regno,
6700 i, BPF_DW, BPF_WRITE, -1, false);
6701 if (err)
6702 return err;
6b75bd3d
KKD
6703 }
6704
1d18feb2 6705 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
27060531
KKD
6706 } else /* MEM_RDONLY and None case from above */ {
6707 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6708 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6709 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6710 return -EINVAL;
6711 }
6712
7e0dac28 6713 if (!is_dynptr_reg_valid_init(env, reg)) {
6b75bd3d
KKD
6714 verbose(env,
6715 "Expected an initialized dynptr as arg #%d\n",
6716 regno);
6717 return -EINVAL;
6718 }
6719
27060531
KKD
6720 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6721 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6b75bd3d
KKD
6722 verbose(env,
6723 "Expected a dynptr of type %s as arg #%d\n",
d54e0f6c 6724 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6b75bd3d
KKD
6725 return -EINVAL;
6726 }
d6fefa11
KKD
6727
6728 err = mark_dynptr_read(env, reg);
6b75bd3d 6729 }
1d18feb2 6730 return err;
6b75bd3d
KKD
6731}
6732
06accc87
AN
6733static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
6734{
6735 struct bpf_func_state *state = func(env, reg);
6736
6737 return state->stack[spi].spilled_ptr.ref_obj_id;
6738}
6739
6740static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6741{
6742 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
6743}
6744
6745static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6746{
6747 return meta->kfunc_flags & KF_ITER_NEW;
6748}
6749
6750static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6751{
6752 return meta->kfunc_flags & KF_ITER_NEXT;
6753}
6754
6755static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6756{
6757 return meta->kfunc_flags & KF_ITER_DESTROY;
6758}
6759
6760static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
6761{
6762 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
6763 * kfunc is iter state pointer
6764 */
6765 return arg == 0 && is_iter_kfunc(meta);
6766}
6767
6768static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
6769 struct bpf_kfunc_call_arg_meta *meta)
6770{
6771 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6772 const struct btf_type *t;
6773 const struct btf_param *arg;
6774 int spi, err, i, nr_slots;
6775 u32 btf_id;
6776
6777 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
6778 arg = &btf_params(meta->func_proto)[0];
6779 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
6780 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
6781 nr_slots = t->size / BPF_REG_SIZE;
6782
06accc87
AN
6783 if (is_iter_new_kfunc(meta)) {
6784 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
6785 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
6786 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
6787 iter_type_str(meta->btf, btf_id), regno);
6788 return -EINVAL;
6789 }
6790
6791 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
6792 err = check_mem_access(env, insn_idx, regno,
6793 i, BPF_DW, BPF_WRITE, -1, false);
6794 if (err)
6795 return err;
6796 }
6797
6798 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
6799 if (err)
6800 return err;
6801 } else {
6802 /* iter_next() or iter_destroy() expect initialized iter state*/
6803 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
6804 verbose(env, "expected an initialized iter_%s as arg #%d\n",
6805 iter_type_str(meta->btf, btf_id), regno);
6806 return -EINVAL;
6807 }
6808
b63cbc49
AN
6809 spi = iter_get_spi(env, reg, nr_slots);
6810 if (spi < 0)
6811 return spi;
6812
06accc87
AN
6813 err = mark_iter_read(env, reg, spi, nr_slots);
6814 if (err)
6815 return err;
6816
b63cbc49
AN
6817 /* remember meta->iter info for process_iter_next_call() */
6818 meta->iter.spi = spi;
6819 meta->iter.frameno = reg->frameno;
06accc87
AN
6820 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
6821
6822 if (is_iter_destroy_kfunc(meta)) {
6823 err = unmark_stack_slots_iter(env, reg, nr_slots);
6824 if (err)
6825 return err;
6826 }
6827 }
6828
6829 return 0;
6830}
6831
6832/* process_iter_next_call() is called when verifier gets to iterator's next
6833 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
6834 * to it as just "iter_next()" in comments below.
6835 *
6836 * BPF verifier relies on a crucial contract for any iter_next()
6837 * implementation: it should *eventually* return NULL, and once that happens
6838 * it should keep returning NULL. That is, once iterator exhausts elements to
6839 * iterate, it should never reset or spuriously return new elements.
6840 *
6841 * With the assumption of such contract, process_iter_next_call() simulates
6842 * a fork in the verifier state to validate loop logic correctness and safety
6843 * without having to simulate infinite amount of iterations.
6844 *
6845 * In current state, we first assume that iter_next() returned NULL and
6846 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
6847 * conditions we should not form an infinite loop and should eventually reach
6848 * exit.
6849 *
6850 * Besides that, we also fork current state and enqueue it for later
6851 * verification. In a forked state we keep iterator state as ACTIVE
6852 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
6853 * also bump iteration depth to prevent erroneous infinite loop detection
6854 * later on (see iter_active_depths_differ() comment for details). In this
6855 * state we assume that we'll eventually loop back to another iter_next()
6856 * calls (it could be in exactly same location or in some other instruction,
6857 * it doesn't matter, we don't make any unnecessary assumptions about this,
6858 * everything revolves around iterator state in a stack slot, not which
6859 * instruction is calling iter_next()). When that happens, we either will come
6860 * to iter_next() with equivalent state and can conclude that next iteration
6861 * will proceed in exactly the same way as we just verified, so it's safe to
6862 * assume that loop converges. If not, we'll go on another iteration
6863 * simulation with a different input state, until all possible starting states
6864 * are validated or we reach maximum number of instructions limit.
6865 *
6866 * This way, we will either exhaustively discover all possible input states
6867 * that iterator loop can start with and eventually will converge, or we'll
6868 * effectively regress into bounded loop simulation logic and either reach
6869 * maximum number of instructions if loop is not provably convergent, or there
6870 * is some statically known limit on number of iterations (e.g., if there is
6871 * an explicit `if n > 100 then break;` statement somewhere in the loop).
6872 *
6873 * One very subtle but very important aspect is that we *always* simulate NULL
6874 * condition first (as the current state) before we simulate non-NULL case.
6875 * This has to do with intricacies of scalar precision tracking. By simulating
6876 * "exit condition" of iter_next() returning NULL first, we make sure all the
6877 * relevant precision marks *that will be set **after** we exit iterator loop*
6878 * are propagated backwards to common parent state of NULL and non-NULL
6879 * branches. Thanks to that, state equivalence checks done later in forked
6880 * state, when reaching iter_next() for ACTIVE iterator, can assume that
6881 * precision marks are finalized and won't change. Because simulating another
6882 * ACTIVE iterator iteration won't change them (because given same input
6883 * states we'll end up with exactly same output states which we are currently
6884 * comparing; and verification after the loop already propagated back what
6885 * needs to be **additionally** tracked as precise). It's subtle, grok
6886 * precision tracking for more intuitive understanding.
6887 */
6888static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
6889 struct bpf_kfunc_call_arg_meta *meta)
6890{
6891 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
6892 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
6893 struct bpf_reg_state *cur_iter, *queued_iter;
6894 int iter_frameno = meta->iter.frameno;
6895 int iter_spi = meta->iter.spi;
6896
6897 BTF_TYPE_EMIT(struct bpf_iter);
6898
6899 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6900
6901 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
6902 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
6903 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
6904 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
6905 return -EFAULT;
6906 }
6907
6908 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
6909 /* branch out active iter state */
6910 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
6911 if (!queued_st)
6912 return -ENOMEM;
6913
6914 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6915 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
6916 queued_iter->iter.depth++;
6917
6918 queued_fr = queued_st->frame[queued_st->curframe];
6919 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
6920 }
6921
6922 /* switch to DRAINED state, but keep the depth unchanged */
6923 /* mark current iter state as drained and assume returned NULL */
6924 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
6925 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
6926
6927 return 0;
6928}
6929
90133415
DB
6930static bool arg_type_is_mem_size(enum bpf_arg_type type)
6931{
6932 return type == ARG_CONST_SIZE ||
6933 type == ARG_CONST_SIZE_OR_ZERO;
6934}
6935
8f14852e
KKD
6936static bool arg_type_is_release(enum bpf_arg_type type)
6937{
6938 return type & OBJ_RELEASE;
6939}
6940
97e03f52
JK
6941static bool arg_type_is_dynptr(enum bpf_arg_type type)
6942{
6943 return base_type(type) == ARG_PTR_TO_DYNPTR;
6944}
6945
57c3bb72
AI
6946static int int_ptr_type_to_size(enum bpf_arg_type type)
6947{
6948 if (type == ARG_PTR_TO_INT)
6949 return sizeof(u32);
6950 else if (type == ARG_PTR_TO_LONG)
6951 return sizeof(u64);
6952
6953 return -EINVAL;
6954}
6955
912f442c
LB
6956static int resolve_map_arg_type(struct bpf_verifier_env *env,
6957 const struct bpf_call_arg_meta *meta,
6958 enum bpf_arg_type *arg_type)
6959{
6960 if (!meta->map_ptr) {
6961 /* kernel subsystem misconfigured verifier */
6962 verbose(env, "invalid map_ptr to access map->type\n");
6963 return -EACCES;
6964 }
6965
6966 switch (meta->map_ptr->map_type) {
6967 case BPF_MAP_TYPE_SOCKMAP:
6968 case BPF_MAP_TYPE_SOCKHASH:
6969 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 6970 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
6971 } else {
6972 verbose(env, "invalid arg_type for sockmap/sockhash\n");
6973 return -EINVAL;
6974 }
6975 break;
9330986c
JK
6976 case BPF_MAP_TYPE_BLOOM_FILTER:
6977 if (meta->func_id == BPF_FUNC_map_peek_elem)
6978 *arg_type = ARG_PTR_TO_MAP_VALUE;
6979 break;
912f442c
LB
6980 default:
6981 break;
6982 }
6983 return 0;
6984}
6985
f79e7ea5
LB
6986struct bpf_reg_types {
6987 const enum bpf_reg_type types[10];
1df8f55a 6988 u32 *btf_id;
f79e7ea5
LB
6989};
6990
f79e7ea5
LB
6991static const struct bpf_reg_types sock_types = {
6992 .types = {
6993 PTR_TO_SOCK_COMMON,
6994 PTR_TO_SOCKET,
6995 PTR_TO_TCP_SOCK,
6996 PTR_TO_XDP_SOCK,
6997 },
6998};
6999
49a2a4d4 7000#ifdef CONFIG_NET
1df8f55a
MKL
7001static const struct bpf_reg_types btf_id_sock_common_types = {
7002 .types = {
7003 PTR_TO_SOCK_COMMON,
7004 PTR_TO_SOCKET,
7005 PTR_TO_TCP_SOCK,
7006 PTR_TO_XDP_SOCK,
7007 PTR_TO_BTF_ID,
3f00c523 7008 PTR_TO_BTF_ID | PTR_TRUSTED,
1df8f55a
MKL
7009 },
7010 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7011};
49a2a4d4 7012#endif
1df8f55a 7013
f79e7ea5
LB
7014static const struct bpf_reg_types mem_types = {
7015 .types = {
7016 PTR_TO_STACK,
7017 PTR_TO_PACKET,
7018 PTR_TO_PACKET_META,
69c087ba 7019 PTR_TO_MAP_KEY,
f79e7ea5
LB
7020 PTR_TO_MAP_VALUE,
7021 PTR_TO_MEM,
894f2a8b 7022 PTR_TO_MEM | MEM_RINGBUF,
20b2aff4 7023 PTR_TO_BUF,
3e30be42 7024 PTR_TO_BTF_ID | PTR_TRUSTED,
f79e7ea5
LB
7025 },
7026};
7027
7028static const struct bpf_reg_types int_ptr_types = {
7029 .types = {
7030 PTR_TO_STACK,
7031 PTR_TO_PACKET,
7032 PTR_TO_PACKET_META,
69c087ba 7033 PTR_TO_MAP_KEY,
f79e7ea5
LB
7034 PTR_TO_MAP_VALUE,
7035 },
7036};
7037
4e814da0
KKD
7038static const struct bpf_reg_types spin_lock_types = {
7039 .types = {
7040 PTR_TO_MAP_VALUE,
7041 PTR_TO_BTF_ID | MEM_ALLOC,
7042 }
7043};
7044
f79e7ea5
LB
7045static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7046static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7047static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
894f2a8b 7048static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
f79e7ea5 7049static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
3f00c523
DV
7050static const struct bpf_reg_types btf_ptr_types = {
7051 .types = {
7052 PTR_TO_BTF_ID,
7053 PTR_TO_BTF_ID | PTR_TRUSTED,
fca1aa75 7054 PTR_TO_BTF_ID | MEM_RCU,
3f00c523
DV
7055 },
7056};
7057static const struct bpf_reg_types percpu_btf_ptr_types = {
7058 .types = {
7059 PTR_TO_BTF_ID | MEM_PERCPU,
7060 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7061 }
7062};
69c087ba
YS
7063static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7064static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 7065static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
b00628b1 7066static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
c0a5a21c 7067static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
20571567
DV
7068static const struct bpf_reg_types dynptr_types = {
7069 .types = {
7070 PTR_TO_STACK,
27060531 7071 CONST_PTR_TO_DYNPTR,
20571567
DV
7072 }
7073};
f79e7ea5 7074
0789e13b 7075static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
d1673304
DM
7076 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7077 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
f79e7ea5
LB
7078 [ARG_CONST_SIZE] = &scalar_types,
7079 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7080 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7081 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7082 [ARG_PTR_TO_CTX] = &context_types,
f79e7ea5 7083 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 7084#ifdef CONFIG_NET
1df8f55a 7085 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 7086#endif
f79e7ea5 7087 [ARG_PTR_TO_SOCKET] = &fullsock_types,
f79e7ea5
LB
7088 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7089 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7090 [ARG_PTR_TO_MEM] = &mem_types,
894f2a8b 7091 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
f79e7ea5
LB
7092 [ARG_PTR_TO_INT] = &int_ptr_types,
7093 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 7094 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba 7095 [ARG_PTR_TO_FUNC] = &func_ptr_types,
48946bd6 7096 [ARG_PTR_TO_STACK] = &stack_ptr_types,
fff13c4b 7097 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
b00628b1 7098 [ARG_PTR_TO_TIMER] = &timer_types,
c0a5a21c 7099 [ARG_PTR_TO_KPTR] = &kptr_types,
20571567 7100 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
f79e7ea5
LB
7101};
7102
7103static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2 7104 enum bpf_arg_type arg_type,
c0a5a21c
KKD
7105 const u32 *arg_btf_id,
7106 struct bpf_call_arg_meta *meta)
f79e7ea5
LB
7107{
7108 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7109 enum bpf_reg_type expected, type = reg->type;
a968d5e2 7110 const struct bpf_reg_types *compatible;
f79e7ea5
LB
7111 int i, j;
7112
48946bd6 7113 compatible = compatible_reg_types[base_type(arg_type)];
a968d5e2
MKL
7114 if (!compatible) {
7115 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7116 return -EFAULT;
7117 }
7118
216e3cd2
HL
7119 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7120 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7121 *
7122 * Same for MAYBE_NULL:
7123 *
7124 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7125 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7126 *
7127 * Therefore we fold these flags depending on the arg_type before comparison.
7128 */
7129 if (arg_type & MEM_RDONLY)
7130 type &= ~MEM_RDONLY;
7131 if (arg_type & PTR_MAYBE_NULL)
7132 type &= ~PTR_MAYBE_NULL;
7133
738c96d5
DM
7134 if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7135 type &= ~MEM_ALLOC;
7136
f79e7ea5
LB
7137 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7138 expected = compatible->types[i];
7139 if (expected == NOT_INIT)
7140 break;
7141
7142 if (type == expected)
a968d5e2 7143 goto found;
f79e7ea5
LB
7144 }
7145
216e3cd2 7146 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
f79e7ea5 7147 for (j = 0; j + 1 < i; j++)
c25b2ae1
HL
7148 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7149 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
f79e7ea5 7150 return -EACCES;
a968d5e2
MKL
7151
7152found:
da03e43a
KKD
7153 if (base_type(reg->type) != PTR_TO_BTF_ID)
7154 return 0;
7155
3e30be42
AS
7156 if (compatible == &mem_types) {
7157 if (!(arg_type & MEM_RDONLY)) {
7158 verbose(env,
7159 "%s() may write into memory pointed by R%d type=%s\n",
7160 func_id_name(meta->func_id),
7161 regno, reg_type_str(env, reg->type));
7162 return -EACCES;
7163 }
7164 return 0;
7165 }
7166
da03e43a
KKD
7167 switch ((int)reg->type) {
7168 case PTR_TO_BTF_ID:
7169 case PTR_TO_BTF_ID | PTR_TRUSTED:
7170 case PTR_TO_BTF_ID | MEM_RCU:
add68b84
AS
7171 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7172 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
da03e43a 7173 {
2ab3b380
KKD
7174 /* For bpf_sk_release, it needs to match against first member
7175 * 'struct sock_common', hence make an exception for it. This
7176 * allows bpf_sk_release to work for multiple socket types.
7177 */
7178 bool strict_type_match = arg_type_is_release(arg_type) &&
7179 meta->func_id != BPF_FUNC_sk_release;
7180
add68b84
AS
7181 if (type_may_be_null(reg->type) &&
7182 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7183 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7184 return -EACCES;
7185 }
7186
1df8f55a
MKL
7187 if (!arg_btf_id) {
7188 if (!compatible->btf_id) {
7189 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7190 return -EFAULT;
7191 }
7192 arg_btf_id = compatible->btf_id;
7193 }
7194
c0a5a21c 7195 if (meta->func_id == BPF_FUNC_kptr_xchg) {
aa3496ac 7196 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
c0a5a21c 7197 return -EACCES;
47e34cb7
DM
7198 } else {
7199 if (arg_btf_id == BPF_PTR_POISON) {
7200 verbose(env, "verifier internal error:");
7201 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7202 regno);
7203 return -EACCES;
7204 }
7205
7206 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7207 btf_vmlinux, *arg_btf_id,
7208 strict_type_match)) {
7209 verbose(env, "R%d is of type %s but %s is expected\n",
b32a5dae
DM
7210 regno, btf_type_name(reg->btf, reg->btf_id),
7211 btf_type_name(btf_vmlinux, *arg_btf_id));
47e34cb7
DM
7212 return -EACCES;
7213 }
a968d5e2 7214 }
da03e43a
KKD
7215 break;
7216 }
7217 case PTR_TO_BTF_ID | MEM_ALLOC:
738c96d5
DM
7218 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7219 meta->func_id != BPF_FUNC_kptr_xchg) {
4e814da0
KKD
7220 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7221 return -EFAULT;
7222 }
da03e43a
KKD
7223 /* Handled by helper specific checks */
7224 break;
7225 case PTR_TO_BTF_ID | MEM_PERCPU:
7226 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7227 /* Handled by helper specific checks */
7228 break;
7229 default:
7230 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7231 return -EFAULT;
a968d5e2 7232 }
a968d5e2 7233 return 0;
f79e7ea5
LB
7234}
7235
6a3cd331
DM
7236static struct btf_field *
7237reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7238{
7239 struct btf_field *field;
7240 struct btf_record *rec;
7241
7242 rec = reg_btf_record(reg);
7243 if (!rec)
7244 return NULL;
7245
7246 field = btf_record_find(rec, off, fields);
7247 if (!field)
7248 return NULL;
7249
7250 return field;
7251}
7252
25b35dd2
KKD
7253int check_func_arg_reg_off(struct bpf_verifier_env *env,
7254 const struct bpf_reg_state *reg, int regno,
8f14852e 7255 enum bpf_arg_type arg_type)
25b35dd2 7256{
184c9bdb 7257 u32 type = reg->type;
25b35dd2 7258
184c9bdb
KKD
7259 /* When referenced register is passed to release function, its fixed
7260 * offset must be 0.
7261 *
7262 * We will check arg_type_is_release reg has ref_obj_id when storing
7263 * meta->release_regno.
7264 */
7265 if (arg_type_is_release(arg_type)) {
7266 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7267 * may not directly point to the object being released, but to
7268 * dynptr pointing to such object, which might be at some offset
7269 * on the stack. In that case, we simply to fallback to the
7270 * default handling.
7271 */
7272 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7273 return 0;
6a3cd331
DM
7274
7275 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7276 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7277 return __check_ptr_off_reg(env, reg, regno, true);
7278
7279 verbose(env, "R%d must have zero offset when passed to release func\n",
7280 regno);
7281 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
b32a5dae 7282 btf_type_name(reg->btf, reg->btf_id), reg->off);
6a3cd331
DM
7283 return -EINVAL;
7284 }
7285
184c9bdb
KKD
7286 /* Doing check_ptr_off_reg check for the offset will catch this
7287 * because fixed_off_ok is false, but checking here allows us
7288 * to give the user a better error message.
7289 */
7290 if (reg->off) {
7291 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7292 regno);
7293 return -EINVAL;
7294 }
7295 return __check_ptr_off_reg(env, reg, regno, false);
7296 }
7297
7298 switch (type) {
7299 /* Pointer types where both fixed and variable offset is explicitly allowed: */
97e03f52 7300 case PTR_TO_STACK:
25b35dd2
KKD
7301 case PTR_TO_PACKET:
7302 case PTR_TO_PACKET_META:
7303 case PTR_TO_MAP_KEY:
7304 case PTR_TO_MAP_VALUE:
7305 case PTR_TO_MEM:
7306 case PTR_TO_MEM | MEM_RDONLY:
894f2a8b 7307 case PTR_TO_MEM | MEM_RINGBUF:
25b35dd2
KKD
7308 case PTR_TO_BUF:
7309 case PTR_TO_BUF | MEM_RDONLY:
97e03f52 7310 case SCALAR_VALUE:
184c9bdb 7311 return 0;
25b35dd2
KKD
7312 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7313 * fixed offset.
7314 */
7315 case PTR_TO_BTF_ID:
282de143 7316 case PTR_TO_BTF_ID | MEM_ALLOC:
3f00c523 7317 case PTR_TO_BTF_ID | PTR_TRUSTED:
fca1aa75 7318 case PTR_TO_BTF_ID | MEM_RCU:
6a3cd331 7319 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
24d5bb80 7320 /* When referenced PTR_TO_BTF_ID is passed to release function,
184c9bdb
KKD
7321 * its fixed offset must be 0. In the other cases, fixed offset
7322 * can be non-zero. This was already checked above. So pass
7323 * fixed_off_ok as true to allow fixed offset for all other
7324 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7325 * still need to do checks instead of returning.
24d5bb80 7326 */
184c9bdb 7327 return __check_ptr_off_reg(env, reg, regno, true);
25b35dd2 7328 default:
184c9bdb 7329 return __check_ptr_off_reg(env, reg, regno, false);
25b35dd2 7330 }
25b35dd2
KKD
7331}
7332
485ec51e
JK
7333static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7334 const struct bpf_func_proto *fn,
7335 struct bpf_reg_state *regs)
7336{
7337 struct bpf_reg_state *state = NULL;
7338 int i;
7339
7340 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7341 if (arg_type_is_dynptr(fn->arg_type[i])) {
7342 if (state) {
7343 verbose(env, "verifier internal error: multiple dynptr args\n");
7344 return NULL;
7345 }
7346 state = &regs[BPF_REG_1 + i];
7347 }
7348
7349 if (!state)
7350 verbose(env, "verifier internal error: no dynptr arg found\n");
7351
7352 return state;
7353}
7354
f8064ab9 7355static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
34d4ef57
JK
7356{
7357 struct bpf_func_state *state = func(env, reg);
27060531 7358 int spi;
34d4ef57 7359
27060531 7360 if (reg->type == CONST_PTR_TO_DYNPTR)
f8064ab9
KKD
7361 return reg->id;
7362 spi = dynptr_get_spi(env, reg);
7363 if (spi < 0)
7364 return spi;
7365 return state->stack[spi].spilled_ptr.id;
7366}
7367
79168a66 7368static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
34d4ef57
JK
7369{
7370 struct bpf_func_state *state = func(env, reg);
27060531 7371 int spi;
27060531 7372
27060531
KKD
7373 if (reg->type == CONST_PTR_TO_DYNPTR)
7374 return reg->ref_obj_id;
79168a66
KKD
7375 spi = dynptr_get_spi(env, reg);
7376 if (spi < 0)
7377 return spi;
27060531 7378 return state->stack[spi].spilled_ptr.ref_obj_id;
34d4ef57
JK
7379}
7380
b5964b96
JK
7381static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7382 struct bpf_reg_state *reg)
7383{
7384 struct bpf_func_state *state = func(env, reg);
7385 int spi;
7386
7387 if (reg->type == CONST_PTR_TO_DYNPTR)
7388 return reg->dynptr.type;
7389
7390 spi = __get_spi(reg->off);
7391 if (spi < 0) {
7392 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7393 return BPF_DYNPTR_TYPE_INVALID;
7394 }
7395
7396 return state->stack[spi].spilled_ptr.dynptr.type;
7397}
7398
af7ec138
YS
7399static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7400 struct bpf_call_arg_meta *meta,
1d18feb2
JK
7401 const struct bpf_func_proto *fn,
7402 int insn_idx)
17a52670 7403{
af7ec138 7404 u32 regno = BPF_REG_1 + arg;
638f5b90 7405 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 7406 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 7407 enum bpf_reg_type type = reg->type;
508362ac 7408 u32 *arg_btf_id = NULL;
17a52670
AS
7409 int err = 0;
7410
80f1d68c 7411 if (arg_type == ARG_DONTCARE)
17a52670
AS
7412 return 0;
7413
dc503a8a
EC
7414 err = check_reg_arg(env, regno, SRC_OP);
7415 if (err)
7416 return err;
17a52670 7417
1be7f75d
AS
7418 if (arg_type == ARG_ANYTHING) {
7419 if (is_pointer_value(env, regno)) {
61bd5218
JK
7420 verbose(env, "R%d leaks addr into helper function\n",
7421 regno);
1be7f75d
AS
7422 return -EACCES;
7423 }
80f1d68c 7424 return 0;
1be7f75d 7425 }
80f1d68c 7426
de8f3a83 7427 if (type_is_pkt_pointer(type) &&
3a0af8fd 7428 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 7429 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
7430 return -EACCES;
7431 }
7432
16d1e00c 7433 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
912f442c
LB
7434 err = resolve_map_arg_type(env, meta, &arg_type);
7435 if (err)
7436 return err;
7437 }
7438
48946bd6 7439 if (register_is_null(reg) && type_may_be_null(arg_type))
fd1b0d60
LB
7440 /* A NULL register has a SCALAR_VALUE type, so skip
7441 * type checking.
7442 */
7443 goto skip_type_check;
7444
508362ac 7445 /* arg_btf_id and arg_size are in a union. */
4e814da0
KKD
7446 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7447 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
508362ac
MM
7448 arg_btf_id = fn->arg_btf_id[arg];
7449
7450 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
f79e7ea5
LB
7451 if (err)
7452 return err;
7453
8f14852e 7454 err = check_func_arg_reg_off(env, reg, regno, arg_type);
25b35dd2
KKD
7455 if (err)
7456 return err;
d7b9454a 7457
fd1b0d60 7458skip_type_check:
8f14852e 7459 if (arg_type_is_release(arg_type)) {
bc34dee6
JK
7460 if (arg_type_is_dynptr(arg_type)) {
7461 struct bpf_func_state *state = func(env, reg);
27060531 7462 int spi;
bc34dee6 7463
27060531
KKD
7464 /* Only dynptr created on stack can be released, thus
7465 * the get_spi and stack state checks for spilled_ptr
7466 * should only be done before process_dynptr_func for
7467 * PTR_TO_STACK.
7468 */
7469 if (reg->type == PTR_TO_STACK) {
79168a66 7470 spi = dynptr_get_spi(env, reg);
f5b625e5 7471 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
27060531
KKD
7472 verbose(env, "arg %d is an unacquired reference\n", regno);
7473 return -EINVAL;
7474 }
7475 } else {
7476 verbose(env, "cannot release unowned const bpf_dynptr\n");
bc34dee6
JK
7477 return -EINVAL;
7478 }
7479 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8f14852e
KKD
7480 verbose(env, "R%d must be referenced when passed to release function\n",
7481 regno);
7482 return -EINVAL;
7483 }
7484 if (meta->release_regno) {
7485 verbose(env, "verifier internal error: more than one release argument\n");
7486 return -EFAULT;
7487 }
7488 meta->release_regno = regno;
7489 }
7490
02f7c958 7491 if (reg->ref_obj_id) {
457f4436
AN
7492 if (meta->ref_obj_id) {
7493 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7494 regno, reg->ref_obj_id,
7495 meta->ref_obj_id);
7496 return -EFAULT;
7497 }
7498 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
7499 }
7500
8ab4cdcf
JK
7501 switch (base_type(arg_type)) {
7502 case ARG_CONST_MAP_PTR:
17a52670 7503 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3e8ce298
AS
7504 if (meta->map_ptr) {
7505 /* Use map_uid (which is unique id of inner map) to reject:
7506 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7507 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7508 * if (inner_map1 && inner_map2) {
7509 * timer = bpf_map_lookup_elem(inner_map1);
7510 * if (timer)
7511 * // mismatch would have been allowed
7512 * bpf_timer_init(timer, inner_map2);
7513 * }
7514 *
7515 * Comparing map_ptr is enough to distinguish normal and outer maps.
7516 */
7517 if (meta->map_ptr != reg->map_ptr ||
7518 meta->map_uid != reg->map_uid) {
7519 verbose(env,
7520 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7521 meta->map_uid, reg->map_uid);
7522 return -EINVAL;
7523 }
b00628b1 7524 }
33ff9823 7525 meta->map_ptr = reg->map_ptr;
3e8ce298 7526 meta->map_uid = reg->map_uid;
8ab4cdcf
JK
7527 break;
7528 case ARG_PTR_TO_MAP_KEY:
17a52670
AS
7529 /* bpf_map_xxx(..., map_ptr, ..., key) call:
7530 * check that [key, key + map->key_size) are within
7531 * stack limits and initialized
7532 */
33ff9823 7533 if (!meta->map_ptr) {
17a52670
AS
7534 /* in function declaration map_ptr must come before
7535 * map_key, so that it's verified and known before
7536 * we have to check map_key here. Otherwise it means
7537 * that kernel subsystem misconfigured verifier
7538 */
61bd5218 7539 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
7540 return -EACCES;
7541 }
d71962f3
PC
7542 err = check_helper_mem_access(env, regno,
7543 meta->map_ptr->key_size, false,
7544 NULL);
8ab4cdcf
JK
7545 break;
7546 case ARG_PTR_TO_MAP_VALUE:
48946bd6
HL
7547 if (type_may_be_null(arg_type) && register_is_null(reg))
7548 return 0;
7549
17a52670
AS
7550 /* bpf_map_xxx(..., map_ptr, ..., value) call:
7551 * check [value, value + map->value_size) validity
7552 */
33ff9823 7553 if (!meta->map_ptr) {
17a52670 7554 /* kernel subsystem misconfigured verifier */
61bd5218 7555 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
7556 return -EACCES;
7557 }
16d1e00c 7558 meta->raw_mode = arg_type & MEM_UNINIT;
d71962f3
PC
7559 err = check_helper_mem_access(env, regno,
7560 meta->map_ptr->value_size, false,
2ea864c5 7561 meta);
8ab4cdcf
JK
7562 break;
7563 case ARG_PTR_TO_PERCPU_BTF_ID:
eaa6bcb7
HL
7564 if (!reg->btf_id) {
7565 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7566 return -EACCES;
7567 }
22dc4a0f 7568 meta->ret_btf = reg->btf;
eaa6bcb7 7569 meta->ret_btf_id = reg->btf_id;
8ab4cdcf
JK
7570 break;
7571 case ARG_PTR_TO_SPIN_LOCK:
5d92ddc3
DM
7572 if (in_rbtree_lock_required_cb(env)) {
7573 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7574 return -EACCES;
7575 }
c18f0b6a 7576 if (meta->func_id == BPF_FUNC_spin_lock) {
ac50fe51
KKD
7577 err = process_spin_lock(env, regno, true);
7578 if (err)
7579 return err;
c18f0b6a 7580 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
ac50fe51
KKD
7581 err = process_spin_lock(env, regno, false);
7582 if (err)
7583 return err;
c18f0b6a
LB
7584 } else {
7585 verbose(env, "verifier internal error\n");
7586 return -EFAULT;
7587 }
8ab4cdcf
JK
7588 break;
7589 case ARG_PTR_TO_TIMER:
ac50fe51
KKD
7590 err = process_timer_func(env, regno, meta);
7591 if (err)
7592 return err;
8ab4cdcf
JK
7593 break;
7594 case ARG_PTR_TO_FUNC:
69c087ba 7595 meta->subprogno = reg->subprogno;
8ab4cdcf
JK
7596 break;
7597 case ARG_PTR_TO_MEM:
a2bbe7cc
LB
7598 /* The access to this pointer is only checked when we hit the
7599 * next is_mem_size argument below.
7600 */
16d1e00c 7601 meta->raw_mode = arg_type & MEM_UNINIT;
508362ac
MM
7602 if (arg_type & MEM_FIXED_SIZE) {
7603 err = check_helper_mem_access(env, regno,
7604 fn->arg_size[arg], false,
7605 meta);
7606 }
8ab4cdcf
JK
7607 break;
7608 case ARG_CONST_SIZE:
7609 err = check_mem_size_reg(env, reg, regno, false, meta);
7610 break;
7611 case ARG_CONST_SIZE_OR_ZERO:
7612 err = check_mem_size_reg(env, reg, regno, true, meta);
7613 break;
7614 case ARG_PTR_TO_DYNPTR:
1d18feb2 7615 err = process_dynptr_func(env, regno, insn_idx, arg_type);
ac50fe51
KKD
7616 if (err)
7617 return err;
8ab4cdcf
JK
7618 break;
7619 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
457f4436 7620 if (!tnum_is_const(reg->var_off)) {
28a8add6 7621 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
7622 regno);
7623 return -EACCES;
7624 }
7625 meta->mem_size = reg->var_off.value;
2fc31465
KKD
7626 err = mark_chain_precision(env, regno);
7627 if (err)
7628 return err;
8ab4cdcf
JK
7629 break;
7630 case ARG_PTR_TO_INT:
7631 case ARG_PTR_TO_LONG:
7632 {
57c3bb72
AI
7633 int size = int_ptr_type_to_size(arg_type);
7634
7635 err = check_helper_mem_access(env, regno, size, false, meta);
7636 if (err)
7637 return err;
7638 err = check_ptr_alignment(env, reg, 0, size, true);
8ab4cdcf
JK
7639 break;
7640 }
7641 case ARG_PTR_TO_CONST_STR:
7642 {
fff13c4b
FR
7643 struct bpf_map *map = reg->map_ptr;
7644 int map_off;
7645 u64 map_addr;
7646 char *str_ptr;
7647
a8fad73e 7648 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
7649 verbose(env, "R%d does not point to a readonly map'\n", regno);
7650 return -EACCES;
7651 }
7652
7653 if (!tnum_is_const(reg->var_off)) {
7654 verbose(env, "R%d is not a constant address'\n", regno);
7655 return -EACCES;
7656 }
7657
7658 if (!map->ops->map_direct_value_addr) {
7659 verbose(env, "no direct value access support for this map type\n");
7660 return -EACCES;
7661 }
7662
7663 err = check_map_access(env, regno, reg->off,
61df10c7
KKD
7664 map->value_size - reg->off, false,
7665 ACCESS_HELPER);
fff13c4b
FR
7666 if (err)
7667 return err;
7668
7669 map_off = reg->off + reg->var_off.value;
7670 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7671 if (err) {
7672 verbose(env, "direct value access on string failed\n");
7673 return err;
7674 }
7675
7676 str_ptr = (char *)(long)(map_addr);
7677 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7678 verbose(env, "string is not zero-terminated\n");
7679 return -EINVAL;
7680 }
8ab4cdcf
JK
7681 break;
7682 }
7683 case ARG_PTR_TO_KPTR:
ac50fe51
KKD
7684 err = process_kptr_func(env, regno, meta);
7685 if (err)
7686 return err;
8ab4cdcf 7687 break;
17a52670
AS
7688 }
7689
7690 return err;
7691}
7692
0126240f
LB
7693static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7694{
7695 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 7696 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
7697
7698 if (func_id != BPF_FUNC_map_update_elem)
7699 return false;
7700
7701 /* It's not possible to get access to a locked struct sock in these
7702 * contexts, so updating is safe.
7703 */
7704 switch (type) {
7705 case BPF_PROG_TYPE_TRACING:
7706 if (eatype == BPF_TRACE_ITER)
7707 return true;
7708 break;
7709 case BPF_PROG_TYPE_SOCKET_FILTER:
7710 case BPF_PROG_TYPE_SCHED_CLS:
7711 case BPF_PROG_TYPE_SCHED_ACT:
7712 case BPF_PROG_TYPE_XDP:
7713 case BPF_PROG_TYPE_SK_REUSEPORT:
7714 case BPF_PROG_TYPE_FLOW_DISSECTOR:
7715 case BPF_PROG_TYPE_SK_LOOKUP:
7716 return true;
7717 default:
7718 break;
7719 }
7720
7721 verbose(env, "cannot update sockmap in this context\n");
7722 return false;
7723}
7724
e411901c
MF
7725static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7726{
95acd881
TA
7727 return env->prog->jit_requested &&
7728 bpf_jit_supports_subprog_tailcalls();
e411901c
MF
7729}
7730
61bd5218
JK
7731static int check_map_func_compatibility(struct bpf_verifier_env *env,
7732 struct bpf_map *map, int func_id)
35578d79 7733{
35578d79
KX
7734 if (!map)
7735 return 0;
7736
6aff67c8
AS
7737 /* We need a two way check, first is from map perspective ... */
7738 switch (map->map_type) {
7739 case BPF_MAP_TYPE_PROG_ARRAY:
7740 if (func_id != BPF_FUNC_tail_call)
7741 goto error;
7742 break;
7743 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7744 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 7745 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 7746 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
7747 func_id != BPF_FUNC_perf_event_read_value &&
7748 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
7749 goto error;
7750 break;
457f4436
AN
7751 case BPF_MAP_TYPE_RINGBUF:
7752 if (func_id != BPF_FUNC_ringbuf_output &&
7753 func_id != BPF_FUNC_ringbuf_reserve &&
bc34dee6
JK
7754 func_id != BPF_FUNC_ringbuf_query &&
7755 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7756 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7757 func_id != BPF_FUNC_ringbuf_discard_dynptr)
457f4436
AN
7758 goto error;
7759 break;
583c1f42 7760 case BPF_MAP_TYPE_USER_RINGBUF:
20571567
DV
7761 if (func_id != BPF_FUNC_user_ringbuf_drain)
7762 goto error;
7763 break;
6aff67c8
AS
7764 case BPF_MAP_TYPE_STACK_TRACE:
7765 if (func_id != BPF_FUNC_get_stackid)
7766 goto error;
7767 break;
4ed8ec52 7768 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 7769 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 7770 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
7771 goto error;
7772 break;
cd339431 7773 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 7774 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
7775 if (func_id != BPF_FUNC_get_local_storage)
7776 goto error;
7777 break;
546ac1ff 7778 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 7779 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
7780 if (func_id != BPF_FUNC_redirect_map &&
7781 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
7782 goto error;
7783 break;
fbfc504a
BT
7784 /* Restrict bpf side of cpumap and xskmap, open when use-cases
7785 * appear.
7786 */
6710e112
JDB
7787 case BPF_MAP_TYPE_CPUMAP:
7788 if (func_id != BPF_FUNC_redirect_map)
7789 goto error;
7790 break;
fada7fdc
JL
7791 case BPF_MAP_TYPE_XSKMAP:
7792 if (func_id != BPF_FUNC_redirect_map &&
7793 func_id != BPF_FUNC_map_lookup_elem)
7794 goto error;
7795 break;
56f668df 7796 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 7797 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
7798 if (func_id != BPF_FUNC_map_lookup_elem)
7799 goto error;
16a43625 7800 break;
174a79ff
JF
7801 case BPF_MAP_TYPE_SOCKMAP:
7802 if (func_id != BPF_FUNC_sk_redirect_map &&
7803 func_id != BPF_FUNC_sock_map_update &&
4f738adb 7804 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 7805 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 7806 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
7807 func_id != BPF_FUNC_map_lookup_elem &&
7808 !may_update_sockmap(env, func_id))
174a79ff
JF
7809 goto error;
7810 break;
81110384
JF
7811 case BPF_MAP_TYPE_SOCKHASH:
7812 if (func_id != BPF_FUNC_sk_redirect_hash &&
7813 func_id != BPF_FUNC_sock_hash_update &&
7814 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 7815 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 7816 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
7817 func_id != BPF_FUNC_map_lookup_elem &&
7818 !may_update_sockmap(env, func_id))
81110384
JF
7819 goto error;
7820 break;
2dbb9b9e
MKL
7821 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7822 if (func_id != BPF_FUNC_sk_select_reuseport)
7823 goto error;
7824 break;
f1a2e44a
MV
7825 case BPF_MAP_TYPE_QUEUE:
7826 case BPF_MAP_TYPE_STACK:
7827 if (func_id != BPF_FUNC_map_peek_elem &&
7828 func_id != BPF_FUNC_map_pop_elem &&
7829 func_id != BPF_FUNC_map_push_elem)
7830 goto error;
7831 break;
6ac99e8f
MKL
7832 case BPF_MAP_TYPE_SK_STORAGE:
7833 if (func_id != BPF_FUNC_sk_storage_get &&
9db44fdd
KKD
7834 func_id != BPF_FUNC_sk_storage_delete &&
7835 func_id != BPF_FUNC_kptr_xchg)
6ac99e8f
MKL
7836 goto error;
7837 break;
8ea63684
KS
7838 case BPF_MAP_TYPE_INODE_STORAGE:
7839 if (func_id != BPF_FUNC_inode_storage_get &&
9db44fdd
KKD
7840 func_id != BPF_FUNC_inode_storage_delete &&
7841 func_id != BPF_FUNC_kptr_xchg)
8ea63684
KS
7842 goto error;
7843 break;
4cf1bc1f
KS
7844 case BPF_MAP_TYPE_TASK_STORAGE:
7845 if (func_id != BPF_FUNC_task_storage_get &&
9db44fdd
KKD
7846 func_id != BPF_FUNC_task_storage_delete &&
7847 func_id != BPF_FUNC_kptr_xchg)
4cf1bc1f
KS
7848 goto error;
7849 break;
c4bcfb38
YS
7850 case BPF_MAP_TYPE_CGRP_STORAGE:
7851 if (func_id != BPF_FUNC_cgrp_storage_get &&
9db44fdd
KKD
7852 func_id != BPF_FUNC_cgrp_storage_delete &&
7853 func_id != BPF_FUNC_kptr_xchg)
c4bcfb38
YS
7854 goto error;
7855 break;
9330986c
JK
7856 case BPF_MAP_TYPE_BLOOM_FILTER:
7857 if (func_id != BPF_FUNC_map_peek_elem &&
7858 func_id != BPF_FUNC_map_push_elem)
7859 goto error;
7860 break;
6aff67c8
AS
7861 default:
7862 break;
7863 }
7864
7865 /* ... and second from the function itself. */
7866 switch (func_id) {
7867 case BPF_FUNC_tail_call:
7868 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7869 goto error;
e411901c
MF
7870 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7871 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
7872 return -EINVAL;
7873 }
6aff67c8
AS
7874 break;
7875 case BPF_FUNC_perf_event_read:
7876 case BPF_FUNC_perf_event_output:
908432ca 7877 case BPF_FUNC_perf_event_read_value:
a7658e1a 7878 case BPF_FUNC_skb_output:
d831ee84 7879 case BPF_FUNC_xdp_output:
6aff67c8
AS
7880 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7881 goto error;
7882 break;
5b029a32
DB
7883 case BPF_FUNC_ringbuf_output:
7884 case BPF_FUNC_ringbuf_reserve:
7885 case BPF_FUNC_ringbuf_query:
bc34dee6
JK
7886 case BPF_FUNC_ringbuf_reserve_dynptr:
7887 case BPF_FUNC_ringbuf_submit_dynptr:
7888 case BPF_FUNC_ringbuf_discard_dynptr:
5b029a32
DB
7889 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7890 goto error;
7891 break;
20571567
DV
7892 case BPF_FUNC_user_ringbuf_drain:
7893 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7894 goto error;
7895 break;
6aff67c8
AS
7896 case BPF_FUNC_get_stackid:
7897 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7898 goto error;
7899 break;
60d20f91 7900 case BPF_FUNC_current_task_under_cgroup:
747ea55e 7901 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
7902 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7903 goto error;
7904 break;
97f91a7c 7905 case BPF_FUNC_redirect_map:
9c270af3 7906 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 7907 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
7908 map->map_type != BPF_MAP_TYPE_CPUMAP &&
7909 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
7910 goto error;
7911 break;
174a79ff 7912 case BPF_FUNC_sk_redirect_map:
4f738adb 7913 case BPF_FUNC_msg_redirect_map:
81110384 7914 case BPF_FUNC_sock_map_update:
174a79ff
JF
7915 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7916 goto error;
7917 break;
81110384
JF
7918 case BPF_FUNC_sk_redirect_hash:
7919 case BPF_FUNC_msg_redirect_hash:
7920 case BPF_FUNC_sock_hash_update:
7921 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
7922 goto error;
7923 break;
cd339431 7924 case BPF_FUNC_get_local_storage:
b741f163
RG
7925 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7926 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
7927 goto error;
7928 break;
2dbb9b9e 7929 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
7930 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7931 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7932 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
7933 goto error;
7934 break;
f1a2e44a 7935 case BPF_FUNC_map_pop_elem:
f1a2e44a
MV
7936 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7937 map->map_type != BPF_MAP_TYPE_STACK)
7938 goto error;
7939 break;
9330986c
JK
7940 case BPF_FUNC_map_peek_elem:
7941 case BPF_FUNC_map_push_elem:
7942 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7943 map->map_type != BPF_MAP_TYPE_STACK &&
7944 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7945 goto error;
7946 break;
07343110
FZ
7947 case BPF_FUNC_map_lookup_percpu_elem:
7948 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7949 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7950 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7951 goto error;
7952 break;
6ac99e8f
MKL
7953 case BPF_FUNC_sk_storage_get:
7954 case BPF_FUNC_sk_storage_delete:
7955 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7956 goto error;
7957 break;
8ea63684
KS
7958 case BPF_FUNC_inode_storage_get:
7959 case BPF_FUNC_inode_storage_delete:
7960 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7961 goto error;
7962 break;
4cf1bc1f
KS
7963 case BPF_FUNC_task_storage_get:
7964 case BPF_FUNC_task_storage_delete:
7965 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7966 goto error;
7967 break;
c4bcfb38
YS
7968 case BPF_FUNC_cgrp_storage_get:
7969 case BPF_FUNC_cgrp_storage_delete:
7970 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7971 goto error;
7972 break;
6aff67c8
AS
7973 default:
7974 break;
35578d79
KX
7975 }
7976
7977 return 0;
6aff67c8 7978error:
61bd5218 7979 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 7980 map->map_type, func_id_name(func_id), func_id);
6aff67c8 7981 return -EINVAL;
35578d79
KX
7982}
7983
90133415 7984static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
7985{
7986 int count = 0;
7987
39f19ebb 7988 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 7989 count++;
39f19ebb 7990 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 7991 count++;
39f19ebb 7992 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 7993 count++;
39f19ebb 7994 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 7995 count++;
39f19ebb 7996 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
7997 count++;
7998
90133415
DB
7999 /* We only support one arg being in raw mode at the moment,
8000 * which is sufficient for the helper functions we have
8001 * right now.
8002 */
8003 return count <= 1;
8004}
8005
508362ac 8006static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
90133415 8007{
508362ac
MM
8008 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8009 bool has_size = fn->arg_size[arg] != 0;
8010 bool is_next_size = false;
8011
8012 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8013 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8014
8015 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8016 return is_next_size;
8017
8018 return has_size == is_next_size || is_next_size == is_fixed;
90133415
DB
8019}
8020
8021static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8022{
8023 /* bpf_xxx(..., buf, len) call will access 'len'
8024 * bytes from memory 'buf'. Both arg types need
8025 * to be paired, so make sure there's no buggy
8026 * helper function specification.
8027 */
8028 if (arg_type_is_mem_size(fn->arg1_type) ||
508362ac
MM
8029 check_args_pair_invalid(fn, 0) ||
8030 check_args_pair_invalid(fn, 1) ||
8031 check_args_pair_invalid(fn, 2) ||
8032 check_args_pair_invalid(fn, 3) ||
8033 check_args_pair_invalid(fn, 4))
90133415
DB
8034 return false;
8035
8036 return true;
8037}
8038
9436ef6e
LB
8039static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8040{
8041 int i;
8042
1df8f55a 8043 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4e814da0
KKD
8044 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8045 return !!fn->arg_btf_id[i];
8046 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8047 return fn->arg_btf_id[i] == BPF_PTR_POISON;
508362ac
MM
8048 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8049 /* arg_btf_id and arg_size are in a union. */
8050 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8051 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
1df8f55a
MKL
8052 return false;
8053 }
8054
9436ef6e
LB
8055 return true;
8056}
8057
0c9a7a7e 8058static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
8059{
8060 return check_raw_mode_ok(fn) &&
fd978bf7 8061 check_arg_pair_ok(fn) &&
b2d8ef19 8062 check_btf_id_ok(fn) ? 0 : -EINVAL;
435faee1
DB
8063}
8064
de8f3a83
DB
8065/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8066 * are now invalid, so turn them into unknown SCALAR_VALUE.
66e3a13e
JK
8067 *
8068 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8069 * since these slices point to packet data.
f1174f77 8070 */
b239da34 8071static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 8072{
b239da34
KKD
8073 struct bpf_func_state *state;
8074 struct bpf_reg_state *reg;
969bf05e 8075
b239da34 8076 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
66e3a13e 8077 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
dbd8d228 8078 mark_reg_invalid(env, reg);
b239da34 8079 }));
f4d7e40a
AS
8080}
8081
6d94e741
AS
8082enum {
8083 AT_PKT_END = -1,
8084 BEYOND_PKT_END = -2,
8085};
8086
8087static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8088{
8089 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8090 struct bpf_reg_state *reg = &state->regs[regn];
8091
8092 if (reg->type != PTR_TO_PACKET)
8093 /* PTR_TO_PACKET_META is not supported yet */
8094 return;
8095
8096 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8097 * How far beyond pkt_end it goes is unknown.
8098 * if (!range_open) it's the case of pkt >= pkt_end
8099 * if (range_open) it's the case of pkt > pkt_end
8100 * hence this pointer is at least 1 byte bigger than pkt_end
8101 */
8102 if (range_open)
8103 reg->range = BEYOND_PKT_END;
8104 else
8105 reg->range = AT_PKT_END;
8106}
8107
fd978bf7
JS
8108/* The pointer with the specified id has released its reference to kernel
8109 * resources. Identify all copies of the same pointer and clear the reference.
8110 */
8111static int release_reference(struct bpf_verifier_env *env,
1b986589 8112 int ref_obj_id)
fd978bf7 8113{
b239da34
KKD
8114 struct bpf_func_state *state;
8115 struct bpf_reg_state *reg;
1b986589 8116 int err;
fd978bf7 8117
1b986589
MKL
8118 err = release_reference_state(cur_func(env), ref_obj_id);
8119 if (err)
8120 return err;
8121
b239da34 8122 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
dbd8d228
KKD
8123 if (reg->ref_obj_id == ref_obj_id)
8124 mark_reg_invalid(env, reg);
b239da34 8125 }));
fd978bf7 8126
1b986589 8127 return 0;
fd978bf7
JS
8128}
8129
6a3cd331
DM
8130static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8131{
8132 struct bpf_func_state *unused;
8133 struct bpf_reg_state *reg;
8134
8135 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8136 if (type_is_non_owning_ref(reg->type))
dbd8d228 8137 mark_reg_invalid(env, reg);
6a3cd331
DM
8138 }));
8139}
8140
51c39bb1
AS
8141static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8142 struct bpf_reg_state *regs)
8143{
8144 int i;
8145
8146 /* after the call registers r0 - r5 were scratched */
8147 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8148 mark_reg_not_init(env, regs, caller_saved[i]);
8149 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8150 }
8151}
8152
14351375
YS
8153typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8154 struct bpf_func_state *caller,
8155 struct bpf_func_state *callee,
8156 int insn_idx);
8157
be2ef816
AN
8158static int set_callee_state(struct bpf_verifier_env *env,
8159 struct bpf_func_state *caller,
8160 struct bpf_func_state *callee, int insn_idx);
8161
5d92ddc3
DM
8162static bool is_callback_calling_kfunc(u32 btf_id);
8163
14351375
YS
8164static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8165 int *insn_idx, int subprog,
8166 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
8167{
8168 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 8169 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 8170 struct bpf_func_state *caller, *callee;
14351375 8171 int err;
51c39bb1 8172 bool is_global = false;
f4d7e40a 8173
aada9ce6 8174 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 8175 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 8176 state->curframe + 2);
f4d7e40a
AS
8177 return -E2BIG;
8178 }
8179
f4d7e40a
AS
8180 caller = state->frame[state->curframe];
8181 if (state->frame[state->curframe + 1]) {
8182 verbose(env, "verifier bug. Frame %d already allocated\n",
8183 state->curframe + 1);
8184 return -EFAULT;
8185 }
8186
51c39bb1
AS
8187 func_info_aux = env->prog->aux->func_info_aux;
8188 if (func_info_aux)
8189 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
95f2f26f 8190 err = btf_check_subprog_call(env, subprog, caller->regs);
51c39bb1
AS
8191 if (err == -EFAULT)
8192 return err;
8193 if (is_global) {
8194 if (err) {
8195 verbose(env, "Caller passes invalid args into func#%d\n",
8196 subprog);
8197 return err;
8198 } else {
8199 if (env->log.level & BPF_LOG_LEVEL)
8200 verbose(env,
8201 "Func#%d is global and valid. Skipping.\n",
8202 subprog);
8203 clear_caller_saved_regs(env, caller->regs);
8204
45159b27 8205 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 8206 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 8207 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
8208
8209 /* continue with next insn after call */
8210 return 0;
8211 }
8212 }
8213
be2ef816
AN
8214 /* set_callee_state is used for direct subprog calls, but we are
8215 * interested in validating only BPF helpers that can call subprogs as
8216 * callbacks
8217 */
5d92ddc3
DM
8218 if (set_callee_state_cb != set_callee_state) {
8219 if (bpf_pseudo_kfunc_call(insn) &&
8220 !is_callback_calling_kfunc(insn->imm)) {
8221 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8222 func_id_name(insn->imm), insn->imm);
8223 return -EFAULT;
8224 } else if (!bpf_pseudo_kfunc_call(insn) &&
8225 !is_callback_calling_function(insn->imm)) { /* helper */
8226 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8227 func_id_name(insn->imm), insn->imm);
8228 return -EFAULT;
8229 }
be2ef816
AN
8230 }
8231
bfc6bb74 8232 if (insn->code == (BPF_JMP | BPF_CALL) &&
a5bebc4f 8233 insn->src_reg == 0 &&
bfc6bb74
AS
8234 insn->imm == BPF_FUNC_timer_set_callback) {
8235 struct bpf_verifier_state *async_cb;
8236
8237 /* there is no real recursion here. timer callbacks are async */
7ddc80a4 8238 env->subprog_info[subprog].is_async_cb = true;
bfc6bb74
AS
8239 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8240 *insn_idx, subprog);
8241 if (!async_cb)
8242 return -EFAULT;
8243 callee = async_cb->frame[0];
8244 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8245
8246 /* Convert bpf_timer_set_callback() args into timer callback args */
8247 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8248 if (err)
8249 return err;
8250
8251 clear_caller_saved_regs(env, caller->regs);
8252 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8253 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8254 /* continue with next insn after call */
8255 return 0;
8256 }
8257
f4d7e40a
AS
8258 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8259 if (!callee)
8260 return -ENOMEM;
8261 state->frame[state->curframe + 1] = callee;
8262
8263 /* callee cannot access r0, r6 - r9 for reading and has to write
8264 * into its own stack before reading from it.
8265 * callee can read/write into caller's stack
8266 */
8267 init_func_state(env, callee,
8268 /* remember the callsite, it will be used by bpf_exit */
8269 *insn_idx /* callsite */,
8270 state->curframe + 1 /* frameno within this callchain */,
f910cefa 8271 subprog /* subprog number within this prog */);
f4d7e40a 8272
fd978bf7 8273 /* Transfer references to the callee */
c69431aa 8274 err = copy_reference_state(callee, caller);
fd978bf7 8275 if (err)
eb86559a 8276 goto err_out;
fd978bf7 8277
14351375
YS
8278 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8279 if (err)
eb86559a 8280 goto err_out;
f4d7e40a 8281
51c39bb1 8282 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
8283
8284 /* only increment it after check_reg_arg() finished */
8285 state->curframe++;
8286
8287 /* and go analyze first insn of the callee */
14351375 8288 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 8289
06ee7115 8290 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 8291 verbose(env, "caller:\n");
0f55f9ed 8292 print_verifier_state(env, caller, true);
f4d7e40a 8293 verbose(env, "callee:\n");
0f55f9ed 8294 print_verifier_state(env, callee, true);
f4d7e40a
AS
8295 }
8296 return 0;
eb86559a
WY
8297
8298err_out:
8299 free_func_state(callee);
8300 state->frame[state->curframe + 1] = NULL;
8301 return err;
f4d7e40a
AS
8302}
8303
314ee05e
YS
8304int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8305 struct bpf_func_state *caller,
8306 struct bpf_func_state *callee)
8307{
8308 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8309 * void *callback_ctx, u64 flags);
8310 * callback_fn(struct bpf_map *map, void *key, void *value,
8311 * void *callback_ctx);
8312 */
8313 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8314
8315 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8316 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8317 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8318
8319 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8320 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8321 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8322
8323 /* pointer to stack or null */
8324 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8325
8326 /* unused */
8327 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8328 return 0;
8329}
8330
14351375
YS
8331static int set_callee_state(struct bpf_verifier_env *env,
8332 struct bpf_func_state *caller,
8333 struct bpf_func_state *callee, int insn_idx)
8334{
8335 int i;
8336
8337 /* copy r1 - r5 args that callee can access. The copy includes parent
8338 * pointers, which connects us up to the liveness chain
8339 */
8340 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8341 callee->regs[i] = caller->regs[i];
8342 return 0;
8343}
8344
8345static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8346 int *insn_idx)
8347{
8348 int subprog, target_insn;
8349
8350 target_insn = *insn_idx + insn->imm + 1;
8351 subprog = find_subprog(env, target_insn);
8352 if (subprog < 0) {
8353 verbose(env, "verifier bug. No program starts at insn %d\n",
8354 target_insn);
8355 return -EFAULT;
8356 }
8357
8358 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8359}
8360
69c087ba
YS
8361static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8362 struct bpf_func_state *caller,
8363 struct bpf_func_state *callee,
8364 int insn_idx)
8365{
8366 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8367 struct bpf_map *map;
8368 int err;
8369
8370 if (bpf_map_ptr_poisoned(insn_aux)) {
8371 verbose(env, "tail_call abusing map_ptr\n");
8372 return -EINVAL;
8373 }
8374
8375 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8376 if (!map->ops->map_set_for_each_callback_args ||
8377 !map->ops->map_for_each_callback) {
8378 verbose(env, "callback function not allowed for map\n");
8379 return -ENOTSUPP;
8380 }
8381
8382 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8383 if (err)
8384 return err;
8385
8386 callee->in_callback_fn = true;
1bfe26fb 8387 callee->callback_ret_range = tnum_range(0, 1);
69c087ba
YS
8388 return 0;
8389}
8390
e6f2dd0f
JK
8391static int set_loop_callback_state(struct bpf_verifier_env *env,
8392 struct bpf_func_state *caller,
8393 struct bpf_func_state *callee,
8394 int insn_idx)
8395{
8396 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8397 * u64 flags);
8398 * callback_fn(u32 index, void *callback_ctx);
8399 */
8400 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8401 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8402
8403 /* unused */
8404 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8405 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8406 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8407
8408 callee->in_callback_fn = true;
1bfe26fb 8409 callee->callback_ret_range = tnum_range(0, 1);
e6f2dd0f
JK
8410 return 0;
8411}
8412
b00628b1
AS
8413static int set_timer_callback_state(struct bpf_verifier_env *env,
8414 struct bpf_func_state *caller,
8415 struct bpf_func_state *callee,
8416 int insn_idx)
8417{
8418 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8419
8420 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8421 * callback_fn(struct bpf_map *map, void *key, void *value);
8422 */
8423 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8424 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8425 callee->regs[BPF_REG_1].map_ptr = map_ptr;
8426
8427 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8428 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8429 callee->regs[BPF_REG_2].map_ptr = map_ptr;
8430
8431 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8432 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8433 callee->regs[BPF_REG_3].map_ptr = map_ptr;
8434
8435 /* unused */
8436 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8437 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
bfc6bb74 8438 callee->in_async_callback_fn = true;
1bfe26fb 8439 callee->callback_ret_range = tnum_range(0, 1);
b00628b1
AS
8440 return 0;
8441}
8442
7c7e3d31
SL
8443static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8444 struct bpf_func_state *caller,
8445 struct bpf_func_state *callee,
8446 int insn_idx)
8447{
8448 /* bpf_find_vma(struct task_struct *task, u64 addr,
8449 * void *callback_fn, void *callback_ctx, u64 flags)
8450 * (callback_fn)(struct task_struct *task,
8451 * struct vm_area_struct *vma, void *callback_ctx);
8452 */
8453 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8454
8455 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8456 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8457 callee->regs[BPF_REG_2].btf = btf_vmlinux;
d19ddb47 8458 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7c7e3d31
SL
8459
8460 /* pointer to stack or null */
8461 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8462
8463 /* unused */
8464 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8465 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8466 callee->in_callback_fn = true;
1bfe26fb 8467 callee->callback_ret_range = tnum_range(0, 1);
7c7e3d31
SL
8468 return 0;
8469}
8470
20571567
DV
8471static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8472 struct bpf_func_state *caller,
8473 struct bpf_func_state *callee,
8474 int insn_idx)
8475{
8476 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8477 * callback_ctx, u64 flags);
27060531 8478 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
20571567
DV
8479 */
8480 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
f8064ab9 8481 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
20571567
DV
8482 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8483
8484 /* unused */
8485 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8486 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8487 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8488
8489 callee->in_callback_fn = true;
c92a7a52 8490 callee->callback_ret_range = tnum_range(0, 1);
20571567
DV
8491 return 0;
8492}
8493
5d92ddc3
DM
8494static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8495 struct bpf_func_state *caller,
8496 struct bpf_func_state *callee,
8497 int insn_idx)
8498{
8499 /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8500 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8501 *
8502 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8503 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8504 * by this point, so look at 'root'
8505 */
8506 struct btf_field *field;
8507
8508 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8509 BPF_RB_ROOT);
8510 if (!field || !field->graph_root.value_btf_id)
8511 return -EFAULT;
8512
8513 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8514 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8515 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8516 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8517
8518 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8519 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8520 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8521 callee->in_callback_fn = true;
8522 callee->callback_ret_range = tnum_range(0, 1);
8523 return 0;
8524}
8525
8526static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8527
8528/* Are we currently verifying the callback for a rbtree helper that must
8529 * be called with lock held? If so, no need to complain about unreleased
8530 * lock
8531 */
8532static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8533{
8534 struct bpf_verifier_state *state = env->cur_state;
8535 struct bpf_insn *insn = env->prog->insnsi;
8536 struct bpf_func_state *callee;
8537 int kfunc_btf_id;
8538
8539 if (!state->curframe)
8540 return false;
8541
8542 callee = state->frame[state->curframe];
8543
8544 if (!callee->in_callback_fn)
8545 return false;
8546
8547 kfunc_btf_id = insn[callee->callsite].imm;
8548 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8549}
8550
f4d7e40a
AS
8551static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8552{
8553 struct bpf_verifier_state *state = env->cur_state;
8554 struct bpf_func_state *caller, *callee;
8555 struct bpf_reg_state *r0;
fd978bf7 8556 int err;
f4d7e40a
AS
8557
8558 callee = state->frame[state->curframe];
8559 r0 = &callee->regs[BPF_REG_0];
8560 if (r0->type == PTR_TO_STACK) {
8561 /* technically it's ok to return caller's stack pointer
8562 * (or caller's caller's pointer) back to the caller,
8563 * since these pointers are valid. Only current stack
8564 * pointer will be invalid as soon as function exits,
8565 * but let's be conservative
8566 */
8567 verbose(env, "cannot return stack pointer to the caller\n");
8568 return -EINVAL;
8569 }
8570
eb86559a 8571 caller = state->frame[state->curframe - 1];
69c087ba
YS
8572 if (callee->in_callback_fn) {
8573 /* enforce R0 return value range [0, 1]. */
1bfe26fb 8574 struct tnum range = callee->callback_ret_range;
69c087ba
YS
8575
8576 if (r0->type != SCALAR_VALUE) {
8577 verbose(env, "R0 not a scalar value\n");
8578 return -EACCES;
8579 }
8580 if (!tnum_in(range, r0->var_off)) {
8581 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8582 return -EINVAL;
8583 }
8584 } else {
8585 /* return to the caller whatever r0 had in the callee */
8586 caller->regs[BPF_REG_0] = *r0;
8587 }
f4d7e40a 8588
9d9d00ac
KKD
8589 /* callback_fn frame should have released its own additions to parent's
8590 * reference state at this point, or check_reference_leak would
8591 * complain, hence it must be the same as the caller. There is no need
8592 * to copy it back.
8593 */
8594 if (!callee->in_callback_fn) {
8595 /* Transfer references to the caller */
8596 err = copy_reference_state(caller, callee);
8597 if (err)
8598 return err;
8599 }
fd978bf7 8600
f4d7e40a 8601 *insn_idx = callee->callsite + 1;
06ee7115 8602 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 8603 verbose(env, "returning from callee:\n");
0f55f9ed 8604 print_verifier_state(env, callee, true);
f4d7e40a 8605 verbose(env, "to caller at %d:\n", *insn_idx);
0f55f9ed 8606 print_verifier_state(env, caller, true);
f4d7e40a
AS
8607 }
8608 /* clear everything in the callee */
8609 free_func_state(callee);
eb86559a 8610 state->frame[state->curframe--] = NULL;
f4d7e40a
AS
8611 return 0;
8612}
8613
849fa506
YS
8614static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8615 int func_id,
8616 struct bpf_call_arg_meta *meta)
8617{
8618 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8619
8620 if (ret_type != RET_INTEGER ||
8621 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 8622 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
8623 func_id != BPF_FUNC_probe_read_str &&
8624 func_id != BPF_FUNC_probe_read_kernel_str &&
8625 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
8626 return;
8627
10060503 8628 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 8629 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
8630 ret_reg->smin_value = -MAX_ERRNO;
8631 ret_reg->s32_min_value = -MAX_ERRNO;
3844d153 8632 reg_bounds_sync(ret_reg);
849fa506
YS
8633}
8634
c93552c4
DB
8635static int
8636record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8637 int func_id, int insn_idx)
8638{
8639 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 8640 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
8641
8642 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
8643 func_id != BPF_FUNC_map_lookup_elem &&
8644 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
8645 func_id != BPF_FUNC_map_delete_elem &&
8646 func_id != BPF_FUNC_map_push_elem &&
8647 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 8648 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f 8649 func_id != BPF_FUNC_for_each_map_elem &&
07343110
FZ
8650 func_id != BPF_FUNC_redirect_map &&
8651 func_id != BPF_FUNC_map_lookup_percpu_elem)
c93552c4 8652 return 0;
09772d92 8653
591fe988 8654 if (map == NULL) {
c93552c4
DB
8655 verbose(env, "kernel subsystem misconfigured verifier\n");
8656 return -EINVAL;
8657 }
8658
591fe988
DB
8659 /* In case of read-only, some additional restrictions
8660 * need to be applied in order to prevent altering the
8661 * state of the map from program side.
8662 */
8663 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8664 (func_id == BPF_FUNC_map_delete_elem ||
8665 func_id == BPF_FUNC_map_update_elem ||
8666 func_id == BPF_FUNC_map_push_elem ||
8667 func_id == BPF_FUNC_map_pop_elem)) {
8668 verbose(env, "write into map forbidden\n");
8669 return -EACCES;
8670 }
8671
d2e4c1e6 8672 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 8673 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 8674 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 8675 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 8676 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 8677 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
8678 return 0;
8679}
8680
d2e4c1e6
DB
8681static int
8682record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8683 int func_id, int insn_idx)
8684{
8685 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8686 struct bpf_reg_state *regs = cur_regs(env), *reg;
8687 struct bpf_map *map = meta->map_ptr;
a657182a 8688 u64 val, max;
cc52d914 8689 int err;
d2e4c1e6
DB
8690
8691 if (func_id != BPF_FUNC_tail_call)
8692 return 0;
8693 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8694 verbose(env, "kernel subsystem misconfigured verifier\n");
8695 return -EINVAL;
8696 }
8697
d2e4c1e6 8698 reg = &regs[BPF_REG_3];
a657182a
DB
8699 val = reg->var_off.value;
8700 max = map->max_entries;
d2e4c1e6 8701
a657182a 8702 if (!(register_is_const(reg) && val < max)) {
d2e4c1e6
DB
8703 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8704 return 0;
8705 }
8706
cc52d914
DB
8707 err = mark_chain_precision(env, BPF_REG_3);
8708 if (err)
8709 return err;
d2e4c1e6
DB
8710 if (bpf_map_key_unseen(aux))
8711 bpf_map_key_store(aux, val);
8712 else if (!bpf_map_key_poisoned(aux) &&
8713 bpf_map_key_immediate(aux) != val)
8714 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8715 return 0;
8716}
8717
fd978bf7
JS
8718static int check_reference_leak(struct bpf_verifier_env *env)
8719{
8720 struct bpf_func_state *state = cur_func(env);
9d9d00ac 8721 bool refs_lingering = false;
fd978bf7
JS
8722 int i;
8723
9d9d00ac
KKD
8724 if (state->frameno && !state->in_callback_fn)
8725 return 0;
8726
fd978bf7 8727 for (i = 0; i < state->acquired_refs; i++) {
9d9d00ac
KKD
8728 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8729 continue;
fd978bf7
JS
8730 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8731 state->refs[i].id, state->refs[i].insn_idx);
9d9d00ac 8732 refs_lingering = true;
fd978bf7 8733 }
9d9d00ac 8734 return refs_lingering ? -EINVAL : 0;
fd978bf7
JS
8735}
8736
7b15523a
FR
8737static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8738 struct bpf_reg_state *regs)
8739{
8740 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8741 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8742 struct bpf_map *fmt_map = fmt_reg->map_ptr;
78aa1cc9 8743 struct bpf_bprintf_data data = {};
7b15523a
FR
8744 int err, fmt_map_off, num_args;
8745 u64 fmt_addr;
8746 char *fmt;
8747
8748 /* data must be an array of u64 */
8749 if (data_len_reg->var_off.value % 8)
8750 return -EINVAL;
8751 num_args = data_len_reg->var_off.value / 8;
8752
8753 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8754 * and map_direct_value_addr is set.
8755 */
8756 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8757 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8758 fmt_map_off);
8e8ee109
FR
8759 if (err) {
8760 verbose(env, "verifier bug\n");
8761 return -EFAULT;
8762 }
7b15523a
FR
8763 fmt = (char *)(long)fmt_addr + fmt_map_off;
8764
8765 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8766 * can focus on validating the format specifiers.
8767 */
78aa1cc9 8768 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7b15523a
FR
8769 if (err < 0)
8770 verbose(env, "Invalid format string\n");
8771
8772 return err;
8773}
8774
9b99edca
JO
8775static int check_get_func_ip(struct bpf_verifier_env *env)
8776{
9b99edca
JO
8777 enum bpf_prog_type type = resolve_prog_type(env->prog);
8778 int func_id = BPF_FUNC_get_func_ip;
8779
8780 if (type == BPF_PROG_TYPE_TRACING) {
f92c1e18 8781 if (!bpf_prog_has_trampoline(env->prog)) {
9b99edca
JO
8782 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8783 func_id_name(func_id), func_id);
8784 return -ENOTSUPP;
8785 }
8786 return 0;
9ffd9f3f
JO
8787 } else if (type == BPF_PROG_TYPE_KPROBE) {
8788 return 0;
9b99edca
JO
8789 }
8790
8791 verbose(env, "func %s#%d not supported for program type %d\n",
8792 func_id_name(func_id), func_id, type);
8793 return -ENOTSUPP;
8794}
8795
1ade2371
EZ
8796static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8797{
8798 return &env->insn_aux_data[env->insn_idx];
8799}
8800
8801static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8802{
8803 struct bpf_reg_state *regs = cur_regs(env);
8804 struct bpf_reg_state *reg = &regs[BPF_REG_4];
8805 bool reg_is_null = register_is_null(reg);
8806
8807 if (reg_is_null)
8808 mark_chain_precision(env, BPF_REG_4);
8809
8810 return reg_is_null;
8811}
8812
8813static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8814{
8815 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8816
8817 if (!state->initialized) {
8818 state->initialized = 1;
8819 state->fit_for_inline = loop_flag_is_zero(env);
8820 state->callback_subprogno = subprogno;
8821 return;
8822 }
8823
8824 if (!state->fit_for_inline)
8825 return;
8826
8827 state->fit_for_inline = (loop_flag_is_zero(env) &&
8828 state->callback_subprogno == subprogno);
8829}
8830
69c087ba
YS
8831static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8832 int *insn_idx_p)
17a52670 8833{
aef9d4a3 8834 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17a52670 8835 const struct bpf_func_proto *fn = NULL;
3c480732 8836 enum bpf_return_type ret_type;
c25b2ae1 8837 enum bpf_type_flag ret_flag;
638f5b90 8838 struct bpf_reg_state *regs;
33ff9823 8839 struct bpf_call_arg_meta meta;
69c087ba 8840 int insn_idx = *insn_idx_p;
969bf05e 8841 bool changes_data;
69c087ba 8842 int i, err, func_id;
17a52670
AS
8843
8844 /* find function prototype */
69c087ba 8845 func_id = insn->imm;
17a52670 8846 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
8847 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8848 func_id);
17a52670
AS
8849 return -EINVAL;
8850 }
8851
00176a34 8852 if (env->ops->get_func_proto)
5e43f899 8853 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 8854 if (!fn) {
61bd5218
JK
8855 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8856 func_id);
17a52670
AS
8857 return -EINVAL;
8858 }
8859
8860 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 8861 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 8862 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
8863 return -EINVAL;
8864 }
8865
eae2e83e
JO
8866 if (fn->allowed && !fn->allowed(env->prog)) {
8867 verbose(env, "helper call is not allowed in probe\n");
8868 return -EINVAL;
8869 }
8870
01685c5b
YS
8871 if (!env->prog->aux->sleepable && fn->might_sleep) {
8872 verbose(env, "helper call might sleep in a non-sleepable prog\n");
8873 return -EINVAL;
8874 }
8875
04514d13 8876 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 8877 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
8878 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8879 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8880 func_id_name(func_id), func_id);
8881 return -EINVAL;
8882 }
969bf05e 8883
33ff9823 8884 memset(&meta, 0, sizeof(meta));
36bbef52 8885 meta.pkt_access = fn->pkt_access;
33ff9823 8886
0c9a7a7e 8887 err = check_func_proto(fn, func_id);
435faee1 8888 if (err) {
61bd5218 8889 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 8890 func_id_name(func_id), func_id);
435faee1
DB
8891 return err;
8892 }
8893
9bb00b28
YS
8894 if (env->cur_state->active_rcu_lock) {
8895 if (fn->might_sleep) {
8896 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8897 func_id_name(func_id), func_id);
8898 return -EINVAL;
8899 }
8900
8901 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8902 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8903 }
8904
d83525ca 8905 meta.func_id = func_id;
17a52670 8906 /* check args */
523a4cf4 8907 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
1d18feb2 8908 err = check_func_arg(env, i, &meta, fn, insn_idx);
a7658e1a
AS
8909 if (err)
8910 return err;
8911 }
17a52670 8912
c93552c4
DB
8913 err = record_func_map(env, &meta, func_id, insn_idx);
8914 if (err)
8915 return err;
8916
d2e4c1e6
DB
8917 err = record_func_key(env, &meta, func_id, insn_idx);
8918 if (err)
8919 return err;
8920
435faee1
DB
8921 /* Mark slots with STACK_MISC in case of raw mode, stack offset
8922 * is inferred from register state.
8923 */
8924 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
8925 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8926 BPF_WRITE, -1, false);
435faee1
DB
8927 if (err)
8928 return err;
8929 }
8930
8f14852e
KKD
8931 regs = cur_regs(env);
8932
8933 if (meta.release_regno) {
8934 err = -EINVAL;
27060531
KKD
8935 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8936 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8937 * is safe to do directly.
8938 */
8939 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8940 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8941 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8942 return -EFAULT;
8943 }
97e03f52 8944 err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
27060531 8945 } else if (meta.ref_obj_id) {
8f14852e 8946 err = release_reference(env, meta.ref_obj_id);
27060531
KKD
8947 } else if (register_is_null(&regs[meta.release_regno])) {
8948 /* meta.ref_obj_id can only be 0 if register that is meant to be
8949 * released is NULL, which must be > R0.
8950 */
8f14852e 8951 err = 0;
27060531 8952 }
46f8bc92
MKL
8953 if (err) {
8954 verbose(env, "func %s#%d reference has not been acquired before\n",
8955 func_id_name(func_id), func_id);
fd978bf7 8956 return err;
46f8bc92 8957 }
fd978bf7
JS
8958 }
8959
e6f2dd0f
JK
8960 switch (func_id) {
8961 case BPF_FUNC_tail_call:
8962 err = check_reference_leak(env);
8963 if (err) {
8964 verbose(env, "tail_call would lead to reference leak\n");
8965 return err;
8966 }
8967 break;
8968 case BPF_FUNC_get_local_storage:
8969 /* check that flags argument in get_local_storage(map, flags) is 0,
8970 * this is required because get_local_storage() can't return an error.
8971 */
8972 if (!register_is_null(&regs[BPF_REG_2])) {
8973 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8974 return -EINVAL;
8975 }
8976 break;
8977 case BPF_FUNC_for_each_map_elem:
69c087ba
YS
8978 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8979 set_map_elem_callback_state);
e6f2dd0f
JK
8980 break;
8981 case BPF_FUNC_timer_set_callback:
b00628b1
AS
8982 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8983 set_timer_callback_state);
e6f2dd0f
JK
8984 break;
8985 case BPF_FUNC_find_vma:
7c7e3d31
SL
8986 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8987 set_find_vma_callback_state);
e6f2dd0f
JK
8988 break;
8989 case BPF_FUNC_snprintf:
7b15523a 8990 err = check_bpf_snprintf_call(env, regs);
e6f2dd0f
JK
8991 break;
8992 case BPF_FUNC_loop:
1ade2371 8993 update_loop_inline_state(env, meta.subprogno);
e6f2dd0f
JK
8994 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8995 set_loop_callback_state);
8996 break;
263ae152
JK
8997 case BPF_FUNC_dynptr_from_mem:
8998 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8999 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9000 reg_type_str(env, regs[BPF_REG_1].type));
9001 return -EACCES;
9002 }
69fd337a
SF
9003 break;
9004 case BPF_FUNC_set_retval:
aef9d4a3
SF
9005 if (prog_type == BPF_PROG_TYPE_LSM &&
9006 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
69fd337a
SF
9007 if (!env->prog->aux->attach_func_proto->type) {
9008 /* Make sure programs that attach to void
9009 * hooks don't try to modify return value.
9010 */
9011 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9012 return -EINVAL;
9013 }
9014 }
9015 break;
88374342 9016 case BPF_FUNC_dynptr_data:
485ec51e
JK
9017 {
9018 struct bpf_reg_state *reg;
9019 int id, ref_obj_id;
20571567 9020
485ec51e
JK
9021 reg = get_dynptr_arg_reg(env, fn, regs);
9022 if (!reg)
9023 return -EFAULT;
f8064ab9 9024
f8064ab9 9025
485ec51e
JK
9026 if (meta.dynptr_id) {
9027 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9028 return -EFAULT;
88374342 9029 }
485ec51e
JK
9030 if (meta.ref_obj_id) {
9031 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
88374342
JK
9032 return -EFAULT;
9033 }
485ec51e
JK
9034
9035 id = dynptr_id(env, reg);
9036 if (id < 0) {
9037 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9038 return id;
9039 }
9040
9041 ref_obj_id = dynptr_ref_obj_id(env, reg);
9042 if (ref_obj_id < 0) {
9043 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9044 return ref_obj_id;
9045 }
9046
9047 meta.dynptr_id = id;
9048 meta.ref_obj_id = ref_obj_id;
9049
88374342 9050 break;
485ec51e 9051 }
b5964b96
JK
9052 case BPF_FUNC_dynptr_write:
9053 {
9054 enum bpf_dynptr_type dynptr_type;
9055 struct bpf_reg_state *reg;
9056
9057 reg = get_dynptr_arg_reg(env, fn, regs);
9058 if (!reg)
9059 return -EFAULT;
9060
9061 dynptr_type = dynptr_get_type(env, reg);
9062 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9063 return -EFAULT;
9064
9065 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9066 /* this will trigger clear_all_pkt_pointers(), which will
9067 * invalidate all dynptr slices associated with the skb
9068 */
9069 changes_data = true;
9070
9071 break;
9072 }
20571567
DV
9073 case BPF_FUNC_user_ringbuf_drain:
9074 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9075 set_user_ringbuf_callback_state);
9076 break;
7b15523a
FR
9077 }
9078
e6f2dd0f
JK
9079 if (err)
9080 return err;
9081
17a52670 9082 /* reset caller saved regs */
dc503a8a 9083 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 9084 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
9085 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9086 }
17a52670 9087
5327ed3d
JW
9088 /* helper call returns 64-bit value. */
9089 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9090
dc503a8a 9091 /* update return register (already marked as written above) */
3c480732 9092 ret_type = fn->ret_type;
0c9a7a7e
JK
9093 ret_flag = type_flag(ret_type);
9094
9095 switch (base_type(ret_type)) {
9096 case RET_INTEGER:
f1174f77 9097 /* sets type to SCALAR_VALUE */
61bd5218 9098 mark_reg_unknown(env, regs, BPF_REG_0);
0c9a7a7e
JK
9099 break;
9100 case RET_VOID:
17a52670 9101 regs[BPF_REG_0].type = NOT_INIT;
0c9a7a7e
JK
9102 break;
9103 case RET_PTR_TO_MAP_VALUE:
f1174f77 9104 /* There is no offset yet applied, variable or fixed */
61bd5218 9105 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
9106 /* remember map_ptr, so that check_map_access()
9107 * can check 'value_size' boundary of memory access
9108 * to map element returned from bpf_map_lookup_elem()
9109 */
33ff9823 9110 if (meta.map_ptr == NULL) {
61bd5218
JK
9111 verbose(env,
9112 "kernel subsystem misconfigured verifier\n");
17a52670
AS
9113 return -EINVAL;
9114 }
33ff9823 9115 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3e8ce298 9116 regs[BPF_REG_0].map_uid = meta.map_uid;
c25b2ae1
HL
9117 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9118 if (!type_may_be_null(ret_type) &&
db559117 9119 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
c25b2ae1 9120 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301 9121 }
0c9a7a7e
JK
9122 break;
9123 case RET_PTR_TO_SOCKET:
c64b7983 9124 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9125 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
0c9a7a7e
JK
9126 break;
9127 case RET_PTR_TO_SOCK_COMMON:
85a51f8c 9128 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9129 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
0c9a7a7e
JK
9130 break;
9131 case RET_PTR_TO_TCP_SOCK:
655a51e5 9132 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9133 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
0c9a7a7e 9134 break;
2de2669b 9135 case RET_PTR_TO_MEM:
457f4436 9136 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9137 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
457f4436 9138 regs[BPF_REG_0].mem_size = meta.mem_size;
0c9a7a7e
JK
9139 break;
9140 case RET_PTR_TO_MEM_OR_BTF_ID:
9141 {
eaa6bcb7
HL
9142 const struct btf_type *t;
9143
9144 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 9145 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
9146 if (!btf_type_is_struct(t)) {
9147 u32 tsize;
9148 const struct btf_type *ret;
9149 const char *tname;
9150
9151 /* resolve the type size of ksym. */
22dc4a0f 9152 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 9153 if (IS_ERR(ret)) {
22dc4a0f 9154 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
9155 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9156 tname, PTR_ERR(ret));
9157 return -EINVAL;
9158 }
c25b2ae1 9159 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
eaa6bcb7
HL
9160 regs[BPF_REG_0].mem_size = tsize;
9161 } else {
34d3a78c
HL
9162 /* MEM_RDONLY may be carried from ret_flag, but it
9163 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9164 * it will confuse the check of PTR_TO_BTF_ID in
9165 * check_mem_access().
9166 */
9167 ret_flag &= ~MEM_RDONLY;
9168
c25b2ae1 9169 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
22dc4a0f 9170 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
9171 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9172 }
0c9a7a7e
JK
9173 break;
9174 }
9175 case RET_PTR_TO_BTF_ID:
9176 {
c0a5a21c 9177 struct btf *ret_btf;
af7ec138
YS
9178 int ret_btf_id;
9179
9180 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9181 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
c0a5a21c 9182 if (func_id == BPF_FUNC_kptr_xchg) {
aa3496ac
KKD
9183 ret_btf = meta.kptr_field->kptr.btf;
9184 ret_btf_id = meta.kptr_field->kptr.btf_id;
738c96d5
DM
9185 if (!btf_is_kernel(ret_btf))
9186 regs[BPF_REG_0].type |= MEM_ALLOC;
c0a5a21c 9187 } else {
47e34cb7
DM
9188 if (fn->ret_btf_id == BPF_PTR_POISON) {
9189 verbose(env, "verifier internal error:");
9190 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9191 func_id_name(func_id));
9192 return -EINVAL;
9193 }
c0a5a21c
KKD
9194 ret_btf = btf_vmlinux;
9195 ret_btf_id = *fn->ret_btf_id;
9196 }
af7ec138 9197 if (ret_btf_id == 0) {
3c480732
HL
9198 verbose(env, "invalid return type %u of func %s#%d\n",
9199 base_type(ret_type), func_id_name(func_id),
9200 func_id);
af7ec138
YS
9201 return -EINVAL;
9202 }
c0a5a21c 9203 regs[BPF_REG_0].btf = ret_btf;
af7ec138 9204 regs[BPF_REG_0].btf_id = ret_btf_id;
0c9a7a7e
JK
9205 break;
9206 }
9207 default:
3c480732
HL
9208 verbose(env, "unknown return type %u of func %s#%d\n",
9209 base_type(ret_type), func_id_name(func_id), func_id);
17a52670
AS
9210 return -EINVAL;
9211 }
04fd61ab 9212
c25b2ae1 9213 if (type_may_be_null(regs[BPF_REG_0].type))
93c230e3
MKL
9214 regs[BPF_REG_0].id = ++env->id_gen;
9215
b2d8ef19
DM
9216 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9217 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9218 func_id_name(func_id), func_id);
9219 return -EFAULT;
9220 }
9221
f8064ab9
KKD
9222 if (is_dynptr_ref_function(func_id))
9223 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9224
88374342 9225 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
1b986589
MKL
9226 /* For release_reference() */
9227 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 9228 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
9229 int id = acquire_reference_state(env, insn_idx);
9230
9231 if (id < 0)
9232 return id;
9233 /* For mark_ptr_or_null_reg() */
9234 regs[BPF_REG_0].id = id;
9235 /* For release_reference() */
9236 regs[BPF_REG_0].ref_obj_id = id;
9237 }
1b986589 9238
849fa506
YS
9239 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9240
61bd5218 9241 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
9242 if (err)
9243 return err;
04fd61ab 9244
fa28dcb8
SL
9245 if ((func_id == BPF_FUNC_get_stack ||
9246 func_id == BPF_FUNC_get_task_stack) &&
9247 !env->prog->has_callchain_buf) {
c195651e
YS
9248 const char *err_str;
9249
9250#ifdef CONFIG_PERF_EVENTS
9251 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9252 err_str = "cannot get callchain buffer for func %s#%d\n";
9253#else
9254 err = -ENOTSUPP;
9255 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9256#endif
9257 if (err) {
9258 verbose(env, err_str, func_id_name(func_id), func_id);
9259 return err;
9260 }
9261
9262 env->prog->has_callchain_buf = true;
9263 }
9264
5d99cb2c
SL
9265 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9266 env->prog->call_get_stack = true;
9267
9b99edca
JO
9268 if (func_id == BPF_FUNC_get_func_ip) {
9269 if (check_get_func_ip(env))
9270 return -ENOTSUPP;
9271 env->prog->call_get_func_ip = true;
9272 }
9273
969bf05e
AS
9274 if (changes_data)
9275 clear_all_pkt_pointers(env);
9276 return 0;
9277}
9278
e6ac2450
MKL
9279/* mark_btf_func_reg_size() is used when the reg size is determined by
9280 * the BTF func_proto's return value size and argument.
9281 */
9282static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9283 size_t reg_size)
9284{
9285 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9286
9287 if (regno == BPF_REG_0) {
9288 /* Function return value */
9289 reg->live |= REG_LIVE_WRITTEN;
9290 reg->subreg_def = reg_size == sizeof(u64) ?
9291 DEF_NOT_SUBREG : env->insn_idx + 1;
9292 } else {
9293 /* Function argument */
9294 if (reg_size == sizeof(u64)) {
9295 mark_insn_zext(env, reg);
9296 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9297 } else {
9298 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9299 }
9300 }
9301}
9302
00b85860
KKD
9303static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9304{
9305 return meta->kfunc_flags & KF_ACQUIRE;
9306}
a5d82727 9307
00b85860
KKD
9308static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9309{
9310 return meta->kfunc_flags & KF_RET_NULL;
9311}
2357672c 9312
00b85860
KKD
9313static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9314{
9315 return meta->kfunc_flags & KF_RELEASE;
9316}
e6ac2450 9317
00b85860
KKD
9318static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9319{
6c831c46 9320 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
00b85860 9321}
4dd48c6f 9322
00b85860
KKD
9323static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9324{
9325 return meta->kfunc_flags & KF_SLEEPABLE;
9326}
5c073f26 9327
00b85860
KKD
9328static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9329{
9330 return meta->kfunc_flags & KF_DESTRUCTIVE;
9331}
eb1f7f71 9332
fca1aa75
YS
9333static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9334{
9335 return meta->kfunc_flags & KF_RCU;
9336}
9337
00b85860
KKD
9338static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
9339{
9340 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
9341}
e6ac2450 9342
a50388db
KKD
9343static bool __kfunc_param_match_suffix(const struct btf *btf,
9344 const struct btf_param *arg,
9345 const char *suffix)
00b85860 9346{
a50388db 9347 int suffix_len = strlen(suffix), len;
00b85860 9348 const char *param_name;
e6ac2450 9349
00b85860
KKD
9350 /* In the future, this can be ported to use BTF tagging */
9351 param_name = btf_name_by_offset(btf, arg->name_off);
9352 if (str_is_empty(param_name))
9353 return false;
9354 len = strlen(param_name);
a50388db 9355 if (len < suffix_len)
00b85860 9356 return false;
a50388db
KKD
9357 param_name += len - suffix_len;
9358 return !strncmp(param_name, suffix, suffix_len);
9359}
5c073f26 9360
a50388db
KKD
9361static bool is_kfunc_arg_mem_size(const struct btf *btf,
9362 const struct btf_param *arg,
9363 const struct bpf_reg_state *reg)
9364{
9365 const struct btf_type *t;
5c073f26 9366
a50388db
KKD
9367 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9368 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
00b85860 9369 return false;
eb1f7f71 9370
a50388db
KKD
9371 return __kfunc_param_match_suffix(btf, arg, "__sz");
9372}
eb1f7f71 9373
66e3a13e
JK
9374static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9375 const struct btf_param *arg,
9376 const struct bpf_reg_state *reg)
9377{
9378 const struct btf_type *t;
9379
9380 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9381 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9382 return false;
9383
9384 return __kfunc_param_match_suffix(btf, arg, "__szk");
9385}
9386
a50388db
KKD
9387static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9388{
9389 return __kfunc_param_match_suffix(btf, arg, "__k");
00b85860 9390}
eb1f7f71 9391
958cf2e2
KKD
9392static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9393{
9394 return __kfunc_param_match_suffix(btf, arg, "__ign");
9395}
5c073f26 9396
ac9f0605
KKD
9397static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9398{
9399 return __kfunc_param_match_suffix(btf, arg, "__alloc");
9400}
e6ac2450 9401
d96d937d
JK
9402static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9403{
9404 return __kfunc_param_match_suffix(btf, arg, "__uninit");
9405}
9406
00b85860
KKD
9407static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9408 const struct btf_param *arg,
9409 const char *name)
9410{
9411 int len, target_len = strlen(name);
9412 const char *param_name;
e6ac2450 9413
00b85860
KKD
9414 param_name = btf_name_by_offset(btf, arg->name_off);
9415 if (str_is_empty(param_name))
9416 return false;
9417 len = strlen(param_name);
9418 if (len != target_len)
9419 return false;
9420 if (strcmp(param_name, name))
9421 return false;
e6ac2450 9422
00b85860 9423 return true;
e6ac2450
MKL
9424}
9425
00b85860
KKD
9426enum {
9427 KF_ARG_DYNPTR_ID,
8cab76ec
KKD
9428 KF_ARG_LIST_HEAD_ID,
9429 KF_ARG_LIST_NODE_ID,
cd6791b4
DM
9430 KF_ARG_RB_ROOT_ID,
9431 KF_ARG_RB_NODE_ID,
00b85860 9432};
b03c9f9f 9433
00b85860
KKD
9434BTF_ID_LIST(kf_arg_btf_ids)
9435BTF_ID(struct, bpf_dynptr_kern)
8cab76ec
KKD
9436BTF_ID(struct, bpf_list_head)
9437BTF_ID(struct, bpf_list_node)
bd1279ae
DM
9438BTF_ID(struct, bpf_rb_root)
9439BTF_ID(struct, bpf_rb_node)
b03c9f9f 9440
8cab76ec
KKD
9441static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9442 const struct btf_param *arg, int type)
3f50f132 9443{
00b85860
KKD
9444 const struct btf_type *t;
9445 u32 res_id;
3f50f132 9446
00b85860
KKD
9447 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9448 if (!t)
9449 return false;
9450 if (!btf_type_is_ptr(t))
9451 return false;
9452 t = btf_type_skip_modifiers(btf, t->type, &res_id);
9453 if (!t)
9454 return false;
8cab76ec 9455 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
3f50f132
JF
9456}
9457
8cab76ec 9458static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
b03c9f9f 9459{
8cab76ec 9460 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
969bf05e
AS
9461}
9462
8cab76ec 9463static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
3f50f132 9464{
8cab76ec 9465 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
3f50f132
JF
9466}
9467
8cab76ec 9468static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
bb7f0f98 9469{
8cab76ec 9470 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
00b85860
KKD
9471}
9472
cd6791b4
DM
9473static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9474{
9475 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9476}
9477
9478static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9479{
9480 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9481}
9482
5d92ddc3
DM
9483static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9484 const struct btf_param *arg)
9485{
9486 const struct btf_type *t;
9487
9488 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9489 if (!t)
9490 return false;
9491
9492 return true;
9493}
9494
00b85860
KKD
9495/* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9496static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9497 const struct btf *btf,
9498 const struct btf_type *t, int rec)
9499{
9500 const struct btf_type *member_type;
9501 const struct btf_member *member;
9502 u32 i;
9503
9504 if (!btf_type_is_struct(t))
9505 return false;
9506
9507 for_each_member(i, t, member) {
9508 const struct btf_array *array;
9509
9510 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9511 if (btf_type_is_struct(member_type)) {
9512 if (rec >= 3) {
9513 verbose(env, "max struct nesting depth exceeded\n");
9514 return false;
9515 }
9516 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9517 return false;
9518 continue;
9519 }
9520 if (btf_type_is_array(member_type)) {
9521 array = btf_array(member_type);
9522 if (!array->nelems)
9523 return false;
9524 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9525 if (!btf_type_is_scalar(member_type))
9526 return false;
9527 continue;
9528 }
9529 if (!btf_type_is_scalar(member_type))
9530 return false;
9531 }
9532 return true;
9533}
9534
9535
9536static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9537#ifdef CONFIG_NET
9538 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9539 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9540 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9541#endif
9542};
9543
9544enum kfunc_ptr_arg_type {
9545 KF_ARG_PTR_TO_CTX,
ac9f0605 9546 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
00b85860
KKD
9547 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
9548 KF_ARG_PTR_TO_DYNPTR,
06accc87 9549 KF_ARG_PTR_TO_ITER,
8cab76ec
KKD
9550 KF_ARG_PTR_TO_LIST_HEAD,
9551 KF_ARG_PTR_TO_LIST_NODE,
00b85860
KKD
9552 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
9553 KF_ARG_PTR_TO_MEM,
9554 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
5d92ddc3 9555 KF_ARG_PTR_TO_CALLBACK,
cd6791b4
DM
9556 KF_ARG_PTR_TO_RB_ROOT,
9557 KF_ARG_PTR_TO_RB_NODE,
00b85860
KKD
9558};
9559
ac9f0605
KKD
9560enum special_kfunc_type {
9561 KF_bpf_obj_new_impl,
9562 KF_bpf_obj_drop_impl,
8cab76ec
KKD
9563 KF_bpf_list_push_front,
9564 KF_bpf_list_push_back,
9565 KF_bpf_list_pop_front,
9566 KF_bpf_list_pop_back,
fd264ca0 9567 KF_bpf_cast_to_kern_ctx,
a35b9af4 9568 KF_bpf_rdonly_cast,
9bb00b28
YS
9569 KF_bpf_rcu_read_lock,
9570 KF_bpf_rcu_read_unlock,
bd1279ae
DM
9571 KF_bpf_rbtree_remove,
9572 KF_bpf_rbtree_add,
9573 KF_bpf_rbtree_first,
b5964b96 9574 KF_bpf_dynptr_from_skb,
05421aec 9575 KF_bpf_dynptr_from_xdp,
66e3a13e
JK
9576 KF_bpf_dynptr_slice,
9577 KF_bpf_dynptr_slice_rdwr,
ac9f0605
KKD
9578};
9579
9580BTF_SET_START(special_kfunc_set)
9581BTF_ID(func, bpf_obj_new_impl)
9582BTF_ID(func, bpf_obj_drop_impl)
8cab76ec
KKD
9583BTF_ID(func, bpf_list_push_front)
9584BTF_ID(func, bpf_list_push_back)
9585BTF_ID(func, bpf_list_pop_front)
9586BTF_ID(func, bpf_list_pop_back)
fd264ca0 9587BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 9588BTF_ID(func, bpf_rdonly_cast)
bd1279ae
DM
9589BTF_ID(func, bpf_rbtree_remove)
9590BTF_ID(func, bpf_rbtree_add)
9591BTF_ID(func, bpf_rbtree_first)
b5964b96 9592BTF_ID(func, bpf_dynptr_from_skb)
05421aec 9593BTF_ID(func, bpf_dynptr_from_xdp)
66e3a13e
JK
9594BTF_ID(func, bpf_dynptr_slice)
9595BTF_ID(func, bpf_dynptr_slice_rdwr)
ac9f0605
KKD
9596BTF_SET_END(special_kfunc_set)
9597
9598BTF_ID_LIST(special_kfunc_list)
9599BTF_ID(func, bpf_obj_new_impl)
9600BTF_ID(func, bpf_obj_drop_impl)
8cab76ec
KKD
9601BTF_ID(func, bpf_list_push_front)
9602BTF_ID(func, bpf_list_push_back)
9603BTF_ID(func, bpf_list_pop_front)
9604BTF_ID(func, bpf_list_pop_back)
fd264ca0 9605BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 9606BTF_ID(func, bpf_rdonly_cast)
9bb00b28
YS
9607BTF_ID(func, bpf_rcu_read_lock)
9608BTF_ID(func, bpf_rcu_read_unlock)
bd1279ae
DM
9609BTF_ID(func, bpf_rbtree_remove)
9610BTF_ID(func, bpf_rbtree_add)
9611BTF_ID(func, bpf_rbtree_first)
b5964b96 9612BTF_ID(func, bpf_dynptr_from_skb)
05421aec 9613BTF_ID(func, bpf_dynptr_from_xdp)
66e3a13e
JK
9614BTF_ID(func, bpf_dynptr_slice)
9615BTF_ID(func, bpf_dynptr_slice_rdwr)
9bb00b28
YS
9616
9617static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9618{
9619 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9620}
9621
9622static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9623{
9624 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9625}
ac9f0605 9626
00b85860
KKD
9627static enum kfunc_ptr_arg_type
9628get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9629 struct bpf_kfunc_call_arg_meta *meta,
9630 const struct btf_type *t, const struct btf_type *ref_t,
9631 const char *ref_tname, const struct btf_param *args,
9632 int argno, int nargs)
9633{
9634 u32 regno = argno + 1;
9635 struct bpf_reg_state *regs = cur_regs(env);
9636 struct bpf_reg_state *reg = &regs[regno];
9637 bool arg_mem_size = false;
9638
fd264ca0
YS
9639 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9640 return KF_ARG_PTR_TO_CTX;
9641
00b85860
KKD
9642 /* In this function, we verify the kfunc's BTF as per the argument type,
9643 * leaving the rest of the verification with respect to the register
9644 * type to our caller. When a set of conditions hold in the BTF type of
9645 * arguments, we resolve it to a known kfunc_ptr_arg_type.
9646 */
9647 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9648 return KF_ARG_PTR_TO_CTX;
9649
ac9f0605
KKD
9650 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9651 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9652
00b85860
KKD
9653 if (is_kfunc_arg_kptr_get(meta, argno)) {
9654 if (!btf_type_is_ptr(ref_t)) {
9655 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9656 return -EINVAL;
9657 }
9658 ref_t = btf_type_by_id(meta->btf, ref_t->type);
9659 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9660 if (!btf_type_is_struct(ref_t)) {
9661 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9662 meta->func_name, btf_type_str(ref_t), ref_tname);
9663 return -EINVAL;
9664 }
9665 return KF_ARG_PTR_TO_KPTR;
9666 }
9667
9668 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9669 return KF_ARG_PTR_TO_DYNPTR;
9670
06accc87
AN
9671 if (is_kfunc_arg_iter(meta, argno))
9672 return KF_ARG_PTR_TO_ITER;
9673
8cab76ec
KKD
9674 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9675 return KF_ARG_PTR_TO_LIST_HEAD;
9676
9677 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9678 return KF_ARG_PTR_TO_LIST_NODE;
9679
cd6791b4
DM
9680 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9681 return KF_ARG_PTR_TO_RB_ROOT;
9682
9683 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9684 return KF_ARG_PTR_TO_RB_NODE;
9685
00b85860
KKD
9686 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9687 if (!btf_type_is_struct(ref_t)) {
9688 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9689 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9690 return -EINVAL;
9691 }
9692 return KF_ARG_PTR_TO_BTF_ID;
9693 }
9694
5d92ddc3
DM
9695 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9696 return KF_ARG_PTR_TO_CALLBACK;
9697
66e3a13e
JK
9698
9699 if (argno + 1 < nargs &&
9700 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
9701 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
00b85860
KKD
9702 arg_mem_size = true;
9703
9704 /* This is the catch all argument type of register types supported by
9705 * check_helper_mem_access. However, we only allow when argument type is
9706 * pointer to scalar, or struct composed (recursively) of scalars. When
9707 * arg_mem_size is true, the pointer can be void *.
9708 */
9709 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9710 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9711 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9712 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9713 return -EINVAL;
9714 }
9715 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9716}
9717
9718static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9719 struct bpf_reg_state *reg,
9720 const struct btf_type *ref_t,
9721 const char *ref_tname, u32 ref_id,
9722 struct bpf_kfunc_call_arg_meta *meta,
9723 int argno)
9724{
9725 const struct btf_type *reg_ref_t;
9726 bool strict_type_match = false;
9727 const struct btf *reg_btf;
9728 const char *reg_ref_tname;
9729 u32 reg_ref_id;
9730
3f00c523 9731 if (base_type(reg->type) == PTR_TO_BTF_ID) {
00b85860
KKD
9732 reg_btf = reg->btf;
9733 reg_ref_id = reg->btf_id;
9734 } else {
9735 reg_btf = btf_vmlinux;
9736 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9737 }
9738
b613d335
DV
9739 /* Enforce strict type matching for calls to kfuncs that are acquiring
9740 * or releasing a reference, or are no-cast aliases. We do _not_
9741 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9742 * as we want to enable BPF programs to pass types that are bitwise
9743 * equivalent without forcing them to explicitly cast with something
9744 * like bpf_cast_to_kern_ctx().
9745 *
9746 * For example, say we had a type like the following:
9747 *
9748 * struct bpf_cpumask {
9749 * cpumask_t cpumask;
9750 * refcount_t usage;
9751 * };
9752 *
9753 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9754 * to a struct cpumask, so it would be safe to pass a struct
9755 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9756 *
9757 * The philosophy here is similar to how we allow scalars of different
9758 * types to be passed to kfuncs as long as the size is the same. The
9759 * only difference here is that we're simply allowing
9760 * btf_struct_ids_match() to walk the struct at the 0th offset, and
9761 * resolve types.
9762 */
9763 if (is_kfunc_acquire(meta) ||
9764 (is_kfunc_release(meta) && reg->ref_obj_id) ||
9765 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
00b85860
KKD
9766 strict_type_match = true;
9767
b613d335
DV
9768 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9769
00b85860
KKD
9770 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9771 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9772 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9773 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9774 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9775 btf_type_str(reg_ref_t), reg_ref_tname);
9776 return -EINVAL;
9777 }
9778 return 0;
9779}
9780
9781static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9782 struct bpf_reg_state *reg,
9783 const struct btf_type *ref_t,
9784 const char *ref_tname,
9785 struct bpf_kfunc_call_arg_meta *meta,
9786 int argno)
9787{
9788 struct btf_field *kptr_field;
9789
9790 /* check_func_arg_reg_off allows var_off for
9791 * PTR_TO_MAP_VALUE, but we need fixed offset to find
9792 * off_desc.
9793 */
9794 if (!tnum_is_const(reg->var_off)) {
9795 verbose(env, "arg#0 must have constant offset\n");
9796 return -EINVAL;
9797 }
9798
9799 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9800 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9801 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9802 reg->off + reg->var_off.value);
9803 return -EINVAL;
9804 }
9805
9806 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9807 kptr_field->kptr.btf_id, true)) {
9808 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9809 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9810 return -EINVAL;
9811 }
9812 return 0;
9813}
9814
6a3cd331 9815static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
534e86bc 9816{
6a3cd331
DM
9817 struct bpf_verifier_state *state = env->cur_state;
9818
9819 if (!state->active_lock.ptr) {
9820 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9821 return -EFAULT;
9822 }
9823
9824 if (type_flag(reg->type) & NON_OWN_REF) {
9825 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9826 return -EFAULT;
9827 }
9828
9829 reg->type |= NON_OWN_REF;
9830 return 0;
9831}
9832
9833static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9834{
9835 struct bpf_func_state *state, *unused;
534e86bc
KKD
9836 struct bpf_reg_state *reg;
9837 int i;
9838
6a3cd331
DM
9839 state = cur_func(env);
9840
534e86bc 9841 if (!ref_obj_id) {
6a3cd331
DM
9842 verbose(env, "verifier internal error: ref_obj_id is zero for "
9843 "owning -> non-owning conversion\n");
534e86bc
KKD
9844 return -EFAULT;
9845 }
6a3cd331 9846
534e86bc 9847 for (i = 0; i < state->acquired_refs; i++) {
6a3cd331
DM
9848 if (state->refs[i].id != ref_obj_id)
9849 continue;
9850
9851 /* Clear ref_obj_id here so release_reference doesn't clobber
9852 * the whole reg
9853 */
9854 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9855 if (reg->ref_obj_id == ref_obj_id) {
9856 reg->ref_obj_id = 0;
9857 ref_set_non_owning(env, reg);
534e86bc 9858 }
6a3cd331
DM
9859 }));
9860 return 0;
534e86bc 9861 }
6a3cd331 9862
534e86bc
KKD
9863 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9864 return -EFAULT;
9865}
9866
8cab76ec
KKD
9867/* Implementation details:
9868 *
9869 * Each register points to some region of memory, which we define as an
9870 * allocation. Each allocation may embed a bpf_spin_lock which protects any
9871 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9872 * allocation. The lock and the data it protects are colocated in the same
9873 * memory region.
9874 *
9875 * Hence, everytime a register holds a pointer value pointing to such
9876 * allocation, the verifier preserves a unique reg->id for it.
9877 *
9878 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9879 * bpf_spin_lock is called.
9880 *
9881 * To enable this, lock state in the verifier captures two values:
9882 * active_lock.ptr = Register's type specific pointer
9883 * active_lock.id = A unique ID for each register pointer value
9884 *
9885 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9886 * supported register types.
9887 *
9888 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9889 * allocated objects is the reg->btf pointer.
9890 *
9891 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9892 * can establish the provenance of the map value statically for each distinct
9893 * lookup into such maps. They always contain a single map value hence unique
9894 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9895 *
9896 * So, in case of global variables, they use array maps with max_entries = 1,
9897 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9898 * into the same map value as max_entries is 1, as described above).
9899 *
9900 * In case of inner map lookups, the inner map pointer has same map_ptr as the
9901 * outer map pointer (in verifier context), but each lookup into an inner map
9902 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9903 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9904 * will get different reg->id assigned to each lookup, hence different
9905 * active_lock.id.
9906 *
9907 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9908 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9909 * returned from bpf_obj_new. Each allocation receives a new reg->id.
9910 */
9911static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9912{
9913 void *ptr;
9914 u32 id;
9915
9916 switch ((int)reg->type) {
9917 case PTR_TO_MAP_VALUE:
9918 ptr = reg->map_ptr;
9919 break;
9920 case PTR_TO_BTF_ID | MEM_ALLOC:
9921 ptr = reg->btf;
9922 break;
9923 default:
9924 verbose(env, "verifier internal error: unknown reg type for lock check\n");
9925 return -EFAULT;
9926 }
9927 id = reg->id;
9928
9929 if (!env->cur_state->active_lock.ptr)
9930 return -EINVAL;
9931 if (env->cur_state->active_lock.ptr != ptr ||
9932 env->cur_state->active_lock.id != id) {
9933 verbose(env, "held lock and object are not in the same allocation\n");
9934 return -EINVAL;
9935 }
9936 return 0;
9937}
9938
9939static bool is_bpf_list_api_kfunc(u32 btf_id)
9940{
9941 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9942 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9943 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9944 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9945}
9946
cd6791b4
DM
9947static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9948{
9949 return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9950 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9951 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9952}
9953
9954static bool is_bpf_graph_api_kfunc(u32 btf_id)
9955{
9956 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9957}
9958
5d92ddc3
DM
9959static bool is_callback_calling_kfunc(u32 btf_id)
9960{
9961 return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9962}
9963
9964static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9965{
9966 return is_bpf_rbtree_api_kfunc(btf_id);
9967}
9968
cd6791b4
DM
9969static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9970 enum btf_field_type head_field_type,
9971 u32 kfunc_btf_id)
9972{
9973 bool ret;
9974
9975 switch (head_field_type) {
9976 case BPF_LIST_HEAD:
9977 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9978 break;
9979 case BPF_RB_ROOT:
9980 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9981 break;
9982 default:
9983 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9984 btf_field_type_name(head_field_type));
9985 return false;
9986 }
9987
9988 if (!ret)
9989 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9990 btf_field_type_name(head_field_type));
9991 return ret;
9992}
9993
9994static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9995 enum btf_field_type node_field_type,
9996 u32 kfunc_btf_id)
8cab76ec 9997{
cd6791b4
DM
9998 bool ret;
9999
10000 switch (node_field_type) {
10001 case BPF_LIST_NODE:
10002 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
10003 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
10004 break;
10005 case BPF_RB_NODE:
10006 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10007 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
10008 break;
10009 default:
10010 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10011 btf_field_type_name(node_field_type));
10012 return false;
10013 }
10014
10015 if (!ret)
10016 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10017 btf_field_type_name(node_field_type));
10018 return ret;
10019}
10020
10021static int
10022__process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10023 struct bpf_reg_state *reg, u32 regno,
10024 struct bpf_kfunc_call_arg_meta *meta,
10025 enum btf_field_type head_field_type,
10026 struct btf_field **head_field)
10027{
10028 const char *head_type_name;
8cab76ec
KKD
10029 struct btf_field *field;
10030 struct btf_record *rec;
cd6791b4 10031 u32 head_off;
8cab76ec 10032
cd6791b4
DM
10033 if (meta->btf != btf_vmlinux) {
10034 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
8cab76ec
KKD
10035 return -EFAULT;
10036 }
10037
cd6791b4
DM
10038 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10039 return -EFAULT;
10040
10041 head_type_name = btf_field_type_name(head_field_type);
8cab76ec
KKD
10042 if (!tnum_is_const(reg->var_off)) {
10043 verbose(env,
cd6791b4
DM
10044 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10045 regno, head_type_name);
8cab76ec
KKD
10046 return -EINVAL;
10047 }
10048
10049 rec = reg_btf_record(reg);
cd6791b4
DM
10050 head_off = reg->off + reg->var_off.value;
10051 field = btf_record_find(rec, head_off, head_field_type);
8cab76ec 10052 if (!field) {
cd6791b4 10053 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
8cab76ec
KKD
10054 return -EINVAL;
10055 }
10056
10057 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10058 if (check_reg_allocation_locked(env, reg)) {
cd6791b4
DM
10059 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10060 rec->spin_lock_off, head_type_name);
8cab76ec
KKD
10061 return -EINVAL;
10062 }
10063
cd6791b4
DM
10064 if (*head_field) {
10065 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
8cab76ec
KKD
10066 return -EFAULT;
10067 }
cd6791b4 10068 *head_field = field;
8cab76ec
KKD
10069 return 0;
10070}
10071
cd6791b4 10072static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8cab76ec
KKD
10073 struct bpf_reg_state *reg, u32 regno,
10074 struct bpf_kfunc_call_arg_meta *meta)
10075{
cd6791b4
DM
10076 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10077 &meta->arg_list_head.field);
10078}
10079
10080static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10081 struct bpf_reg_state *reg, u32 regno,
10082 struct bpf_kfunc_call_arg_meta *meta)
10083{
10084 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10085 &meta->arg_rbtree_root.field);
10086}
10087
10088static int
10089__process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10090 struct bpf_reg_state *reg, u32 regno,
10091 struct bpf_kfunc_call_arg_meta *meta,
10092 enum btf_field_type head_field_type,
10093 enum btf_field_type node_field_type,
10094 struct btf_field **node_field)
10095{
10096 const char *node_type_name;
8cab76ec
KKD
10097 const struct btf_type *et, *t;
10098 struct btf_field *field;
cd6791b4 10099 u32 node_off;
8cab76ec 10100
cd6791b4
DM
10101 if (meta->btf != btf_vmlinux) {
10102 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
8cab76ec
KKD
10103 return -EFAULT;
10104 }
10105
cd6791b4
DM
10106 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10107 return -EFAULT;
10108
10109 node_type_name = btf_field_type_name(node_field_type);
8cab76ec
KKD
10110 if (!tnum_is_const(reg->var_off)) {
10111 verbose(env,
cd6791b4
DM
10112 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10113 regno, node_type_name);
8cab76ec
KKD
10114 return -EINVAL;
10115 }
10116
cd6791b4
DM
10117 node_off = reg->off + reg->var_off.value;
10118 field = reg_find_field_offset(reg, node_off, node_field_type);
10119 if (!field || field->offset != node_off) {
10120 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
8cab76ec
KKD
10121 return -EINVAL;
10122 }
10123
cd6791b4 10124 field = *node_field;
8cab76ec 10125
30465003 10126 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
8cab76ec 10127 t = btf_type_by_id(reg->btf, reg->btf_id);
30465003
DM
10128 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10129 field->graph_root.value_btf_id, true)) {
cd6791b4 10130 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
8cab76ec 10131 "in struct %s, but arg is at offset=%d in struct %s\n",
cd6791b4
DM
10132 btf_field_type_name(head_field_type),
10133 btf_field_type_name(node_field_type),
30465003
DM
10134 field->graph_root.node_offset,
10135 btf_name_by_offset(field->graph_root.btf, et->name_off),
cd6791b4 10136 node_off, btf_name_by_offset(reg->btf, t->name_off));
8cab76ec
KKD
10137 return -EINVAL;
10138 }
10139
cd6791b4
DM
10140 if (node_off != field->graph_root.node_offset) {
10141 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10142 node_off, btf_field_type_name(node_field_type),
10143 field->graph_root.node_offset,
30465003 10144 btf_name_by_offset(field->graph_root.btf, et->name_off));
8cab76ec
KKD
10145 return -EINVAL;
10146 }
6a3cd331
DM
10147
10148 return 0;
8cab76ec
KKD
10149}
10150
cd6791b4
DM
10151static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10152 struct bpf_reg_state *reg, u32 regno,
10153 struct bpf_kfunc_call_arg_meta *meta)
10154{
10155 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10156 BPF_LIST_HEAD, BPF_LIST_NODE,
10157 &meta->arg_list_head.field);
10158}
10159
10160static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10161 struct bpf_reg_state *reg, u32 regno,
10162 struct bpf_kfunc_call_arg_meta *meta)
10163{
10164 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10165 BPF_RB_ROOT, BPF_RB_NODE,
10166 &meta->arg_rbtree_root.field);
10167}
10168
1d18feb2
JK
10169static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10170 int insn_idx)
00b85860
KKD
10171{
10172 const char *func_name = meta->func_name, *ref_tname;
10173 const struct btf *btf = meta->btf;
10174 const struct btf_param *args;
10175 u32 i, nargs;
10176 int ret;
10177
10178 args = (const struct btf_param *)(meta->func_proto + 1);
10179 nargs = btf_type_vlen(meta->func_proto);
10180 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10181 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10182 MAX_BPF_FUNC_REG_ARGS);
10183 return -EINVAL;
10184 }
10185
10186 /* Check that BTF function arguments match actual types that the
10187 * verifier sees.
10188 */
10189 for (i = 0; i < nargs; i++) {
10190 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10191 const struct btf_type *t, *ref_t, *resolve_ret;
10192 enum bpf_arg_type arg_type = ARG_DONTCARE;
10193 u32 regno = i + 1, ref_id, type_size;
10194 bool is_ret_buf_sz = false;
10195 int kf_arg_type;
10196
10197 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
958cf2e2
KKD
10198
10199 if (is_kfunc_arg_ignore(btf, &args[i]))
10200 continue;
10201
00b85860
KKD
10202 if (btf_type_is_scalar(t)) {
10203 if (reg->type != SCALAR_VALUE) {
10204 verbose(env, "R%d is not a scalar\n", regno);
10205 return -EINVAL;
10206 }
a50388db
KKD
10207
10208 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10209 if (meta->arg_constant.found) {
10210 verbose(env, "verifier internal error: only one constant argument permitted\n");
10211 return -EFAULT;
10212 }
10213 if (!tnum_is_const(reg->var_off)) {
10214 verbose(env, "R%d must be a known constant\n", regno);
10215 return -EINVAL;
10216 }
10217 ret = mark_chain_precision(env, regno);
10218 if (ret < 0)
10219 return ret;
10220 meta->arg_constant.found = true;
10221 meta->arg_constant.value = reg->var_off.value;
10222 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
00b85860
KKD
10223 meta->r0_rdonly = true;
10224 is_ret_buf_sz = true;
10225 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10226 is_ret_buf_sz = true;
10227 }
10228
10229 if (is_ret_buf_sz) {
10230 if (meta->r0_size) {
10231 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10232 return -EINVAL;
10233 }
10234
10235 if (!tnum_is_const(reg->var_off)) {
10236 verbose(env, "R%d is not a const\n", regno);
10237 return -EINVAL;
10238 }
10239
10240 meta->r0_size = reg->var_off.value;
10241 ret = mark_chain_precision(env, regno);
10242 if (ret)
10243 return ret;
10244 }
10245 continue;
10246 }
10247
10248 if (!btf_type_is_ptr(t)) {
10249 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10250 return -EINVAL;
10251 }
10252
20c09d92 10253 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
caf713c3
DV
10254 (register_is_null(reg) || type_may_be_null(reg->type))) {
10255 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10256 return -EACCES;
10257 }
10258
00b85860
KKD
10259 if (reg->ref_obj_id) {
10260 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10261 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10262 regno, reg->ref_obj_id,
10263 meta->ref_obj_id);
10264 return -EFAULT;
10265 }
10266 meta->ref_obj_id = reg->ref_obj_id;
10267 if (is_kfunc_release(meta))
10268 meta->release_regno = regno;
10269 }
10270
10271 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10272 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10273
10274 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10275 if (kf_arg_type < 0)
10276 return kf_arg_type;
10277
10278 switch (kf_arg_type) {
ac9f0605 10279 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
00b85860 10280 case KF_ARG_PTR_TO_BTF_ID:
fca1aa75 10281 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
00b85860 10282 break;
3f00c523
DV
10283
10284 if (!is_trusted_reg(reg)) {
fca1aa75
YS
10285 if (!is_kfunc_rcu(meta)) {
10286 verbose(env, "R%d must be referenced or trusted\n", regno);
10287 return -EINVAL;
10288 }
10289 if (!is_rcu_reg(reg)) {
10290 verbose(env, "R%d must be a rcu pointer\n", regno);
10291 return -EINVAL;
10292 }
00b85860 10293 }
fca1aa75 10294
00b85860
KKD
10295 fallthrough;
10296 case KF_ARG_PTR_TO_CTX:
10297 /* Trusted arguments have the same offset checks as release arguments */
10298 arg_type |= OBJ_RELEASE;
10299 break;
10300 case KF_ARG_PTR_TO_KPTR:
10301 case KF_ARG_PTR_TO_DYNPTR:
06accc87 10302 case KF_ARG_PTR_TO_ITER:
8cab76ec
KKD
10303 case KF_ARG_PTR_TO_LIST_HEAD:
10304 case KF_ARG_PTR_TO_LIST_NODE:
cd6791b4
DM
10305 case KF_ARG_PTR_TO_RB_ROOT:
10306 case KF_ARG_PTR_TO_RB_NODE:
00b85860
KKD
10307 case KF_ARG_PTR_TO_MEM:
10308 case KF_ARG_PTR_TO_MEM_SIZE:
5d92ddc3 10309 case KF_ARG_PTR_TO_CALLBACK:
00b85860
KKD
10310 /* Trusted by default */
10311 break;
10312 default:
10313 WARN_ON_ONCE(1);
10314 return -EFAULT;
10315 }
10316
10317 if (is_kfunc_release(meta) && reg->ref_obj_id)
10318 arg_type |= OBJ_RELEASE;
10319 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10320 if (ret < 0)
10321 return ret;
10322
10323 switch (kf_arg_type) {
10324 case KF_ARG_PTR_TO_CTX:
10325 if (reg->type != PTR_TO_CTX) {
10326 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10327 return -EINVAL;
10328 }
fd264ca0
YS
10329
10330 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10331 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10332 if (ret < 0)
10333 return -EINVAL;
10334 meta->ret_btf_id = ret;
10335 }
00b85860 10336 break;
ac9f0605
KKD
10337 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10338 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10339 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10340 return -EINVAL;
10341 }
10342 if (!reg->ref_obj_id) {
10343 verbose(env, "allocated object must be referenced\n");
10344 return -EINVAL;
10345 }
10346 if (meta->btf == btf_vmlinux &&
10347 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10348 meta->arg_obj_drop.btf = reg->btf;
10349 meta->arg_obj_drop.btf_id = reg->btf_id;
10350 }
10351 break;
00b85860
KKD
10352 case KF_ARG_PTR_TO_KPTR:
10353 if (reg->type != PTR_TO_MAP_VALUE) {
10354 verbose(env, "arg#0 expected pointer to map value\n");
10355 return -EINVAL;
10356 }
10357 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
10358 if (ret < 0)
10359 return ret;
10360 break;
10361 case KF_ARG_PTR_TO_DYNPTR:
d96d937d
JK
10362 {
10363 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10364
6b75bd3d 10365 if (reg->type != PTR_TO_STACK &&
27060531 10366 reg->type != CONST_PTR_TO_DYNPTR) {
6b75bd3d 10367 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
00b85860
KKD
10368 return -EINVAL;
10369 }
10370
d96d937d
JK
10371 if (reg->type == CONST_PTR_TO_DYNPTR)
10372 dynptr_arg_type |= MEM_RDONLY;
10373
10374 if (is_kfunc_arg_uninit(btf, &args[i]))
10375 dynptr_arg_type |= MEM_UNINIT;
10376
b5964b96
JK
10377 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
10378 dynptr_arg_type |= DYNPTR_TYPE_SKB;
05421aec
JK
10379 else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
10380 dynptr_arg_type |= DYNPTR_TYPE_XDP;
b5964b96 10381
d96d937d 10382 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
6b75bd3d
KKD
10383 if (ret < 0)
10384 return ret;
66e3a13e
JK
10385
10386 if (!(dynptr_arg_type & MEM_UNINIT)) {
10387 int id = dynptr_id(env, reg);
10388
10389 if (id < 0) {
10390 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10391 return id;
10392 }
10393 meta->initialized_dynptr.id = id;
10394 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10395 }
10396
00b85860 10397 break;
d96d937d 10398 }
06accc87
AN
10399 case KF_ARG_PTR_TO_ITER:
10400 ret = process_iter_arg(env, regno, insn_idx, meta);
10401 if (ret < 0)
10402 return ret;
10403 break;
8cab76ec
KKD
10404 case KF_ARG_PTR_TO_LIST_HEAD:
10405 if (reg->type != PTR_TO_MAP_VALUE &&
10406 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10407 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10408 return -EINVAL;
10409 }
10410 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10411 verbose(env, "allocated object must be referenced\n");
10412 return -EINVAL;
10413 }
10414 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10415 if (ret < 0)
10416 return ret;
10417 break;
cd6791b4
DM
10418 case KF_ARG_PTR_TO_RB_ROOT:
10419 if (reg->type != PTR_TO_MAP_VALUE &&
10420 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10421 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10422 return -EINVAL;
10423 }
10424 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10425 verbose(env, "allocated object must be referenced\n");
10426 return -EINVAL;
10427 }
10428 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10429 if (ret < 0)
10430 return ret;
10431 break;
8cab76ec
KKD
10432 case KF_ARG_PTR_TO_LIST_NODE:
10433 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10434 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10435 return -EINVAL;
10436 }
10437 if (!reg->ref_obj_id) {
10438 verbose(env, "allocated object must be referenced\n");
10439 return -EINVAL;
10440 }
10441 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10442 if (ret < 0)
10443 return ret;
10444 break;
cd6791b4 10445 case KF_ARG_PTR_TO_RB_NODE:
a40d3632
DM
10446 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10447 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10448 verbose(env, "rbtree_remove node input must be non-owning ref\n");
10449 return -EINVAL;
10450 }
10451 if (in_rbtree_lock_required_cb(env)) {
10452 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10453 return -EINVAL;
10454 }
10455 } else {
10456 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10457 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10458 return -EINVAL;
10459 }
10460 if (!reg->ref_obj_id) {
10461 verbose(env, "allocated object must be referenced\n");
10462 return -EINVAL;
10463 }
cd6791b4 10464 }
a40d3632 10465
cd6791b4
DM
10466 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10467 if (ret < 0)
10468 return ret;
10469 break;
00b85860
KKD
10470 case KF_ARG_PTR_TO_BTF_ID:
10471 /* Only base_type is checked, further checks are done here */
3f00c523 10472 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
fca1aa75 10473 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
3f00c523
DV
10474 !reg2btf_ids[base_type(reg->type)]) {
10475 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10476 verbose(env, "expected %s or socket\n",
10477 reg_type_str(env, base_type(reg->type) |
10478 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
00b85860
KKD
10479 return -EINVAL;
10480 }
10481 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10482 if (ret < 0)
10483 return ret;
10484 break;
10485 case KF_ARG_PTR_TO_MEM:
10486 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10487 if (IS_ERR(resolve_ret)) {
10488 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10489 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10490 return -EINVAL;
10491 }
10492 ret = check_mem_reg(env, reg, regno, type_size);
10493 if (ret < 0)
10494 return ret;
10495 break;
10496 case KF_ARG_PTR_TO_MEM_SIZE:
66e3a13e
JK
10497 {
10498 struct bpf_reg_state *size_reg = &regs[regno + 1];
10499 const struct btf_param *size_arg = &args[i + 1];
10500
10501 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
00b85860
KKD
10502 if (ret < 0) {
10503 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10504 return ret;
10505 }
66e3a13e
JK
10506
10507 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10508 if (meta->arg_constant.found) {
10509 verbose(env, "verifier internal error: only one constant argument permitted\n");
10510 return -EFAULT;
10511 }
10512 if (!tnum_is_const(size_reg->var_off)) {
10513 verbose(env, "R%d must be a known constant\n", regno + 1);
10514 return -EINVAL;
10515 }
10516 meta->arg_constant.found = true;
10517 meta->arg_constant.value = size_reg->var_off.value;
10518 }
10519
10520 /* Skip next '__sz' or '__szk' argument */
00b85860
KKD
10521 i++;
10522 break;
66e3a13e 10523 }
5d92ddc3
DM
10524 case KF_ARG_PTR_TO_CALLBACK:
10525 meta->subprogno = reg->subprogno;
10526 break;
00b85860
KKD
10527 }
10528 }
10529
10530 if (is_kfunc_release(meta) && !meta->release_regno) {
10531 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10532 func_name);
10533 return -EINVAL;
10534 }
10535
10536 return 0;
10537}
10538
07236eab
AN
10539static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10540 struct bpf_insn *insn,
10541 struct bpf_kfunc_call_arg_meta *meta,
10542 const char **kfunc_name)
e6ac2450 10543{
07236eab
AN
10544 const struct btf_type *func, *func_proto;
10545 u32 func_id, *kfunc_flags;
10546 const char *func_name;
2357672c 10547 struct btf *desc_btf;
e6ac2450 10548
07236eab
AN
10549 if (kfunc_name)
10550 *kfunc_name = NULL;
10551
a5d82727 10552 if (!insn->imm)
07236eab 10553 return -EINVAL;
a5d82727 10554
43bf0878 10555 desc_btf = find_kfunc_desc_btf(env, insn->off);
2357672c
KKD
10556 if (IS_ERR(desc_btf))
10557 return PTR_ERR(desc_btf);
10558
e6ac2450 10559 func_id = insn->imm;
2357672c
KKD
10560 func = btf_type_by_id(desc_btf, func_id);
10561 func_name = btf_name_by_offset(desc_btf, func->name_off);
07236eab
AN
10562 if (kfunc_name)
10563 *kfunc_name = func_name;
2357672c 10564 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450 10565
a4703e31
KKD
10566 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10567 if (!kfunc_flags) {
e6ac2450
MKL
10568 return -EACCES;
10569 }
00b85860 10570
07236eab
AN
10571 memset(meta, 0, sizeof(*meta));
10572 meta->btf = desc_btf;
10573 meta->func_id = func_id;
10574 meta->kfunc_flags = *kfunc_flags;
10575 meta->func_proto = func_proto;
10576 meta->func_name = func_name;
10577
10578 return 0;
10579}
10580
10581static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10582 int *insn_idx_p)
10583{
10584 const struct btf_type *t, *ptr_type;
10585 u32 i, nargs, ptr_type_id, release_ref_obj_id;
10586 struct bpf_reg_state *regs = cur_regs(env);
10587 const char *func_name, *ptr_type_name;
10588 bool sleepable, rcu_lock, rcu_unlock;
10589 struct bpf_kfunc_call_arg_meta meta;
10590 struct bpf_insn_aux_data *insn_aux;
10591 int err, insn_idx = *insn_idx_p;
10592 const struct btf_param *args;
10593 const struct btf_type *ret_t;
10594 struct btf *desc_btf;
10595
10596 /* skip for now, but return error when we find this in fixup_kfunc_call */
10597 if (!insn->imm)
10598 return 0;
10599
10600 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10601 if (err == -EACCES && func_name)
10602 verbose(env, "calling kernel function %s is not allowed\n", func_name);
10603 if (err)
10604 return err;
10605 desc_btf = meta.btf;
10606 insn_aux = &env->insn_aux_data[insn_idx];
00b85860 10607
06accc87
AN
10608 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10609
00b85860
KKD
10610 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10611 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
4dd48c6f
AS
10612 return -EACCES;
10613 }
10614
9bb00b28
YS
10615 sleepable = is_kfunc_sleepable(&meta);
10616 if (sleepable && !env->prog->aux->sleepable) {
00b85860
KKD
10617 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10618 return -EACCES;
10619 }
eb1f7f71 10620
9bb00b28
YS
10621 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10622 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9bb00b28
YS
10623
10624 if (env->cur_state->active_rcu_lock) {
10625 struct bpf_func_state *state;
10626 struct bpf_reg_state *reg;
10627
10628 if (rcu_lock) {
10629 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10630 return -EINVAL;
10631 } else if (rcu_unlock) {
10632 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10633 if (reg->type & MEM_RCU) {
fca1aa75 10634 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9bb00b28
YS
10635 reg->type |= PTR_UNTRUSTED;
10636 }
10637 }));
10638 env->cur_state->active_rcu_lock = false;
10639 } else if (sleepable) {
10640 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10641 return -EACCES;
10642 }
10643 } else if (rcu_lock) {
10644 env->cur_state->active_rcu_lock = true;
10645 } else if (rcu_unlock) {
10646 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10647 return -EINVAL;
10648 }
10649
e6ac2450 10650 /* Check the arguments */
1d18feb2 10651 err = check_kfunc_args(env, &meta, insn_idx);
5c073f26 10652 if (err < 0)
e6ac2450 10653 return err;
5c073f26 10654 /* In case of release function, we get register number of refcounted
00b85860 10655 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
5c073f26 10656 */
00b85860
KKD
10657 if (meta.release_regno) {
10658 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
5c073f26
KKD
10659 if (err) {
10660 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
07236eab 10661 func_name, meta.func_id);
5c073f26
KKD
10662 return err;
10663 }
10664 }
e6ac2450 10665
6a3cd331 10666 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
bd1279ae
DM
10667 meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10668 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
6a3cd331
DM
10669 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10670 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10671 if (err) {
10672 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
07236eab 10673 func_name, meta.func_id);
6a3cd331
DM
10674 return err;
10675 }
10676
10677 err = release_reference(env, release_ref_obj_id);
10678 if (err) {
10679 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
07236eab 10680 func_name, meta.func_id);
6a3cd331
DM
10681 return err;
10682 }
10683 }
10684
5d92ddc3
DM
10685 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10686 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10687 set_rbtree_add_callback_state);
10688 if (err) {
10689 verbose(env, "kfunc %s#%d failed callback verification\n",
07236eab 10690 func_name, meta.func_id);
5d92ddc3
DM
10691 return err;
10692 }
10693 }
10694
e6ac2450
MKL
10695 for (i = 0; i < CALLER_SAVED_REGS; i++)
10696 mark_reg_not_init(env, regs, caller_saved[i]);
10697
10698 /* Check return type */
07236eab 10699 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
5c073f26 10700
00b85860 10701 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
958cf2e2
KKD
10702 /* Only exception is bpf_obj_new_impl */
10703 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10704 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10705 return -EINVAL;
10706 }
5c073f26
KKD
10707 }
10708
e6ac2450
MKL
10709 if (btf_type_is_scalar(t)) {
10710 mark_reg_unknown(env, regs, BPF_REG_0);
10711 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10712 } else if (btf_type_is_ptr(t)) {
958cf2e2
KKD
10713 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10714
10715 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10716 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
958cf2e2
KKD
10717 struct btf *ret_btf;
10718 u32 ret_btf_id;
10719
e181d3f1
KKD
10720 if (unlikely(!bpf_global_ma_set))
10721 return -ENOMEM;
10722
958cf2e2
KKD
10723 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10724 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10725 return -EINVAL;
10726 }
10727
10728 ret_btf = env->prog->aux->btf;
10729 ret_btf_id = meta.arg_constant.value;
10730
10731 /* This may be NULL due to user not supplying a BTF */
10732 if (!ret_btf) {
10733 verbose(env, "bpf_obj_new requires prog BTF\n");
10734 return -EINVAL;
10735 }
10736
10737 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10738 if (!ret_t || !__btf_type_is_struct(ret_t)) {
10739 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10740 return -EINVAL;
10741 }
10742
10743 mark_reg_known_zero(env, regs, BPF_REG_0);
10744 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10745 regs[BPF_REG_0].btf = ret_btf;
10746 regs[BPF_REG_0].btf_id = ret_btf_id;
10747
07236eab
AN
10748 insn_aux->obj_new_size = ret_t->size;
10749 insn_aux->kptr_struct_meta =
958cf2e2 10750 btf_find_struct_meta(ret_btf, ret_btf_id);
8cab76ec
KKD
10751 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10752 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10753 struct btf_field *field = meta.arg_list_head.field;
10754
a40d3632
DM
10755 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10756 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10757 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10758 struct btf_field *field = meta.arg_rbtree_root.field;
10759
10760 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
fd264ca0
YS
10761 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10762 mark_reg_known_zero(env, regs, BPF_REG_0);
10763 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10764 regs[BPF_REG_0].btf = desc_btf;
10765 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
a35b9af4
YS
10766 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10767 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10768 if (!ret_t || !btf_type_is_struct(ret_t)) {
10769 verbose(env,
10770 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10771 return -EINVAL;
10772 }
10773
10774 mark_reg_known_zero(env, regs, BPF_REG_0);
10775 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10776 regs[BPF_REG_0].btf = desc_btf;
10777 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
66e3a13e
JK
10778 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10779 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10780 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10781
10782 mark_reg_known_zero(env, regs, BPF_REG_0);
10783
10784 if (!meta.arg_constant.found) {
10785 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10786 return -EFAULT;
10787 }
10788
10789 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10790
10791 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10792 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10793
10794 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10795 regs[BPF_REG_0].type |= MEM_RDONLY;
10796 } else {
10797 /* this will set env->seen_direct_write to true */
10798 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10799 verbose(env, "the prog does not allow writes to packet data\n");
10800 return -EINVAL;
10801 }
10802 }
10803
10804 if (!meta.initialized_dynptr.id) {
10805 verbose(env, "verifier internal error: no dynptr id\n");
10806 return -EFAULT;
10807 }
10808 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10809
10810 /* we don't need to set BPF_REG_0's ref obj id
10811 * because packet slices are not refcounted (see
10812 * dynptr_type_refcounted)
10813 */
958cf2e2
KKD
10814 } else {
10815 verbose(env, "kernel function %s unhandled dynamic return type\n",
10816 meta.func_name);
10817 return -EFAULT;
10818 }
10819 } else if (!__btf_type_is_struct(ptr_type)) {
f4b4eee6
AN
10820 if (!meta.r0_size) {
10821 __u32 sz;
10822
10823 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
10824 meta.r0_size = sz;
10825 meta.r0_rdonly = true;
10826 }
10827 }
eb1f7f71
BT
10828 if (!meta.r0_size) {
10829 ptr_type_name = btf_name_by_offset(desc_btf,
10830 ptr_type->name_off);
10831 verbose(env,
10832 "kernel function %s returns pointer type %s %s is not supported\n",
10833 func_name,
10834 btf_type_str(ptr_type),
10835 ptr_type_name);
10836 return -EINVAL;
10837 }
10838
10839 mark_reg_known_zero(env, regs, BPF_REG_0);
10840 regs[BPF_REG_0].type = PTR_TO_MEM;
10841 regs[BPF_REG_0].mem_size = meta.r0_size;
10842
10843 if (meta.r0_rdonly)
10844 regs[BPF_REG_0].type |= MEM_RDONLY;
10845
10846 /* Ensures we don't access the memory after a release_reference() */
10847 if (meta.ref_obj_id)
10848 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10849 } else {
10850 mark_reg_known_zero(env, regs, BPF_REG_0);
10851 regs[BPF_REG_0].btf = desc_btf;
10852 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10853 regs[BPF_REG_0].btf_id = ptr_type_id;
e6ac2450 10854 }
958cf2e2 10855
00b85860 10856 if (is_kfunc_ret_null(&meta)) {
5c073f26
KKD
10857 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10858 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10859 regs[BPF_REG_0].id = ++env->id_gen;
10860 }
e6ac2450 10861 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
00b85860 10862 if (is_kfunc_acquire(&meta)) {
5c073f26
KKD
10863 int id = acquire_reference_state(env, insn_idx);
10864
10865 if (id < 0)
10866 return id;
00b85860
KKD
10867 if (is_kfunc_ret_null(&meta))
10868 regs[BPF_REG_0].id = id;
5c073f26 10869 regs[BPF_REG_0].ref_obj_id = id;
a40d3632
DM
10870 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10871 ref_set_non_owning(env, &regs[BPF_REG_0]);
5c073f26 10872 }
a40d3632
DM
10873
10874 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10875 invalidate_non_owning_refs(env);
10876
00b85860
KKD
10877 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10878 regs[BPF_REG_0].id = ++env->id_gen;
f6a6a5a9
DM
10879 } else if (btf_type_is_void(t)) {
10880 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10881 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10882 insn_aux->kptr_struct_meta =
10883 btf_find_struct_meta(meta.arg_obj_drop.btf,
10884 meta.arg_obj_drop.btf_id);
10885 }
10886 }
10887 }
e6ac2450 10888
07236eab
AN
10889 nargs = btf_type_vlen(meta.func_proto);
10890 args = (const struct btf_param *)(meta.func_proto + 1);
e6ac2450
MKL
10891 for (i = 0; i < nargs; i++) {
10892 u32 regno = i + 1;
10893
2357672c 10894 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
e6ac2450
MKL
10895 if (btf_type_is_ptr(t))
10896 mark_btf_func_reg_size(env, regno, sizeof(void *));
10897 else
10898 /* scalar. ensured by btf_check_kfunc_arg_match() */
10899 mark_btf_func_reg_size(env, regno, t->size);
10900 }
10901
06accc87
AN
10902 if (is_iter_next_kfunc(&meta)) {
10903 err = process_iter_next_call(env, insn_idx, &meta);
10904 if (err)
10905 return err;
10906 }
10907
e6ac2450
MKL
10908 return 0;
10909}
10910
b03c9f9f
EC
10911static bool signed_add_overflows(s64 a, s64 b)
10912{
10913 /* Do the add in u64, where overflow is well-defined */
10914 s64 res = (s64)((u64)a + (u64)b);
10915
10916 if (b < 0)
10917 return res > a;
10918 return res < a;
10919}
10920
bc895e8b 10921static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
10922{
10923 /* Do the add in u32, where overflow is well-defined */
10924 s32 res = (s32)((u32)a + (u32)b);
10925
10926 if (b < 0)
10927 return res > a;
10928 return res < a;
10929}
10930
bc895e8b 10931static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
10932{
10933 /* Do the sub in u64, where overflow is well-defined */
10934 s64 res = (s64)((u64)a - (u64)b);
10935
10936 if (b < 0)
10937 return res < a;
10938 return res > a;
969bf05e
AS
10939}
10940
3f50f132
JF
10941static bool signed_sub32_overflows(s32 a, s32 b)
10942{
bc895e8b 10943 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
10944 s32 res = (s32)((u32)a - (u32)b);
10945
10946 if (b < 0)
10947 return res < a;
10948 return res > a;
10949}
10950
bb7f0f98
AS
10951static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10952 const struct bpf_reg_state *reg,
10953 enum bpf_reg_type type)
10954{
10955 bool known = tnum_is_const(reg->var_off);
10956 s64 val = reg->var_off.value;
10957 s64 smin = reg->smin_value;
10958
10959 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10960 verbose(env, "math between %s pointer and %lld is not allowed\n",
c25b2ae1 10961 reg_type_str(env, type), val);
bb7f0f98
AS
10962 return false;
10963 }
10964
10965 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10966 verbose(env, "%s pointer offset %d is not allowed\n",
c25b2ae1 10967 reg_type_str(env, type), reg->off);
bb7f0f98
AS
10968 return false;
10969 }
10970
10971 if (smin == S64_MIN) {
10972 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
c25b2ae1 10973 reg_type_str(env, type));
bb7f0f98
AS
10974 return false;
10975 }
10976
10977 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10978 verbose(env, "value %lld makes %s pointer be out of bounds\n",
c25b2ae1 10979 smin, reg_type_str(env, type));
bb7f0f98
AS
10980 return false;
10981 }
10982
10983 return true;
10984}
10985
a6aaece0
DB
10986enum {
10987 REASON_BOUNDS = -1,
10988 REASON_TYPE = -2,
10989 REASON_PATHS = -3,
10990 REASON_LIMIT = -4,
10991 REASON_STACK = -5,
10992};
10993
979d63d5 10994static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 10995 u32 *alu_limit, bool mask_to_left)
979d63d5 10996{
7fedb63a 10997 u32 max = 0, ptr_limit = 0;
979d63d5
DB
10998
10999 switch (ptr_reg->type) {
11000 case PTR_TO_STACK:
1b1597e6 11001 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
11002 * left direction, see BPF_REG_FP. Also, unknown scalar
11003 * offset where we would need to deal with min/max bounds is
11004 * currently prohibited for unprivileged.
1b1597e6
PK
11005 */
11006 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 11007 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 11008 break;
979d63d5 11009 case PTR_TO_MAP_VALUE:
1b1597e6 11010 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
11011 ptr_limit = (mask_to_left ?
11012 ptr_reg->smin_value :
11013 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 11014 break;
979d63d5 11015 default:
a6aaece0 11016 return REASON_TYPE;
979d63d5 11017 }
b658bbb8
DB
11018
11019 if (ptr_limit >= max)
a6aaece0 11020 return REASON_LIMIT;
b658bbb8
DB
11021 *alu_limit = ptr_limit;
11022 return 0;
979d63d5
DB
11023}
11024
d3bd7413
DB
11025static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11026 const struct bpf_insn *insn)
11027{
2c78ee89 11028 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
11029}
11030
11031static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11032 u32 alu_state, u32 alu_limit)
11033{
11034 /* If we arrived here from different branches with different
11035 * state or limits to sanitize, then this won't work.
11036 */
11037 if (aux->alu_state &&
11038 (aux->alu_state != alu_state ||
11039 aux->alu_limit != alu_limit))
a6aaece0 11040 return REASON_PATHS;
d3bd7413 11041
e6ac5933 11042 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
11043 aux->alu_state = alu_state;
11044 aux->alu_limit = alu_limit;
11045 return 0;
11046}
11047
11048static int sanitize_val_alu(struct bpf_verifier_env *env,
11049 struct bpf_insn *insn)
11050{
11051 struct bpf_insn_aux_data *aux = cur_aux(env);
11052
11053 if (can_skip_alu_sanitation(env, insn))
11054 return 0;
11055
11056 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11057}
11058
f5288193
DB
11059static bool sanitize_needed(u8 opcode)
11060{
11061 return opcode == BPF_ADD || opcode == BPF_SUB;
11062}
11063
3d0220f6
DB
11064struct bpf_sanitize_info {
11065 struct bpf_insn_aux_data aux;
bb01a1bb 11066 bool mask_to_left;
3d0220f6
DB
11067};
11068
9183671a
DB
11069static struct bpf_verifier_state *
11070sanitize_speculative_path(struct bpf_verifier_env *env,
11071 const struct bpf_insn *insn,
11072 u32 next_idx, u32 curr_idx)
11073{
11074 struct bpf_verifier_state *branch;
11075 struct bpf_reg_state *regs;
11076
11077 branch = push_stack(env, next_idx, curr_idx, true);
11078 if (branch && insn) {
11079 regs = branch->frame[branch->curframe]->regs;
11080 if (BPF_SRC(insn->code) == BPF_K) {
11081 mark_reg_unknown(env, regs, insn->dst_reg);
11082 } else if (BPF_SRC(insn->code) == BPF_X) {
11083 mark_reg_unknown(env, regs, insn->dst_reg);
11084 mark_reg_unknown(env, regs, insn->src_reg);
11085 }
11086 }
11087 return branch;
11088}
11089
979d63d5
DB
11090static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11091 struct bpf_insn *insn,
11092 const struct bpf_reg_state *ptr_reg,
6f55b2f2 11093 const struct bpf_reg_state *off_reg,
979d63d5 11094 struct bpf_reg_state *dst_reg,
3d0220f6 11095 struct bpf_sanitize_info *info,
7fedb63a 11096 const bool commit_window)
979d63d5 11097{
3d0220f6 11098 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 11099 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 11100 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 11101 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
11102 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11103 u8 opcode = BPF_OP(insn->code);
11104 u32 alu_state, alu_limit;
11105 struct bpf_reg_state tmp;
11106 bool ret;
f232326f 11107 int err;
979d63d5 11108
d3bd7413 11109 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
11110 return 0;
11111
11112 /* We already marked aux for masking from non-speculative
11113 * paths, thus we got here in the first place. We only care
11114 * to explore bad access from here.
11115 */
11116 if (vstate->speculative)
11117 goto do_sim;
11118
bb01a1bb
DB
11119 if (!commit_window) {
11120 if (!tnum_is_const(off_reg->var_off) &&
11121 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11122 return REASON_BOUNDS;
11123
11124 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11125 (opcode == BPF_SUB && !off_is_neg);
11126 }
11127
11128 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
11129 if (err < 0)
11130 return err;
11131
7fedb63a
DB
11132 if (commit_window) {
11133 /* In commit phase we narrow the masking window based on
11134 * the observed pointer move after the simulated operation.
11135 */
3d0220f6
DB
11136 alu_state = info->aux.alu_state;
11137 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
11138 } else {
11139 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 11140 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
11141 alu_state |= ptr_is_dst_reg ?
11142 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
e042aa53
DB
11143
11144 /* Limit pruning on unknown scalars to enable deep search for
11145 * potential masking differences from other program paths.
11146 */
11147 if (!off_is_imm)
11148 env->explore_alu_limits = true;
7fedb63a
DB
11149 }
11150
f232326f
PK
11151 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11152 if (err < 0)
11153 return err;
979d63d5 11154do_sim:
7fedb63a
DB
11155 /* If we're in commit phase, we're done here given we already
11156 * pushed the truncated dst_reg into the speculative verification
11157 * stack.
a7036191
DB
11158 *
11159 * Also, when register is a known constant, we rewrite register-based
11160 * operation to immediate-based, and thus do not need masking (and as
11161 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 11162 */
a7036191 11163 if (commit_window || off_is_imm)
7fedb63a
DB
11164 return 0;
11165
979d63d5
DB
11166 /* Simulate and find potential out-of-bounds access under
11167 * speculative execution from truncation as a result of
11168 * masking when off was not within expected range. If off
11169 * sits in dst, then we temporarily need to move ptr there
11170 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11171 * for cases where we use K-based arithmetic in one direction
11172 * and truncated reg-based in the other in order to explore
11173 * bad access.
11174 */
11175 if (!ptr_is_dst_reg) {
11176 tmp = *dst_reg;
71f656a5 11177 copy_register_state(dst_reg, ptr_reg);
979d63d5 11178 }
9183671a
DB
11179 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11180 env->insn_idx);
0803278b 11181 if (!ptr_is_dst_reg && ret)
979d63d5 11182 *dst_reg = tmp;
a6aaece0
DB
11183 return !ret ? REASON_STACK : 0;
11184}
11185
fe9a5ca7
DB
11186static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11187{
11188 struct bpf_verifier_state *vstate = env->cur_state;
11189
11190 /* If we simulate paths under speculation, we don't update the
11191 * insn as 'seen' such that when we verify unreachable paths in
11192 * the non-speculative domain, sanitize_dead_code() can still
11193 * rewrite/sanitize them.
11194 */
11195 if (!vstate->speculative)
11196 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11197}
11198
a6aaece0
DB
11199static int sanitize_err(struct bpf_verifier_env *env,
11200 const struct bpf_insn *insn, int reason,
11201 const struct bpf_reg_state *off_reg,
11202 const struct bpf_reg_state *dst_reg)
11203{
11204 static const char *err = "pointer arithmetic with it prohibited for !root";
11205 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11206 u32 dst = insn->dst_reg, src = insn->src_reg;
11207
11208 switch (reason) {
11209 case REASON_BOUNDS:
11210 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11211 off_reg == dst_reg ? dst : src, err);
11212 break;
11213 case REASON_TYPE:
11214 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11215 off_reg == dst_reg ? src : dst, err);
11216 break;
11217 case REASON_PATHS:
11218 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11219 dst, op, err);
11220 break;
11221 case REASON_LIMIT:
11222 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11223 dst, op, err);
11224 break;
11225 case REASON_STACK:
11226 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11227 dst, err);
11228 break;
11229 default:
11230 verbose(env, "verifier internal error: unknown reason (%d)\n",
11231 reason);
11232 break;
11233 }
11234
11235 return -EACCES;
979d63d5
DB
11236}
11237
01f810ac
AM
11238/* check that stack access falls within stack limits and that 'reg' doesn't
11239 * have a variable offset.
11240 *
11241 * Variable offset is prohibited for unprivileged mode for simplicity since it
11242 * requires corresponding support in Spectre masking for stack ALU. See also
11243 * retrieve_ptr_limit().
11244 *
11245 *
11246 * 'off' includes 'reg->off'.
11247 */
11248static int check_stack_access_for_ptr_arithmetic(
11249 struct bpf_verifier_env *env,
11250 int regno,
11251 const struct bpf_reg_state *reg,
11252 int off)
11253{
11254 if (!tnum_is_const(reg->var_off)) {
11255 char tn_buf[48];
11256
11257 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11258 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11259 regno, tn_buf, off);
11260 return -EACCES;
11261 }
11262
11263 if (off >= 0 || off < -MAX_BPF_STACK) {
11264 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11265 "prohibited for !root; off=%d\n", regno, off);
11266 return -EACCES;
11267 }
11268
11269 return 0;
11270}
11271
073815b7
DB
11272static int sanitize_check_bounds(struct bpf_verifier_env *env,
11273 const struct bpf_insn *insn,
11274 const struct bpf_reg_state *dst_reg)
11275{
11276 u32 dst = insn->dst_reg;
11277
11278 /* For unprivileged we require that resulting offset must be in bounds
11279 * in order to be able to sanitize access later on.
11280 */
11281 if (env->bypass_spec_v1)
11282 return 0;
11283
11284 switch (dst_reg->type) {
11285 case PTR_TO_STACK:
11286 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11287 dst_reg->off + dst_reg->var_off.value))
11288 return -EACCES;
11289 break;
11290 case PTR_TO_MAP_VALUE:
61df10c7 11291 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
073815b7
DB
11292 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11293 "prohibited for !root\n", dst);
11294 return -EACCES;
11295 }
11296 break;
11297 default:
11298 break;
11299 }
11300
11301 return 0;
11302}
01f810ac 11303
f1174f77 11304/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
11305 * Caller should also handle BPF_MOV case separately.
11306 * If we return -EACCES, caller may want to try again treating pointer as a
11307 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
11308 */
11309static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11310 struct bpf_insn *insn,
11311 const struct bpf_reg_state *ptr_reg,
11312 const struct bpf_reg_state *off_reg)
969bf05e 11313{
f4d7e40a
AS
11314 struct bpf_verifier_state *vstate = env->cur_state;
11315 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11316 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 11317 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
11318 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11319 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11320 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11321 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 11322 struct bpf_sanitize_info info = {};
969bf05e 11323 u8 opcode = BPF_OP(insn->code);
24c109bb 11324 u32 dst = insn->dst_reg;
979d63d5 11325 int ret;
969bf05e 11326
f1174f77 11327 dst_reg = &regs[dst];
969bf05e 11328
6f16101e
DB
11329 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11330 smin_val > smax_val || umin_val > umax_val) {
11331 /* Taint dst register if offset had invalid bounds derived from
11332 * e.g. dead branches.
11333 */
f54c7898 11334 __mark_reg_unknown(env, dst_reg);
6f16101e 11335 return 0;
f1174f77
EC
11336 }
11337
11338 if (BPF_CLASS(insn->code) != BPF_ALU64) {
11339 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
11340 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11341 __mark_reg_unknown(env, dst_reg);
11342 return 0;
11343 }
11344
82abbf8d
AS
11345 verbose(env,
11346 "R%d 32-bit pointer arithmetic prohibited\n",
11347 dst);
f1174f77 11348 return -EACCES;
969bf05e
AS
11349 }
11350
c25b2ae1 11351 if (ptr_reg->type & PTR_MAYBE_NULL) {
aad2eeaf 11352 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
c25b2ae1 11353 dst, reg_type_str(env, ptr_reg->type));
f1174f77 11354 return -EACCES;
c25b2ae1
HL
11355 }
11356
11357 switch (base_type(ptr_reg->type)) {
aad2eeaf 11358 case CONST_PTR_TO_MAP:
7c696732
YS
11359 /* smin_val represents the known value */
11360 if (known && smin_val == 0 && opcode == BPF_ADD)
11361 break;
8731745e 11362 fallthrough;
aad2eeaf 11363 case PTR_TO_PACKET_END:
c64b7983 11364 case PTR_TO_SOCKET:
46f8bc92 11365 case PTR_TO_SOCK_COMMON:
655a51e5 11366 case PTR_TO_TCP_SOCK:
fada7fdc 11367 case PTR_TO_XDP_SOCK:
aad2eeaf 11368 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
c25b2ae1 11369 dst, reg_type_str(env, ptr_reg->type));
f1174f77 11370 return -EACCES;
aad2eeaf
JS
11371 default:
11372 break;
f1174f77
EC
11373 }
11374
11375 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11376 * The id may be overwritten later if we create a new variable offset.
969bf05e 11377 */
f1174f77
EC
11378 dst_reg->type = ptr_reg->type;
11379 dst_reg->id = ptr_reg->id;
969bf05e 11380
bb7f0f98
AS
11381 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11382 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11383 return -EINVAL;
11384
3f50f132
JF
11385 /* pointer types do not carry 32-bit bounds at the moment. */
11386 __mark_reg32_unbounded(dst_reg);
11387
7fedb63a
DB
11388 if (sanitize_needed(opcode)) {
11389 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 11390 &info, false);
a6aaece0
DB
11391 if (ret < 0)
11392 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 11393 }
a6aaece0 11394
f1174f77
EC
11395 switch (opcode) {
11396 case BPF_ADD:
11397 /* We can take a fixed offset as long as it doesn't overflow
11398 * the s32 'off' field
969bf05e 11399 */
b03c9f9f
EC
11400 if (known && (ptr_reg->off + smin_val ==
11401 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 11402 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
11403 dst_reg->smin_value = smin_ptr;
11404 dst_reg->smax_value = smax_ptr;
11405 dst_reg->umin_value = umin_ptr;
11406 dst_reg->umax_value = umax_ptr;
f1174f77 11407 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 11408 dst_reg->off = ptr_reg->off + smin_val;
0962590e 11409 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
11410 break;
11411 }
f1174f77
EC
11412 /* A new variable offset is created. Note that off_reg->off
11413 * == 0, since it's a scalar.
11414 * dst_reg gets the pointer type and since some positive
11415 * integer value was added to the pointer, give it a new 'id'
11416 * if it's a PTR_TO_PACKET.
11417 * this creates a new 'base' pointer, off_reg (variable) gets
11418 * added into the variable offset, and we copy the fixed offset
11419 * from ptr_reg.
969bf05e 11420 */
b03c9f9f
EC
11421 if (signed_add_overflows(smin_ptr, smin_val) ||
11422 signed_add_overflows(smax_ptr, smax_val)) {
11423 dst_reg->smin_value = S64_MIN;
11424 dst_reg->smax_value = S64_MAX;
11425 } else {
11426 dst_reg->smin_value = smin_ptr + smin_val;
11427 dst_reg->smax_value = smax_ptr + smax_val;
11428 }
11429 if (umin_ptr + umin_val < umin_ptr ||
11430 umax_ptr + umax_val < umax_ptr) {
11431 dst_reg->umin_value = 0;
11432 dst_reg->umax_value = U64_MAX;
11433 } else {
11434 dst_reg->umin_value = umin_ptr + umin_val;
11435 dst_reg->umax_value = umax_ptr + umax_val;
11436 }
f1174f77
EC
11437 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11438 dst_reg->off = ptr_reg->off;
0962590e 11439 dst_reg->raw = ptr_reg->raw;
de8f3a83 11440 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
11441 dst_reg->id = ++env->id_gen;
11442 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 11443 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
11444 }
11445 break;
11446 case BPF_SUB:
11447 if (dst_reg == off_reg) {
11448 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
11449 verbose(env, "R%d tried to subtract pointer from scalar\n",
11450 dst);
f1174f77
EC
11451 return -EACCES;
11452 }
11453 /* We don't allow subtraction from FP, because (according to
11454 * test_verifier.c test "invalid fp arithmetic", JITs might not
11455 * be able to deal with it.
969bf05e 11456 */
f1174f77 11457 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
11458 verbose(env, "R%d subtraction from stack pointer prohibited\n",
11459 dst);
f1174f77
EC
11460 return -EACCES;
11461 }
b03c9f9f
EC
11462 if (known && (ptr_reg->off - smin_val ==
11463 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 11464 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
11465 dst_reg->smin_value = smin_ptr;
11466 dst_reg->smax_value = smax_ptr;
11467 dst_reg->umin_value = umin_ptr;
11468 dst_reg->umax_value = umax_ptr;
f1174f77
EC
11469 dst_reg->var_off = ptr_reg->var_off;
11470 dst_reg->id = ptr_reg->id;
b03c9f9f 11471 dst_reg->off = ptr_reg->off - smin_val;
0962590e 11472 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
11473 break;
11474 }
f1174f77
EC
11475 /* A new variable offset is created. If the subtrahend is known
11476 * nonnegative, then any reg->range we had before is still good.
969bf05e 11477 */
b03c9f9f
EC
11478 if (signed_sub_overflows(smin_ptr, smax_val) ||
11479 signed_sub_overflows(smax_ptr, smin_val)) {
11480 /* Overflow possible, we know nothing */
11481 dst_reg->smin_value = S64_MIN;
11482 dst_reg->smax_value = S64_MAX;
11483 } else {
11484 dst_reg->smin_value = smin_ptr - smax_val;
11485 dst_reg->smax_value = smax_ptr - smin_val;
11486 }
11487 if (umin_ptr < umax_val) {
11488 /* Overflow possible, we know nothing */
11489 dst_reg->umin_value = 0;
11490 dst_reg->umax_value = U64_MAX;
11491 } else {
11492 /* Cannot overflow (as long as bounds are consistent) */
11493 dst_reg->umin_value = umin_ptr - umax_val;
11494 dst_reg->umax_value = umax_ptr - umin_val;
11495 }
f1174f77
EC
11496 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11497 dst_reg->off = ptr_reg->off;
0962590e 11498 dst_reg->raw = ptr_reg->raw;
de8f3a83 11499 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
11500 dst_reg->id = ++env->id_gen;
11501 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 11502 if (smin_val < 0)
22dc4a0f 11503 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 11504 }
f1174f77
EC
11505 break;
11506 case BPF_AND:
11507 case BPF_OR:
11508 case BPF_XOR:
82abbf8d
AS
11509 /* bitwise ops on pointers are troublesome, prohibit. */
11510 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11511 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
11512 return -EACCES;
11513 default:
11514 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
11515 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11516 dst, bpf_alu_string[opcode >> 4]);
f1174f77 11517 return -EACCES;
43188702
JF
11518 }
11519
bb7f0f98
AS
11520 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11521 return -EINVAL;
3844d153 11522 reg_bounds_sync(dst_reg);
073815b7
DB
11523 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11524 return -EACCES;
7fedb63a
DB
11525 if (sanitize_needed(opcode)) {
11526 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 11527 &info, true);
7fedb63a
DB
11528 if (ret < 0)
11529 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
11530 }
11531
43188702
JF
11532 return 0;
11533}
11534
3f50f132
JF
11535static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11536 struct bpf_reg_state *src_reg)
11537{
11538 s32 smin_val = src_reg->s32_min_value;
11539 s32 smax_val = src_reg->s32_max_value;
11540 u32 umin_val = src_reg->u32_min_value;
11541 u32 umax_val = src_reg->u32_max_value;
11542
11543 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11544 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11545 dst_reg->s32_min_value = S32_MIN;
11546 dst_reg->s32_max_value = S32_MAX;
11547 } else {
11548 dst_reg->s32_min_value += smin_val;
11549 dst_reg->s32_max_value += smax_val;
11550 }
11551 if (dst_reg->u32_min_value + umin_val < umin_val ||
11552 dst_reg->u32_max_value + umax_val < umax_val) {
11553 dst_reg->u32_min_value = 0;
11554 dst_reg->u32_max_value = U32_MAX;
11555 } else {
11556 dst_reg->u32_min_value += umin_val;
11557 dst_reg->u32_max_value += umax_val;
11558 }
11559}
11560
07cd2631
JF
11561static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11562 struct bpf_reg_state *src_reg)
11563{
11564 s64 smin_val = src_reg->smin_value;
11565 s64 smax_val = src_reg->smax_value;
11566 u64 umin_val = src_reg->umin_value;
11567 u64 umax_val = src_reg->umax_value;
11568
11569 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11570 signed_add_overflows(dst_reg->smax_value, smax_val)) {
11571 dst_reg->smin_value = S64_MIN;
11572 dst_reg->smax_value = S64_MAX;
11573 } else {
11574 dst_reg->smin_value += smin_val;
11575 dst_reg->smax_value += smax_val;
11576 }
11577 if (dst_reg->umin_value + umin_val < umin_val ||
11578 dst_reg->umax_value + umax_val < umax_val) {
11579 dst_reg->umin_value = 0;
11580 dst_reg->umax_value = U64_MAX;
11581 } else {
11582 dst_reg->umin_value += umin_val;
11583 dst_reg->umax_value += umax_val;
11584 }
3f50f132
JF
11585}
11586
11587static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11588 struct bpf_reg_state *src_reg)
11589{
11590 s32 smin_val = src_reg->s32_min_value;
11591 s32 smax_val = src_reg->s32_max_value;
11592 u32 umin_val = src_reg->u32_min_value;
11593 u32 umax_val = src_reg->u32_max_value;
11594
11595 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11596 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11597 /* Overflow possible, we know nothing */
11598 dst_reg->s32_min_value = S32_MIN;
11599 dst_reg->s32_max_value = S32_MAX;
11600 } else {
11601 dst_reg->s32_min_value -= smax_val;
11602 dst_reg->s32_max_value -= smin_val;
11603 }
11604 if (dst_reg->u32_min_value < umax_val) {
11605 /* Overflow possible, we know nothing */
11606 dst_reg->u32_min_value = 0;
11607 dst_reg->u32_max_value = U32_MAX;
11608 } else {
11609 /* Cannot overflow (as long as bounds are consistent) */
11610 dst_reg->u32_min_value -= umax_val;
11611 dst_reg->u32_max_value -= umin_val;
11612 }
07cd2631
JF
11613}
11614
11615static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11616 struct bpf_reg_state *src_reg)
11617{
11618 s64 smin_val = src_reg->smin_value;
11619 s64 smax_val = src_reg->smax_value;
11620 u64 umin_val = src_reg->umin_value;
11621 u64 umax_val = src_reg->umax_value;
11622
11623 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11624 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11625 /* Overflow possible, we know nothing */
11626 dst_reg->smin_value = S64_MIN;
11627 dst_reg->smax_value = S64_MAX;
11628 } else {
11629 dst_reg->smin_value -= smax_val;
11630 dst_reg->smax_value -= smin_val;
11631 }
11632 if (dst_reg->umin_value < umax_val) {
11633 /* Overflow possible, we know nothing */
11634 dst_reg->umin_value = 0;
11635 dst_reg->umax_value = U64_MAX;
11636 } else {
11637 /* Cannot overflow (as long as bounds are consistent) */
11638 dst_reg->umin_value -= umax_val;
11639 dst_reg->umax_value -= umin_val;
11640 }
3f50f132
JF
11641}
11642
11643static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11644 struct bpf_reg_state *src_reg)
11645{
11646 s32 smin_val = src_reg->s32_min_value;
11647 u32 umin_val = src_reg->u32_min_value;
11648 u32 umax_val = src_reg->u32_max_value;
11649
11650 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11651 /* Ain't nobody got time to multiply that sign */
11652 __mark_reg32_unbounded(dst_reg);
11653 return;
11654 }
11655 /* Both values are positive, so we can work with unsigned and
11656 * copy the result to signed (unless it exceeds S32_MAX).
11657 */
11658 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11659 /* Potential overflow, we know nothing */
11660 __mark_reg32_unbounded(dst_reg);
11661 return;
11662 }
11663 dst_reg->u32_min_value *= umin_val;
11664 dst_reg->u32_max_value *= umax_val;
11665 if (dst_reg->u32_max_value > S32_MAX) {
11666 /* Overflow possible, we know nothing */
11667 dst_reg->s32_min_value = S32_MIN;
11668 dst_reg->s32_max_value = S32_MAX;
11669 } else {
11670 dst_reg->s32_min_value = dst_reg->u32_min_value;
11671 dst_reg->s32_max_value = dst_reg->u32_max_value;
11672 }
07cd2631
JF
11673}
11674
11675static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11676 struct bpf_reg_state *src_reg)
11677{
11678 s64 smin_val = src_reg->smin_value;
11679 u64 umin_val = src_reg->umin_value;
11680 u64 umax_val = src_reg->umax_value;
11681
07cd2631
JF
11682 if (smin_val < 0 || dst_reg->smin_value < 0) {
11683 /* Ain't nobody got time to multiply that sign */
3f50f132 11684 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
11685 return;
11686 }
11687 /* Both values are positive, so we can work with unsigned and
11688 * copy the result to signed (unless it exceeds S64_MAX).
11689 */
11690 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11691 /* Potential overflow, we know nothing */
3f50f132 11692 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
11693 return;
11694 }
11695 dst_reg->umin_value *= umin_val;
11696 dst_reg->umax_value *= umax_val;
11697 if (dst_reg->umax_value > S64_MAX) {
11698 /* Overflow possible, we know nothing */
11699 dst_reg->smin_value = S64_MIN;
11700 dst_reg->smax_value = S64_MAX;
11701 } else {
11702 dst_reg->smin_value = dst_reg->umin_value;
11703 dst_reg->smax_value = dst_reg->umax_value;
11704 }
11705}
11706
3f50f132
JF
11707static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11708 struct bpf_reg_state *src_reg)
11709{
11710 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11711 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11712 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11713 s32 smin_val = src_reg->s32_min_value;
11714 u32 umax_val = src_reg->u32_max_value;
11715
049c4e13
DB
11716 if (src_known && dst_known) {
11717 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 11718 return;
049c4e13 11719 }
3f50f132
JF
11720
11721 /* We get our minimum from the var_off, since that's inherently
11722 * bitwise. Our maximum is the minimum of the operands' maxima.
11723 */
11724 dst_reg->u32_min_value = var32_off.value;
11725 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11726 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11727 /* Lose signed bounds when ANDing negative numbers,
11728 * ain't nobody got time for that.
11729 */
11730 dst_reg->s32_min_value = S32_MIN;
11731 dst_reg->s32_max_value = S32_MAX;
11732 } else {
11733 /* ANDing two positives gives a positive, so safe to
11734 * cast result into s64.
11735 */
11736 dst_reg->s32_min_value = dst_reg->u32_min_value;
11737 dst_reg->s32_max_value = dst_reg->u32_max_value;
11738 }
3f50f132
JF
11739}
11740
07cd2631
JF
11741static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11742 struct bpf_reg_state *src_reg)
11743{
3f50f132
JF
11744 bool src_known = tnum_is_const(src_reg->var_off);
11745 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
11746 s64 smin_val = src_reg->smin_value;
11747 u64 umax_val = src_reg->umax_value;
11748
3f50f132 11749 if (src_known && dst_known) {
4fbb38a3 11750 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
11751 return;
11752 }
11753
07cd2631
JF
11754 /* We get our minimum from the var_off, since that's inherently
11755 * bitwise. Our maximum is the minimum of the operands' maxima.
11756 */
07cd2631
JF
11757 dst_reg->umin_value = dst_reg->var_off.value;
11758 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11759 if (dst_reg->smin_value < 0 || smin_val < 0) {
11760 /* Lose signed bounds when ANDing negative numbers,
11761 * ain't nobody got time for that.
11762 */
11763 dst_reg->smin_value = S64_MIN;
11764 dst_reg->smax_value = S64_MAX;
11765 } else {
11766 /* ANDing two positives gives a positive, so safe to
11767 * cast result into s64.
11768 */
11769 dst_reg->smin_value = dst_reg->umin_value;
11770 dst_reg->smax_value = dst_reg->umax_value;
11771 }
11772 /* We may learn something more from the var_off */
11773 __update_reg_bounds(dst_reg);
11774}
11775
3f50f132
JF
11776static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11777 struct bpf_reg_state *src_reg)
11778{
11779 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11780 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11781 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
11782 s32 smin_val = src_reg->s32_min_value;
11783 u32 umin_val = src_reg->u32_min_value;
3f50f132 11784
049c4e13
DB
11785 if (src_known && dst_known) {
11786 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 11787 return;
049c4e13 11788 }
3f50f132
JF
11789
11790 /* We get our maximum from the var_off, and our minimum is the
11791 * maximum of the operands' minima
11792 */
11793 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11794 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11795 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11796 /* Lose signed bounds when ORing negative numbers,
11797 * ain't nobody got time for that.
11798 */
11799 dst_reg->s32_min_value = S32_MIN;
11800 dst_reg->s32_max_value = S32_MAX;
11801 } else {
11802 /* ORing two positives gives a positive, so safe to
11803 * cast result into s64.
11804 */
5b9fbeb7
DB
11805 dst_reg->s32_min_value = dst_reg->u32_min_value;
11806 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
11807 }
11808}
11809
07cd2631
JF
11810static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11811 struct bpf_reg_state *src_reg)
11812{
3f50f132
JF
11813 bool src_known = tnum_is_const(src_reg->var_off);
11814 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
11815 s64 smin_val = src_reg->smin_value;
11816 u64 umin_val = src_reg->umin_value;
11817
3f50f132 11818 if (src_known && dst_known) {
4fbb38a3 11819 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
11820 return;
11821 }
11822
07cd2631
JF
11823 /* We get our maximum from the var_off, and our minimum is the
11824 * maximum of the operands' minima
11825 */
07cd2631
JF
11826 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11827 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11828 if (dst_reg->smin_value < 0 || smin_val < 0) {
11829 /* Lose signed bounds when ORing negative numbers,
11830 * ain't nobody got time for that.
11831 */
11832 dst_reg->smin_value = S64_MIN;
11833 dst_reg->smax_value = S64_MAX;
11834 } else {
11835 /* ORing two positives gives a positive, so safe to
11836 * cast result into s64.
11837 */
11838 dst_reg->smin_value = dst_reg->umin_value;
11839 dst_reg->smax_value = dst_reg->umax_value;
11840 }
11841 /* We may learn something more from the var_off */
11842 __update_reg_bounds(dst_reg);
11843}
11844
2921c90d
YS
11845static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11846 struct bpf_reg_state *src_reg)
11847{
11848 bool src_known = tnum_subreg_is_const(src_reg->var_off);
11849 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11850 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11851 s32 smin_val = src_reg->s32_min_value;
11852
049c4e13
DB
11853 if (src_known && dst_known) {
11854 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 11855 return;
049c4e13 11856 }
2921c90d
YS
11857
11858 /* We get both minimum and maximum from the var32_off. */
11859 dst_reg->u32_min_value = var32_off.value;
11860 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11861
11862 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11863 /* XORing two positive sign numbers gives a positive,
11864 * so safe to cast u32 result into s32.
11865 */
11866 dst_reg->s32_min_value = dst_reg->u32_min_value;
11867 dst_reg->s32_max_value = dst_reg->u32_max_value;
11868 } else {
11869 dst_reg->s32_min_value = S32_MIN;
11870 dst_reg->s32_max_value = S32_MAX;
11871 }
11872}
11873
11874static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11875 struct bpf_reg_state *src_reg)
11876{
11877 bool src_known = tnum_is_const(src_reg->var_off);
11878 bool dst_known = tnum_is_const(dst_reg->var_off);
11879 s64 smin_val = src_reg->smin_value;
11880
11881 if (src_known && dst_known) {
11882 /* dst_reg->var_off.value has been updated earlier */
11883 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11884 return;
11885 }
11886
11887 /* We get both minimum and maximum from the var_off. */
11888 dst_reg->umin_value = dst_reg->var_off.value;
11889 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11890
11891 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11892 /* XORing two positive sign numbers gives a positive,
11893 * so safe to cast u64 result into s64.
11894 */
11895 dst_reg->smin_value = dst_reg->umin_value;
11896 dst_reg->smax_value = dst_reg->umax_value;
11897 } else {
11898 dst_reg->smin_value = S64_MIN;
11899 dst_reg->smax_value = S64_MAX;
11900 }
11901
11902 __update_reg_bounds(dst_reg);
11903}
11904
3f50f132
JF
11905static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11906 u64 umin_val, u64 umax_val)
07cd2631 11907{
07cd2631
JF
11908 /* We lose all sign bit information (except what we can pick
11909 * up from var_off)
11910 */
3f50f132
JF
11911 dst_reg->s32_min_value = S32_MIN;
11912 dst_reg->s32_max_value = S32_MAX;
11913 /* If we might shift our top bit out, then we know nothing */
11914 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11915 dst_reg->u32_min_value = 0;
11916 dst_reg->u32_max_value = U32_MAX;
11917 } else {
11918 dst_reg->u32_min_value <<= umin_val;
11919 dst_reg->u32_max_value <<= umax_val;
11920 }
11921}
11922
11923static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11924 struct bpf_reg_state *src_reg)
11925{
11926 u32 umax_val = src_reg->u32_max_value;
11927 u32 umin_val = src_reg->u32_min_value;
11928 /* u32 alu operation will zext upper bits */
11929 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11930
11931 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11932 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11933 /* Not required but being careful mark reg64 bounds as unknown so
11934 * that we are forced to pick them up from tnum and zext later and
11935 * if some path skips this step we are still safe.
11936 */
11937 __mark_reg64_unbounded(dst_reg);
11938 __update_reg32_bounds(dst_reg);
11939}
11940
11941static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11942 u64 umin_val, u64 umax_val)
11943{
11944 /* Special case <<32 because it is a common compiler pattern to sign
11945 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11946 * positive we know this shift will also be positive so we can track
11947 * bounds correctly. Otherwise we lose all sign bit information except
11948 * what we can pick up from var_off. Perhaps we can generalize this
11949 * later to shifts of any length.
11950 */
11951 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11952 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11953 else
11954 dst_reg->smax_value = S64_MAX;
11955
11956 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11957 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11958 else
11959 dst_reg->smin_value = S64_MIN;
11960
07cd2631
JF
11961 /* If we might shift our top bit out, then we know nothing */
11962 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11963 dst_reg->umin_value = 0;
11964 dst_reg->umax_value = U64_MAX;
11965 } else {
11966 dst_reg->umin_value <<= umin_val;
11967 dst_reg->umax_value <<= umax_val;
11968 }
3f50f132
JF
11969}
11970
11971static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11972 struct bpf_reg_state *src_reg)
11973{
11974 u64 umax_val = src_reg->umax_value;
11975 u64 umin_val = src_reg->umin_value;
11976
11977 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
11978 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11979 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11980
07cd2631
JF
11981 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11982 /* We may learn something more from the var_off */
11983 __update_reg_bounds(dst_reg);
11984}
11985
3f50f132
JF
11986static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11987 struct bpf_reg_state *src_reg)
11988{
11989 struct tnum subreg = tnum_subreg(dst_reg->var_off);
11990 u32 umax_val = src_reg->u32_max_value;
11991 u32 umin_val = src_reg->u32_min_value;
11992
11993 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
11994 * be negative, then either:
11995 * 1) src_reg might be zero, so the sign bit of the result is
11996 * unknown, so we lose our signed bounds
11997 * 2) it's known negative, thus the unsigned bounds capture the
11998 * signed bounds
11999 * 3) the signed bounds cross zero, so they tell us nothing
12000 * about the result
12001 * If the value in dst_reg is known nonnegative, then again the
18b24d78 12002 * unsigned bounds capture the signed bounds.
3f50f132
JF
12003 * Thus, in all cases it suffices to blow away our signed bounds
12004 * and rely on inferring new ones from the unsigned bounds and
12005 * var_off of the result.
12006 */
12007 dst_reg->s32_min_value = S32_MIN;
12008 dst_reg->s32_max_value = S32_MAX;
12009
12010 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12011 dst_reg->u32_min_value >>= umax_val;
12012 dst_reg->u32_max_value >>= umin_val;
12013
12014 __mark_reg64_unbounded(dst_reg);
12015 __update_reg32_bounds(dst_reg);
12016}
12017
07cd2631
JF
12018static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12019 struct bpf_reg_state *src_reg)
12020{
12021 u64 umax_val = src_reg->umax_value;
12022 u64 umin_val = src_reg->umin_value;
12023
12024 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12025 * be negative, then either:
12026 * 1) src_reg might be zero, so the sign bit of the result is
12027 * unknown, so we lose our signed bounds
12028 * 2) it's known negative, thus the unsigned bounds capture the
12029 * signed bounds
12030 * 3) the signed bounds cross zero, so they tell us nothing
12031 * about the result
12032 * If the value in dst_reg is known nonnegative, then again the
18b24d78 12033 * unsigned bounds capture the signed bounds.
07cd2631
JF
12034 * Thus, in all cases it suffices to blow away our signed bounds
12035 * and rely on inferring new ones from the unsigned bounds and
12036 * var_off of the result.
12037 */
12038 dst_reg->smin_value = S64_MIN;
12039 dst_reg->smax_value = S64_MAX;
12040 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12041 dst_reg->umin_value >>= umax_val;
12042 dst_reg->umax_value >>= umin_val;
3f50f132
JF
12043
12044 /* Its not easy to operate on alu32 bounds here because it depends
12045 * on bits being shifted in. Take easy way out and mark unbounded
12046 * so we can recalculate later from tnum.
12047 */
12048 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
12049 __update_reg_bounds(dst_reg);
12050}
12051
3f50f132
JF
12052static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12053 struct bpf_reg_state *src_reg)
07cd2631 12054{
3f50f132 12055 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
12056
12057 /* Upon reaching here, src_known is true and
12058 * umax_val is equal to umin_val.
12059 */
3f50f132
JF
12060 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12061 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 12062
3f50f132
JF
12063 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12064
12065 /* blow away the dst_reg umin_value/umax_value and rely on
12066 * dst_reg var_off to refine the result.
12067 */
12068 dst_reg->u32_min_value = 0;
12069 dst_reg->u32_max_value = U32_MAX;
12070
12071 __mark_reg64_unbounded(dst_reg);
12072 __update_reg32_bounds(dst_reg);
12073}
12074
12075static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12076 struct bpf_reg_state *src_reg)
12077{
12078 u64 umin_val = src_reg->umin_value;
12079
12080 /* Upon reaching here, src_known is true and umax_val is equal
12081 * to umin_val.
12082 */
12083 dst_reg->smin_value >>= umin_val;
12084 dst_reg->smax_value >>= umin_val;
12085
12086 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
12087
12088 /* blow away the dst_reg umin_value/umax_value and rely on
12089 * dst_reg var_off to refine the result.
12090 */
12091 dst_reg->umin_value = 0;
12092 dst_reg->umax_value = U64_MAX;
3f50f132
JF
12093
12094 /* Its not easy to operate on alu32 bounds here because it depends
12095 * on bits being shifted in from upper 32-bits. Take easy way out
12096 * and mark unbounded so we can recalculate later from tnum.
12097 */
12098 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
12099 __update_reg_bounds(dst_reg);
12100}
12101
468f6eaf
JH
12102/* WARNING: This function does calculations on 64-bit values, but the actual
12103 * execution may occur on 32-bit values. Therefore, things like bitshifts
12104 * need extra checks in the 32-bit case.
12105 */
f1174f77
EC
12106static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12107 struct bpf_insn *insn,
12108 struct bpf_reg_state *dst_reg,
12109 struct bpf_reg_state src_reg)
969bf05e 12110{
638f5b90 12111 struct bpf_reg_state *regs = cur_regs(env);
48461135 12112 u8 opcode = BPF_OP(insn->code);
b0b3fb67 12113 bool src_known;
b03c9f9f
EC
12114 s64 smin_val, smax_val;
12115 u64 umin_val, umax_val;
3f50f132
JF
12116 s32 s32_min_val, s32_max_val;
12117 u32 u32_min_val, u32_max_val;
468f6eaf 12118 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 12119 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 12120 int ret;
b799207e 12121
b03c9f9f
EC
12122 smin_val = src_reg.smin_value;
12123 smax_val = src_reg.smax_value;
12124 umin_val = src_reg.umin_value;
12125 umax_val = src_reg.umax_value;
f23cc643 12126
3f50f132
JF
12127 s32_min_val = src_reg.s32_min_value;
12128 s32_max_val = src_reg.s32_max_value;
12129 u32_min_val = src_reg.u32_min_value;
12130 u32_max_val = src_reg.u32_max_value;
12131
12132 if (alu32) {
12133 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
12134 if ((src_known &&
12135 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12136 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12137 /* Taint dst register if offset had invalid bounds
12138 * derived from e.g. dead branches.
12139 */
12140 __mark_reg_unknown(env, dst_reg);
12141 return 0;
12142 }
12143 } else {
12144 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
12145 if ((src_known &&
12146 (smin_val != smax_val || umin_val != umax_val)) ||
12147 smin_val > smax_val || umin_val > umax_val) {
12148 /* Taint dst register if offset had invalid bounds
12149 * derived from e.g. dead branches.
12150 */
12151 __mark_reg_unknown(env, dst_reg);
12152 return 0;
12153 }
6f16101e
DB
12154 }
12155
bb7f0f98
AS
12156 if (!src_known &&
12157 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 12158 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
12159 return 0;
12160 }
12161
f5288193
DB
12162 if (sanitize_needed(opcode)) {
12163 ret = sanitize_val_alu(env, insn);
12164 if (ret < 0)
12165 return sanitize_err(env, insn, ret, NULL, NULL);
12166 }
12167
3f50f132
JF
12168 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12169 * There are two classes of instructions: The first class we track both
12170 * alu32 and alu64 sign/unsigned bounds independently this provides the
12171 * greatest amount of precision when alu operations are mixed with jmp32
12172 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12173 * and BPF_OR. This is possible because these ops have fairly easy to
12174 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12175 * See alu32 verifier tests for examples. The second class of
12176 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12177 * with regards to tracking sign/unsigned bounds because the bits may
12178 * cross subreg boundaries in the alu64 case. When this happens we mark
12179 * the reg unbounded in the subreg bound space and use the resulting
12180 * tnum to calculate an approximation of the sign/unsigned bounds.
12181 */
48461135
JB
12182 switch (opcode) {
12183 case BPF_ADD:
3f50f132 12184 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 12185 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 12186 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
12187 break;
12188 case BPF_SUB:
3f50f132 12189 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 12190 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 12191 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
12192 break;
12193 case BPF_MUL:
3f50f132
JF
12194 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12195 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 12196 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
12197 break;
12198 case BPF_AND:
3f50f132
JF
12199 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12200 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 12201 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
12202 break;
12203 case BPF_OR:
3f50f132
JF
12204 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12205 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 12206 scalar_min_max_or(dst_reg, &src_reg);
48461135 12207 break;
2921c90d
YS
12208 case BPF_XOR:
12209 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12210 scalar32_min_max_xor(dst_reg, &src_reg);
12211 scalar_min_max_xor(dst_reg, &src_reg);
12212 break;
48461135 12213 case BPF_LSH:
468f6eaf
JH
12214 if (umax_val >= insn_bitness) {
12215 /* Shifts greater than 31 or 63 are undefined.
12216 * This includes shifts by a negative number.
b03c9f9f 12217 */
61bd5218 12218 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
12219 break;
12220 }
3f50f132
JF
12221 if (alu32)
12222 scalar32_min_max_lsh(dst_reg, &src_reg);
12223 else
12224 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
12225 break;
12226 case BPF_RSH:
468f6eaf
JH
12227 if (umax_val >= insn_bitness) {
12228 /* Shifts greater than 31 or 63 are undefined.
12229 * This includes shifts by a negative number.
b03c9f9f 12230 */
61bd5218 12231 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
12232 break;
12233 }
3f50f132
JF
12234 if (alu32)
12235 scalar32_min_max_rsh(dst_reg, &src_reg);
12236 else
12237 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 12238 break;
9cbe1f5a
YS
12239 case BPF_ARSH:
12240 if (umax_val >= insn_bitness) {
12241 /* Shifts greater than 31 or 63 are undefined.
12242 * This includes shifts by a negative number.
12243 */
12244 mark_reg_unknown(env, regs, insn->dst_reg);
12245 break;
12246 }
3f50f132
JF
12247 if (alu32)
12248 scalar32_min_max_arsh(dst_reg, &src_reg);
12249 else
12250 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 12251 break;
48461135 12252 default:
61bd5218 12253 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
12254 break;
12255 }
12256
3f50f132
JF
12257 /* ALU32 ops are zero extended into 64bit register */
12258 if (alu32)
12259 zext_32_to_64(dst_reg);
3844d153 12260 reg_bounds_sync(dst_reg);
f1174f77
EC
12261 return 0;
12262}
12263
12264/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12265 * and var_off.
12266 */
12267static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12268 struct bpf_insn *insn)
12269{
f4d7e40a
AS
12270 struct bpf_verifier_state *vstate = env->cur_state;
12271 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12272 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
12273 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12274 u8 opcode = BPF_OP(insn->code);
b5dc0163 12275 int err;
f1174f77
EC
12276
12277 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
12278 src_reg = NULL;
12279 if (dst_reg->type != SCALAR_VALUE)
12280 ptr_reg = dst_reg;
75748837
AS
12281 else
12282 /* Make sure ID is cleared otherwise dst_reg min/max could be
12283 * incorrectly propagated into other registers by find_equal_scalars()
12284 */
12285 dst_reg->id = 0;
f1174f77
EC
12286 if (BPF_SRC(insn->code) == BPF_X) {
12287 src_reg = &regs[insn->src_reg];
f1174f77
EC
12288 if (src_reg->type != SCALAR_VALUE) {
12289 if (dst_reg->type != SCALAR_VALUE) {
12290 /* Combining two pointers by any ALU op yields
82abbf8d
AS
12291 * an arbitrary scalar. Disallow all math except
12292 * pointer subtraction
f1174f77 12293 */
dd066823 12294 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
12295 mark_reg_unknown(env, regs, insn->dst_reg);
12296 return 0;
f1174f77 12297 }
82abbf8d
AS
12298 verbose(env, "R%d pointer %s pointer prohibited\n",
12299 insn->dst_reg,
12300 bpf_alu_string[opcode >> 4]);
12301 return -EACCES;
f1174f77
EC
12302 } else {
12303 /* scalar += pointer
12304 * This is legal, but we have to reverse our
12305 * src/dest handling in computing the range
12306 */
b5dc0163
AS
12307 err = mark_chain_precision(env, insn->dst_reg);
12308 if (err)
12309 return err;
82abbf8d
AS
12310 return adjust_ptr_min_max_vals(env, insn,
12311 src_reg, dst_reg);
f1174f77
EC
12312 }
12313 } else if (ptr_reg) {
12314 /* pointer += scalar */
b5dc0163
AS
12315 err = mark_chain_precision(env, insn->src_reg);
12316 if (err)
12317 return err;
82abbf8d
AS
12318 return adjust_ptr_min_max_vals(env, insn,
12319 dst_reg, src_reg);
a3b666bf
AN
12320 } else if (dst_reg->precise) {
12321 /* if dst_reg is precise, src_reg should be precise as well */
12322 err = mark_chain_precision(env, insn->src_reg);
12323 if (err)
12324 return err;
f1174f77
EC
12325 }
12326 } else {
12327 /* Pretend the src is a reg with a known value, since we only
12328 * need to be able to read from this state.
12329 */
12330 off_reg.type = SCALAR_VALUE;
b03c9f9f 12331 __mark_reg_known(&off_reg, insn->imm);
f1174f77 12332 src_reg = &off_reg;
82abbf8d
AS
12333 if (ptr_reg) /* pointer += K */
12334 return adjust_ptr_min_max_vals(env, insn,
12335 ptr_reg, src_reg);
f1174f77
EC
12336 }
12337
12338 /* Got here implies adding two SCALAR_VALUEs */
12339 if (WARN_ON_ONCE(ptr_reg)) {
0f55f9ed 12340 print_verifier_state(env, state, true);
61bd5218 12341 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
12342 return -EINVAL;
12343 }
12344 if (WARN_ON(!src_reg)) {
0f55f9ed 12345 print_verifier_state(env, state, true);
61bd5218 12346 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
12347 return -EINVAL;
12348 }
12349 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
12350}
12351
17a52670 12352/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 12353static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 12354{
638f5b90 12355 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
12356 u8 opcode = BPF_OP(insn->code);
12357 int err;
12358
12359 if (opcode == BPF_END || opcode == BPF_NEG) {
12360 if (opcode == BPF_NEG) {
395e942d 12361 if (BPF_SRC(insn->code) != BPF_K ||
17a52670
AS
12362 insn->src_reg != BPF_REG_0 ||
12363 insn->off != 0 || insn->imm != 0) {
61bd5218 12364 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
12365 return -EINVAL;
12366 }
12367 } else {
12368 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
12369 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12370 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 12371 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
12372 return -EINVAL;
12373 }
12374 }
12375
12376 /* check src operand */
dc503a8a 12377 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
12378 if (err)
12379 return err;
12380
1be7f75d 12381 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 12382 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
12383 insn->dst_reg);
12384 return -EACCES;
12385 }
12386
17a52670 12387 /* check dest operand */
dc503a8a 12388 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
12389 if (err)
12390 return err;
12391
12392 } else if (opcode == BPF_MOV) {
12393
12394 if (BPF_SRC(insn->code) == BPF_X) {
12395 if (insn->imm != 0 || insn->off != 0) {
61bd5218 12396 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
12397 return -EINVAL;
12398 }
12399
12400 /* check src operand */
dc503a8a 12401 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
12402 if (err)
12403 return err;
12404 } else {
12405 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 12406 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
12407 return -EINVAL;
12408 }
12409 }
12410
fbeb1603
AF
12411 /* check dest operand, mark as required later */
12412 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
12413 if (err)
12414 return err;
12415
12416 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
12417 struct bpf_reg_state *src_reg = regs + insn->src_reg;
12418 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12419
17a52670
AS
12420 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12421 /* case: R1 = R2
12422 * copy register state to dest reg
12423 */
75748837
AS
12424 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12425 /* Assign src and dst registers the same ID
12426 * that will be used by find_equal_scalars()
12427 * to propagate min/max range.
12428 */
12429 src_reg->id = ++env->id_gen;
71f656a5 12430 copy_register_state(dst_reg, src_reg);
e434b8cd 12431 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 12432 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 12433 } else {
f1174f77 12434 /* R1 = (u32) R2 */
1be7f75d 12435 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
12436 verbose(env,
12437 "R%d partial copy of pointer\n",
1be7f75d
AS
12438 insn->src_reg);
12439 return -EACCES;
e434b8cd 12440 } else if (src_reg->type == SCALAR_VALUE) {
71f656a5 12441 copy_register_state(dst_reg, src_reg);
75748837
AS
12442 /* Make sure ID is cleared otherwise
12443 * dst_reg min/max could be incorrectly
12444 * propagated into src_reg by find_equal_scalars()
12445 */
12446 dst_reg->id = 0;
e434b8cd 12447 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 12448 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
12449 } else {
12450 mark_reg_unknown(env, regs,
12451 insn->dst_reg);
1be7f75d 12452 }
3f50f132 12453 zext_32_to_64(dst_reg);
3844d153 12454 reg_bounds_sync(dst_reg);
17a52670
AS
12455 }
12456 } else {
12457 /* case: R = imm
12458 * remember the value we stored into this reg
12459 */
fbeb1603
AF
12460 /* clear any state __mark_reg_known doesn't set */
12461 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 12462 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
12463 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12464 __mark_reg_known(regs + insn->dst_reg,
12465 insn->imm);
12466 } else {
12467 __mark_reg_known(regs + insn->dst_reg,
12468 (u32)insn->imm);
12469 }
17a52670
AS
12470 }
12471
12472 } else if (opcode > BPF_END) {
61bd5218 12473 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
12474 return -EINVAL;
12475
12476 } else { /* all other ALU ops: and, sub, xor, add, ... */
12477
17a52670
AS
12478 if (BPF_SRC(insn->code) == BPF_X) {
12479 if (insn->imm != 0 || insn->off != 0) {
61bd5218 12480 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
12481 return -EINVAL;
12482 }
12483 /* check src1 operand */
dc503a8a 12484 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
12485 if (err)
12486 return err;
12487 } else {
12488 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 12489 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
12490 return -EINVAL;
12491 }
12492 }
12493
12494 /* check src2 operand */
dc503a8a 12495 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
12496 if (err)
12497 return err;
12498
12499 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12500 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 12501 verbose(env, "div by zero\n");
17a52670
AS
12502 return -EINVAL;
12503 }
12504
229394e8
RV
12505 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12506 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12507 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12508
12509 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 12510 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
12511 return -EINVAL;
12512 }
12513 }
12514
1a0dc1ac 12515 /* check dest operand */
dc503a8a 12516 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
12517 if (err)
12518 return err;
12519
f1174f77 12520 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
12521 }
12522
12523 return 0;
12524}
12525
f4d7e40a 12526static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 12527 struct bpf_reg_state *dst_reg,
f8ddadc4 12528 enum bpf_reg_type type,
fb2a311a 12529 bool range_right_open)
969bf05e 12530{
b239da34
KKD
12531 struct bpf_func_state *state;
12532 struct bpf_reg_state *reg;
12533 int new_range;
2d2be8ca 12534
fb2a311a
DB
12535 if (dst_reg->off < 0 ||
12536 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
12537 /* This doesn't give us any range */
12538 return;
12539
b03c9f9f
EC
12540 if (dst_reg->umax_value > MAX_PACKET_OFF ||
12541 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
12542 /* Risk of overflow. For instance, ptr + (1<<63) may be less
12543 * than pkt_end, but that's because it's also less than pkt.
12544 */
12545 return;
12546
fb2a311a
DB
12547 new_range = dst_reg->off;
12548 if (range_right_open)
2fa7d94a 12549 new_range++;
fb2a311a
DB
12550
12551 /* Examples for register markings:
2d2be8ca 12552 *
fb2a311a 12553 * pkt_data in dst register:
2d2be8ca
DB
12554 *
12555 * r2 = r3;
12556 * r2 += 8;
12557 * if (r2 > pkt_end) goto <handle exception>
12558 * <access okay>
12559 *
b4e432f1
DB
12560 * r2 = r3;
12561 * r2 += 8;
12562 * if (r2 < pkt_end) goto <access okay>
12563 * <handle exception>
12564 *
2d2be8ca
DB
12565 * Where:
12566 * r2 == dst_reg, pkt_end == src_reg
12567 * r2=pkt(id=n,off=8,r=0)
12568 * r3=pkt(id=n,off=0,r=0)
12569 *
fb2a311a 12570 * pkt_data in src register:
2d2be8ca
DB
12571 *
12572 * r2 = r3;
12573 * r2 += 8;
12574 * if (pkt_end >= r2) goto <access okay>
12575 * <handle exception>
12576 *
b4e432f1
DB
12577 * r2 = r3;
12578 * r2 += 8;
12579 * if (pkt_end <= r2) goto <handle exception>
12580 * <access okay>
12581 *
2d2be8ca
DB
12582 * Where:
12583 * pkt_end == dst_reg, r2 == src_reg
12584 * r2=pkt(id=n,off=8,r=0)
12585 * r3=pkt(id=n,off=0,r=0)
12586 *
12587 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
12588 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12589 * and [r3, r3 + 8-1) respectively is safe to access depending on
12590 * the check.
969bf05e 12591 */
2d2be8ca 12592
f1174f77
EC
12593 /* If our ids match, then we must have the same max_value. And we
12594 * don't care about the other reg's fixed offset, since if it's too big
12595 * the range won't allow anything.
12596 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12597 */
b239da34
KKD
12598 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12599 if (reg->type == type && reg->id == dst_reg->id)
12600 /* keep the maximum range already checked */
12601 reg->range = max(reg->range, new_range);
12602 }));
969bf05e
AS
12603}
12604
3f50f132 12605static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 12606{
3f50f132
JF
12607 struct tnum subreg = tnum_subreg(reg->var_off);
12608 s32 sval = (s32)val;
a72dafaf 12609
3f50f132
JF
12610 switch (opcode) {
12611 case BPF_JEQ:
12612 if (tnum_is_const(subreg))
12613 return !!tnum_equals_const(subreg, val);
12614 break;
12615 case BPF_JNE:
12616 if (tnum_is_const(subreg))
12617 return !tnum_equals_const(subreg, val);
12618 break;
12619 case BPF_JSET:
12620 if ((~subreg.mask & subreg.value) & val)
12621 return 1;
12622 if (!((subreg.mask | subreg.value) & val))
12623 return 0;
12624 break;
12625 case BPF_JGT:
12626 if (reg->u32_min_value > val)
12627 return 1;
12628 else if (reg->u32_max_value <= val)
12629 return 0;
12630 break;
12631 case BPF_JSGT:
12632 if (reg->s32_min_value > sval)
12633 return 1;
ee114dd6 12634 else if (reg->s32_max_value <= sval)
3f50f132
JF
12635 return 0;
12636 break;
12637 case BPF_JLT:
12638 if (reg->u32_max_value < val)
12639 return 1;
12640 else if (reg->u32_min_value >= val)
12641 return 0;
12642 break;
12643 case BPF_JSLT:
12644 if (reg->s32_max_value < sval)
12645 return 1;
12646 else if (reg->s32_min_value >= sval)
12647 return 0;
12648 break;
12649 case BPF_JGE:
12650 if (reg->u32_min_value >= val)
12651 return 1;
12652 else if (reg->u32_max_value < val)
12653 return 0;
12654 break;
12655 case BPF_JSGE:
12656 if (reg->s32_min_value >= sval)
12657 return 1;
12658 else if (reg->s32_max_value < sval)
12659 return 0;
12660 break;
12661 case BPF_JLE:
12662 if (reg->u32_max_value <= val)
12663 return 1;
12664 else if (reg->u32_min_value > val)
12665 return 0;
12666 break;
12667 case BPF_JSLE:
12668 if (reg->s32_max_value <= sval)
12669 return 1;
12670 else if (reg->s32_min_value > sval)
12671 return 0;
12672 break;
12673 }
4f7b3e82 12674
3f50f132
JF
12675 return -1;
12676}
092ed096 12677
3f50f132
JF
12678
12679static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12680{
12681 s64 sval = (s64)val;
a72dafaf 12682
4f7b3e82
AS
12683 switch (opcode) {
12684 case BPF_JEQ:
12685 if (tnum_is_const(reg->var_off))
12686 return !!tnum_equals_const(reg->var_off, val);
12687 break;
12688 case BPF_JNE:
12689 if (tnum_is_const(reg->var_off))
12690 return !tnum_equals_const(reg->var_off, val);
12691 break;
960ea056
JK
12692 case BPF_JSET:
12693 if ((~reg->var_off.mask & reg->var_off.value) & val)
12694 return 1;
12695 if (!((reg->var_off.mask | reg->var_off.value) & val))
12696 return 0;
12697 break;
4f7b3e82
AS
12698 case BPF_JGT:
12699 if (reg->umin_value > val)
12700 return 1;
12701 else if (reg->umax_value <= val)
12702 return 0;
12703 break;
12704 case BPF_JSGT:
a72dafaf 12705 if (reg->smin_value > sval)
4f7b3e82 12706 return 1;
ee114dd6 12707 else if (reg->smax_value <= sval)
4f7b3e82
AS
12708 return 0;
12709 break;
12710 case BPF_JLT:
12711 if (reg->umax_value < val)
12712 return 1;
12713 else if (reg->umin_value >= val)
12714 return 0;
12715 break;
12716 case BPF_JSLT:
a72dafaf 12717 if (reg->smax_value < sval)
4f7b3e82 12718 return 1;
a72dafaf 12719 else if (reg->smin_value >= sval)
4f7b3e82
AS
12720 return 0;
12721 break;
12722 case BPF_JGE:
12723 if (reg->umin_value >= val)
12724 return 1;
12725 else if (reg->umax_value < val)
12726 return 0;
12727 break;
12728 case BPF_JSGE:
a72dafaf 12729 if (reg->smin_value >= sval)
4f7b3e82 12730 return 1;
a72dafaf 12731 else if (reg->smax_value < sval)
4f7b3e82
AS
12732 return 0;
12733 break;
12734 case BPF_JLE:
12735 if (reg->umax_value <= val)
12736 return 1;
12737 else if (reg->umin_value > val)
12738 return 0;
12739 break;
12740 case BPF_JSLE:
a72dafaf 12741 if (reg->smax_value <= sval)
4f7b3e82 12742 return 1;
a72dafaf 12743 else if (reg->smin_value > sval)
4f7b3e82
AS
12744 return 0;
12745 break;
12746 }
12747
12748 return -1;
12749}
12750
3f50f132
JF
12751/* compute branch direction of the expression "if (reg opcode val) goto target;"
12752 * and return:
12753 * 1 - branch will be taken and "goto target" will be executed
12754 * 0 - branch will not be taken and fall-through to next insn
12755 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12756 * range [0,10]
604dca5e 12757 */
3f50f132
JF
12758static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12759 bool is_jmp32)
604dca5e 12760{
cac616db
JF
12761 if (__is_pointer_value(false, reg)) {
12762 if (!reg_type_not_null(reg->type))
12763 return -1;
12764
12765 /* If pointer is valid tests against zero will fail so we can
12766 * use this to direct branch taken.
12767 */
12768 if (val != 0)
12769 return -1;
12770
12771 switch (opcode) {
12772 case BPF_JEQ:
12773 return 0;
12774 case BPF_JNE:
12775 return 1;
12776 default:
12777 return -1;
12778 }
12779 }
604dca5e 12780
3f50f132
JF
12781 if (is_jmp32)
12782 return is_branch32_taken(reg, val, opcode);
12783 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
12784}
12785
6d94e741
AS
12786static int flip_opcode(u32 opcode)
12787{
12788 /* How can we transform "a <op> b" into "b <op> a"? */
12789 static const u8 opcode_flip[16] = {
12790 /* these stay the same */
12791 [BPF_JEQ >> 4] = BPF_JEQ,
12792 [BPF_JNE >> 4] = BPF_JNE,
12793 [BPF_JSET >> 4] = BPF_JSET,
12794 /* these swap "lesser" and "greater" (L and G in the opcodes) */
12795 [BPF_JGE >> 4] = BPF_JLE,
12796 [BPF_JGT >> 4] = BPF_JLT,
12797 [BPF_JLE >> 4] = BPF_JGE,
12798 [BPF_JLT >> 4] = BPF_JGT,
12799 [BPF_JSGE >> 4] = BPF_JSLE,
12800 [BPF_JSGT >> 4] = BPF_JSLT,
12801 [BPF_JSLE >> 4] = BPF_JSGE,
12802 [BPF_JSLT >> 4] = BPF_JSGT
12803 };
12804 return opcode_flip[opcode >> 4];
12805}
12806
12807static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12808 struct bpf_reg_state *src_reg,
12809 u8 opcode)
12810{
12811 struct bpf_reg_state *pkt;
12812
12813 if (src_reg->type == PTR_TO_PACKET_END) {
12814 pkt = dst_reg;
12815 } else if (dst_reg->type == PTR_TO_PACKET_END) {
12816 pkt = src_reg;
12817 opcode = flip_opcode(opcode);
12818 } else {
12819 return -1;
12820 }
12821
12822 if (pkt->range >= 0)
12823 return -1;
12824
12825 switch (opcode) {
12826 case BPF_JLE:
12827 /* pkt <= pkt_end */
12828 fallthrough;
12829 case BPF_JGT:
12830 /* pkt > pkt_end */
12831 if (pkt->range == BEYOND_PKT_END)
12832 /* pkt has at last one extra byte beyond pkt_end */
12833 return opcode == BPF_JGT;
12834 break;
12835 case BPF_JLT:
12836 /* pkt < pkt_end */
12837 fallthrough;
12838 case BPF_JGE:
12839 /* pkt >= pkt_end */
12840 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12841 return opcode == BPF_JGE;
12842 break;
12843 }
12844 return -1;
12845}
12846
48461135
JB
12847/* Adjusts the register min/max values in the case that the dst_reg is the
12848 * variable register that we are working on, and src_reg is a constant or we're
12849 * simply doing a BPF_K check.
f1174f77 12850 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
12851 */
12852static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
12853 struct bpf_reg_state *false_reg,
12854 u64 val, u32 val32,
092ed096 12855 u8 opcode, bool is_jmp32)
48461135 12856{
3f50f132
JF
12857 struct tnum false_32off = tnum_subreg(false_reg->var_off);
12858 struct tnum false_64off = false_reg->var_off;
12859 struct tnum true_32off = tnum_subreg(true_reg->var_off);
12860 struct tnum true_64off = true_reg->var_off;
12861 s64 sval = (s64)val;
12862 s32 sval32 = (s32)val32;
a72dafaf 12863
f1174f77
EC
12864 /* If the dst_reg is a pointer, we can't learn anything about its
12865 * variable offset from the compare (unless src_reg were a pointer into
12866 * the same object, but we don't bother with that.
12867 * Since false_reg and true_reg have the same type by construction, we
12868 * only need to check one of them for pointerness.
12869 */
12870 if (__is_pointer_value(false, false_reg))
12871 return;
4cabc5b1 12872
48461135 12873 switch (opcode) {
a12ca627
DB
12874 /* JEQ/JNE comparison doesn't change the register equivalence.
12875 *
12876 * r1 = r2;
12877 * if (r1 == 42) goto label;
12878 * ...
12879 * label: // here both r1 and r2 are known to be 42.
12880 *
12881 * Hence when marking register as known preserve it's ID.
12882 */
48461135 12883 case BPF_JEQ:
a12ca627
DB
12884 if (is_jmp32) {
12885 __mark_reg32_known(true_reg, val32);
12886 true_32off = tnum_subreg(true_reg->var_off);
12887 } else {
12888 ___mark_reg_known(true_reg, val);
12889 true_64off = true_reg->var_off;
12890 }
12891 break;
48461135 12892 case BPF_JNE:
a12ca627
DB
12893 if (is_jmp32) {
12894 __mark_reg32_known(false_reg, val32);
12895 false_32off = tnum_subreg(false_reg->var_off);
12896 } else {
12897 ___mark_reg_known(false_reg, val);
12898 false_64off = false_reg->var_off;
12899 }
48461135 12900 break;
960ea056 12901 case BPF_JSET:
3f50f132
JF
12902 if (is_jmp32) {
12903 false_32off = tnum_and(false_32off, tnum_const(~val32));
12904 if (is_power_of_2(val32))
12905 true_32off = tnum_or(true_32off,
12906 tnum_const(val32));
12907 } else {
12908 false_64off = tnum_and(false_64off, tnum_const(~val));
12909 if (is_power_of_2(val))
12910 true_64off = tnum_or(true_64off,
12911 tnum_const(val));
12912 }
960ea056 12913 break;
48461135 12914 case BPF_JGE:
a72dafaf
JW
12915 case BPF_JGT:
12916 {
3f50f132
JF
12917 if (is_jmp32) {
12918 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
12919 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12920
12921 false_reg->u32_max_value = min(false_reg->u32_max_value,
12922 false_umax);
12923 true_reg->u32_min_value = max(true_reg->u32_min_value,
12924 true_umin);
12925 } else {
12926 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
12927 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12928
12929 false_reg->umax_value = min(false_reg->umax_value, false_umax);
12930 true_reg->umin_value = max(true_reg->umin_value, true_umin);
12931 }
b03c9f9f 12932 break;
a72dafaf 12933 }
48461135 12934 case BPF_JSGE:
a72dafaf
JW
12935 case BPF_JSGT:
12936 {
3f50f132
JF
12937 if (is_jmp32) {
12938 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
12939 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 12940
3f50f132
JF
12941 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12942 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12943 } else {
12944 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
12945 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12946
12947 false_reg->smax_value = min(false_reg->smax_value, false_smax);
12948 true_reg->smin_value = max(true_reg->smin_value, true_smin);
12949 }
48461135 12950 break;
a72dafaf 12951 }
b4e432f1 12952 case BPF_JLE:
a72dafaf
JW
12953 case BPF_JLT:
12954 {
3f50f132
JF
12955 if (is_jmp32) {
12956 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
12957 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12958
12959 false_reg->u32_min_value = max(false_reg->u32_min_value,
12960 false_umin);
12961 true_reg->u32_max_value = min(true_reg->u32_max_value,
12962 true_umax);
12963 } else {
12964 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
12965 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12966
12967 false_reg->umin_value = max(false_reg->umin_value, false_umin);
12968 true_reg->umax_value = min(true_reg->umax_value, true_umax);
12969 }
b4e432f1 12970 break;
a72dafaf 12971 }
b4e432f1 12972 case BPF_JSLE:
a72dafaf
JW
12973 case BPF_JSLT:
12974 {
3f50f132
JF
12975 if (is_jmp32) {
12976 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
12977 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 12978
3f50f132
JF
12979 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12980 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12981 } else {
12982 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
12983 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12984
12985 false_reg->smin_value = max(false_reg->smin_value, false_smin);
12986 true_reg->smax_value = min(true_reg->smax_value, true_smax);
12987 }
b4e432f1 12988 break;
a72dafaf 12989 }
48461135 12990 default:
0fc31b10 12991 return;
48461135
JB
12992 }
12993
3f50f132
JF
12994 if (is_jmp32) {
12995 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12996 tnum_subreg(false_32off));
12997 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12998 tnum_subreg(true_32off));
12999 __reg_combine_32_into_64(false_reg);
13000 __reg_combine_32_into_64(true_reg);
13001 } else {
13002 false_reg->var_off = false_64off;
13003 true_reg->var_off = true_64off;
13004 __reg_combine_64_into_32(false_reg);
13005 __reg_combine_64_into_32(true_reg);
13006 }
48461135
JB
13007}
13008
f1174f77
EC
13009/* Same as above, but for the case that dst_reg holds a constant and src_reg is
13010 * the variable reg.
48461135
JB
13011 */
13012static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
13013 struct bpf_reg_state *false_reg,
13014 u64 val, u32 val32,
092ed096 13015 u8 opcode, bool is_jmp32)
48461135 13016{
6d94e741 13017 opcode = flip_opcode(opcode);
0fc31b10
JH
13018 /* This uses zero as "not present in table"; luckily the zero opcode,
13019 * BPF_JA, can't get here.
b03c9f9f 13020 */
0fc31b10 13021 if (opcode)
3f50f132 13022 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
13023}
13024
13025/* Regs are known to be equal, so intersect their min/max/var_off */
13026static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13027 struct bpf_reg_state *dst_reg)
13028{
b03c9f9f
EC
13029 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13030 dst_reg->umin_value);
13031 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13032 dst_reg->umax_value);
13033 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13034 dst_reg->smin_value);
13035 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13036 dst_reg->smax_value);
f1174f77
EC
13037 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13038 dst_reg->var_off);
3844d153
DB
13039 reg_bounds_sync(src_reg);
13040 reg_bounds_sync(dst_reg);
f1174f77
EC
13041}
13042
13043static void reg_combine_min_max(struct bpf_reg_state *true_src,
13044 struct bpf_reg_state *true_dst,
13045 struct bpf_reg_state *false_src,
13046 struct bpf_reg_state *false_dst,
13047 u8 opcode)
13048{
13049 switch (opcode) {
13050 case BPF_JEQ:
13051 __reg_combine_min_max(true_src, true_dst);
13052 break;
13053 case BPF_JNE:
13054 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 13055 break;
4cabc5b1 13056 }
48461135
JB
13057}
13058
fd978bf7
JS
13059static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13060 struct bpf_reg_state *reg, u32 id,
840b9615 13061 bool is_null)
57a09bf0 13062{
c25b2ae1 13063 if (type_may_be_null(reg->type) && reg->id == id &&
fca1aa75 13064 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
df57f38a
KKD
13065 /* Old offset (both fixed and variable parts) should have been
13066 * known-zero, because we don't allow pointer arithmetic on
13067 * pointers that might be NULL. If we see this happening, don't
13068 * convert the register.
13069 *
13070 * But in some cases, some helpers that return local kptrs
13071 * advance offset for the returned pointer. In those cases, it
13072 * is fine to expect to see reg->off.
13073 */
13074 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13075 return;
6a3cd331
DM
13076 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13077 WARN_ON_ONCE(reg->off))
e60b0d12 13078 return;
6a3cd331 13079
f1174f77
EC
13080 if (is_null) {
13081 reg->type = SCALAR_VALUE;
1b986589
MKL
13082 /* We don't need id and ref_obj_id from this point
13083 * onwards anymore, thus we should better reset it,
13084 * so that state pruning has chances to take effect.
13085 */
13086 reg->id = 0;
13087 reg->ref_obj_id = 0;
4ddb7416
DB
13088
13089 return;
13090 }
13091
13092 mark_ptr_not_null_reg(reg);
13093
13094 if (!reg_may_point_to_spin_lock(reg)) {
1b986589 13095 /* For not-NULL ptr, reg->ref_obj_id will be reset
b239da34 13096 * in release_reference().
1b986589
MKL
13097 *
13098 * reg->id is still used by spin_lock ptr. Other
13099 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
13100 */
13101 reg->id = 0;
56f668df 13102 }
57a09bf0
TG
13103 }
13104}
13105
13106/* The logic is similar to find_good_pkt_pointers(), both could eventually
13107 * be folded together at some point.
13108 */
840b9615
JS
13109static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13110 bool is_null)
57a09bf0 13111{
f4d7e40a 13112 struct bpf_func_state *state = vstate->frame[vstate->curframe];
b239da34 13113 struct bpf_reg_state *regs = state->regs, *reg;
1b986589 13114 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 13115 u32 id = regs[regno].id;
57a09bf0 13116
1b986589
MKL
13117 if (ref_obj_id && ref_obj_id == id && is_null)
13118 /* regs[regno] is in the " == NULL" branch.
13119 * No one could have freed the reference state before
13120 * doing the NULL check.
13121 */
13122 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 13123
b239da34
KKD
13124 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13125 mark_ptr_or_null_reg(state, reg, id, is_null);
13126 }));
57a09bf0
TG
13127}
13128
5beca081
DB
13129static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13130 struct bpf_reg_state *dst_reg,
13131 struct bpf_reg_state *src_reg,
13132 struct bpf_verifier_state *this_branch,
13133 struct bpf_verifier_state *other_branch)
13134{
13135 if (BPF_SRC(insn->code) != BPF_X)
13136 return false;
13137
092ed096
JW
13138 /* Pointers are always 64-bit. */
13139 if (BPF_CLASS(insn->code) == BPF_JMP32)
13140 return false;
13141
5beca081
DB
13142 switch (BPF_OP(insn->code)) {
13143 case BPF_JGT:
13144 if ((dst_reg->type == PTR_TO_PACKET &&
13145 src_reg->type == PTR_TO_PACKET_END) ||
13146 (dst_reg->type == PTR_TO_PACKET_META &&
13147 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13148 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13149 find_good_pkt_pointers(this_branch, dst_reg,
13150 dst_reg->type, false);
6d94e741 13151 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
13152 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13153 src_reg->type == PTR_TO_PACKET) ||
13154 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13155 src_reg->type == PTR_TO_PACKET_META)) {
13156 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13157 find_good_pkt_pointers(other_branch, src_reg,
13158 src_reg->type, true);
6d94e741 13159 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
13160 } else {
13161 return false;
13162 }
13163 break;
13164 case BPF_JLT:
13165 if ((dst_reg->type == PTR_TO_PACKET &&
13166 src_reg->type == PTR_TO_PACKET_END) ||
13167 (dst_reg->type == PTR_TO_PACKET_META &&
13168 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13169 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13170 find_good_pkt_pointers(other_branch, dst_reg,
13171 dst_reg->type, true);
6d94e741 13172 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
13173 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13174 src_reg->type == PTR_TO_PACKET) ||
13175 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13176 src_reg->type == PTR_TO_PACKET_META)) {
13177 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13178 find_good_pkt_pointers(this_branch, src_reg,
13179 src_reg->type, false);
6d94e741 13180 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
13181 } else {
13182 return false;
13183 }
13184 break;
13185 case BPF_JGE:
13186 if ((dst_reg->type == PTR_TO_PACKET &&
13187 src_reg->type == PTR_TO_PACKET_END) ||
13188 (dst_reg->type == PTR_TO_PACKET_META &&
13189 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13190 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13191 find_good_pkt_pointers(this_branch, dst_reg,
13192 dst_reg->type, true);
6d94e741 13193 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
13194 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13195 src_reg->type == PTR_TO_PACKET) ||
13196 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13197 src_reg->type == PTR_TO_PACKET_META)) {
13198 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13199 find_good_pkt_pointers(other_branch, src_reg,
13200 src_reg->type, false);
6d94e741 13201 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
13202 } else {
13203 return false;
13204 }
13205 break;
13206 case BPF_JLE:
13207 if ((dst_reg->type == PTR_TO_PACKET &&
13208 src_reg->type == PTR_TO_PACKET_END) ||
13209 (dst_reg->type == PTR_TO_PACKET_META &&
13210 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13211 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13212 find_good_pkt_pointers(other_branch, dst_reg,
13213 dst_reg->type, false);
6d94e741 13214 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
13215 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13216 src_reg->type == PTR_TO_PACKET) ||
13217 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13218 src_reg->type == PTR_TO_PACKET_META)) {
13219 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13220 find_good_pkt_pointers(this_branch, src_reg,
13221 src_reg->type, true);
6d94e741 13222 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
13223 } else {
13224 return false;
13225 }
13226 break;
13227 default:
13228 return false;
13229 }
13230
13231 return true;
13232}
13233
75748837
AS
13234static void find_equal_scalars(struct bpf_verifier_state *vstate,
13235 struct bpf_reg_state *known_reg)
13236{
13237 struct bpf_func_state *state;
13238 struct bpf_reg_state *reg;
75748837 13239
b239da34
KKD
13240 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13241 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
71f656a5 13242 copy_register_state(reg, known_reg);
b239da34 13243 }));
75748837
AS
13244}
13245
58e2af8b 13246static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
13247 struct bpf_insn *insn, int *insn_idx)
13248{
f4d7e40a
AS
13249 struct bpf_verifier_state *this_branch = env->cur_state;
13250 struct bpf_verifier_state *other_branch;
13251 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 13252 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
befae758 13253 struct bpf_reg_state *eq_branch_regs;
17a52670 13254 u8 opcode = BPF_OP(insn->code);
092ed096 13255 bool is_jmp32;
fb8d251e 13256 int pred = -1;
17a52670
AS
13257 int err;
13258
092ed096
JW
13259 /* Only conditional jumps are expected to reach here. */
13260 if (opcode == BPF_JA || opcode > BPF_JSLE) {
13261 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
13262 return -EINVAL;
13263 }
13264
13265 if (BPF_SRC(insn->code) == BPF_X) {
13266 if (insn->imm != 0) {
092ed096 13267 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
13268 return -EINVAL;
13269 }
13270
13271 /* check src1 operand */
dc503a8a 13272 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13273 if (err)
13274 return err;
1be7f75d
AS
13275
13276 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 13277 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
13278 insn->src_reg);
13279 return -EACCES;
13280 }
fb8d251e 13281 src_reg = &regs[insn->src_reg];
17a52670
AS
13282 } else {
13283 if (insn->src_reg != BPF_REG_0) {
092ed096 13284 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
13285 return -EINVAL;
13286 }
13287 }
13288
13289 /* check src2 operand */
dc503a8a 13290 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13291 if (err)
13292 return err;
13293
1a0dc1ac 13294 dst_reg = &regs[insn->dst_reg];
092ed096 13295 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 13296
3f50f132
JF
13297 if (BPF_SRC(insn->code) == BPF_K) {
13298 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13299 } else if (src_reg->type == SCALAR_VALUE &&
13300 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13301 pred = is_branch_taken(dst_reg,
13302 tnum_subreg(src_reg->var_off).value,
13303 opcode,
13304 is_jmp32);
13305 } else if (src_reg->type == SCALAR_VALUE &&
13306 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13307 pred = is_branch_taken(dst_reg,
13308 src_reg->var_off.value,
13309 opcode,
13310 is_jmp32);
6d94e741
AS
13311 } else if (reg_is_pkt_pointer_any(dst_reg) &&
13312 reg_is_pkt_pointer_any(src_reg) &&
13313 !is_jmp32) {
13314 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
13315 }
13316
b5dc0163 13317 if (pred >= 0) {
cac616db
JF
13318 /* If we get here with a dst_reg pointer type it is because
13319 * above is_branch_taken() special cased the 0 comparison.
13320 */
13321 if (!__is_pointer_value(false, dst_reg))
13322 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
13323 if (BPF_SRC(insn->code) == BPF_X && !err &&
13324 !__is_pointer_value(false, src_reg))
b5dc0163
AS
13325 err = mark_chain_precision(env, insn->src_reg);
13326 if (err)
13327 return err;
13328 }
9183671a 13329
fb8d251e 13330 if (pred == 1) {
9183671a
DB
13331 /* Only follow the goto, ignore fall-through. If needed, push
13332 * the fall-through branch for simulation under speculative
13333 * execution.
13334 */
13335 if (!env->bypass_spec_v1 &&
13336 !sanitize_speculative_path(env, insn, *insn_idx + 1,
13337 *insn_idx))
13338 return -EFAULT;
fb8d251e
AS
13339 *insn_idx += insn->off;
13340 return 0;
13341 } else if (pred == 0) {
9183671a
DB
13342 /* Only follow the fall-through branch, since that's where the
13343 * program will go. If needed, push the goto branch for
13344 * simulation under speculative execution.
fb8d251e 13345 */
9183671a
DB
13346 if (!env->bypass_spec_v1 &&
13347 !sanitize_speculative_path(env, insn,
13348 *insn_idx + insn->off + 1,
13349 *insn_idx))
13350 return -EFAULT;
fb8d251e 13351 return 0;
17a52670
AS
13352 }
13353
979d63d5
DB
13354 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13355 false);
17a52670
AS
13356 if (!other_branch)
13357 return -EFAULT;
f4d7e40a 13358 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 13359
48461135
JB
13360 /* detect if we are comparing against a constant value so we can adjust
13361 * our min/max values for our dst register.
f1174f77 13362 * this is only legit if both are scalars (or pointers to the same
befae758
EZ
13363 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13364 * because otherwise the different base pointers mean the offsets aren't
f1174f77 13365 * comparable.
48461135
JB
13366 */
13367 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 13368 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 13369
f1174f77 13370 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
13371 src_reg->type == SCALAR_VALUE) {
13372 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
13373 (is_jmp32 &&
13374 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 13375 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 13376 dst_reg,
3f50f132
JF
13377 src_reg->var_off.value,
13378 tnum_subreg(src_reg->var_off).value,
092ed096
JW
13379 opcode, is_jmp32);
13380 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
13381 (is_jmp32 &&
13382 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 13383 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 13384 src_reg,
3f50f132
JF
13385 dst_reg->var_off.value,
13386 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
13387 opcode, is_jmp32);
13388 else if (!is_jmp32 &&
13389 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 13390 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
13391 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13392 &other_branch_regs[insn->dst_reg],
092ed096 13393 src_reg, dst_reg, opcode);
e688c3db
AS
13394 if (src_reg->id &&
13395 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
13396 find_equal_scalars(this_branch, src_reg);
13397 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13398 }
13399
f1174f77
EC
13400 }
13401 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 13402 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
13403 dst_reg, insn->imm, (u32)insn->imm,
13404 opcode, is_jmp32);
48461135
JB
13405 }
13406
e688c3db
AS
13407 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13408 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
13409 find_equal_scalars(this_branch, dst_reg);
13410 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13411 }
13412
befae758
EZ
13413 /* if one pointer register is compared to another pointer
13414 * register check if PTR_MAYBE_NULL could be lifted.
13415 * E.g. register A - maybe null
13416 * register B - not null
13417 * for JNE A, B, ... - A is not null in the false branch;
13418 * for JEQ A, B, ... - A is not null in the true branch.
8374bfd5
HS
13419 *
13420 * Since PTR_TO_BTF_ID points to a kernel struct that does
13421 * not need to be null checked by the BPF program, i.e.,
13422 * could be null even without PTR_MAYBE_NULL marking, so
13423 * only propagate nullness when neither reg is that type.
befae758
EZ
13424 */
13425 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13426 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
8374bfd5
HS
13427 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13428 base_type(src_reg->type) != PTR_TO_BTF_ID &&
13429 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
befae758
EZ
13430 eq_branch_regs = NULL;
13431 switch (opcode) {
13432 case BPF_JEQ:
13433 eq_branch_regs = other_branch_regs;
13434 break;
13435 case BPF_JNE:
13436 eq_branch_regs = regs;
13437 break;
13438 default:
13439 /* do nothing */
13440 break;
13441 }
13442 if (eq_branch_regs) {
13443 if (type_may_be_null(src_reg->type))
13444 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13445 else
13446 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13447 }
13448 }
13449
092ed096
JW
13450 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13451 * NOTE: these optimizations below are related with pointer comparison
13452 * which will never be JMP32.
13453 */
13454 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 13455 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
c25b2ae1 13456 type_may_be_null(dst_reg->type)) {
840b9615 13457 /* Mark all identical registers in each branch as either
57a09bf0
TG
13458 * safe or unknown depending R == 0 or R != 0 conditional.
13459 */
840b9615
JS
13460 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13461 opcode == BPF_JNE);
13462 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13463 opcode == BPF_JEQ);
5beca081
DB
13464 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
13465 this_branch, other_branch) &&
13466 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
13467 verbose(env, "R%d pointer comparison prohibited\n",
13468 insn->dst_reg);
1be7f75d 13469 return -EACCES;
17a52670 13470 }
06ee7115 13471 if (env->log.level & BPF_LOG_LEVEL)
2e576648 13472 print_insn_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
13473 return 0;
13474}
13475
17a52670 13476/* verify BPF_LD_IMM64 instruction */
58e2af8b 13477static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 13478{
d8eca5bb 13479 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 13480 struct bpf_reg_state *regs = cur_regs(env);
4976b718 13481 struct bpf_reg_state *dst_reg;
d8eca5bb 13482 struct bpf_map *map;
17a52670
AS
13483 int err;
13484
13485 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 13486 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
13487 return -EINVAL;
13488 }
13489 if (insn->off != 0) {
61bd5218 13490 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
13491 return -EINVAL;
13492 }
13493
dc503a8a 13494 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
13495 if (err)
13496 return err;
13497
4976b718 13498 dst_reg = &regs[insn->dst_reg];
6b173873 13499 if (insn->src_reg == 0) {
6b173873
JK
13500 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13501
4976b718 13502 dst_reg->type = SCALAR_VALUE;
b03c9f9f 13503 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 13504 return 0;
6b173873 13505 }
17a52670 13506
d400a6cf
DB
13507 /* All special src_reg cases are listed below. From this point onwards
13508 * we either succeed and assign a corresponding dst_reg->type after
13509 * zeroing the offset, or fail and reject the program.
13510 */
13511 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 13512
d400a6cf 13513 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
4976b718 13514 dst_reg->type = aux->btf_var.reg_type;
34d3a78c 13515 switch (base_type(dst_reg->type)) {
4976b718
HL
13516 case PTR_TO_MEM:
13517 dst_reg->mem_size = aux->btf_var.mem_size;
13518 break;
13519 case PTR_TO_BTF_ID:
22dc4a0f 13520 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
13521 dst_reg->btf_id = aux->btf_var.btf_id;
13522 break;
13523 default:
13524 verbose(env, "bpf verifier is misconfigured\n");
13525 return -EFAULT;
13526 }
13527 return 0;
13528 }
13529
69c087ba
YS
13530 if (insn->src_reg == BPF_PSEUDO_FUNC) {
13531 struct bpf_prog_aux *aux = env->prog->aux;
3990ed4c
MKL
13532 u32 subprogno = find_subprog(env,
13533 env->insn_idx + insn->imm + 1);
69c087ba
YS
13534
13535 if (!aux->func_info) {
13536 verbose(env, "missing btf func_info\n");
13537 return -EINVAL;
13538 }
13539 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13540 verbose(env, "callback function not static\n");
13541 return -EINVAL;
13542 }
13543
13544 dst_reg->type = PTR_TO_FUNC;
13545 dst_reg->subprogno = subprogno;
13546 return 0;
13547 }
13548
d8eca5bb 13549 map = env->used_maps[aux->map_index];
4976b718 13550 dst_reg->map_ptr = map;
d8eca5bb 13551
387544bf
AS
13552 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13553 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
4976b718
HL
13554 dst_reg->type = PTR_TO_MAP_VALUE;
13555 dst_reg->off = aux->map_off;
d0d78c1d
KKD
13556 WARN_ON_ONCE(map->max_entries != 1);
13557 /* We want reg->id to be same (0) as map_value is not distinct */
387544bf
AS
13558 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13559 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
4976b718 13560 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
13561 } else {
13562 verbose(env, "bpf verifier is misconfigured\n");
13563 return -EINVAL;
13564 }
17a52670 13565
17a52670
AS
13566 return 0;
13567}
13568
96be4325
DB
13569static bool may_access_skb(enum bpf_prog_type type)
13570{
13571 switch (type) {
13572 case BPF_PROG_TYPE_SOCKET_FILTER:
13573 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 13574 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
13575 return true;
13576 default:
13577 return false;
13578 }
13579}
13580
ddd872bc
AS
13581/* verify safety of LD_ABS|LD_IND instructions:
13582 * - they can only appear in the programs where ctx == skb
13583 * - since they are wrappers of function calls, they scratch R1-R5 registers,
13584 * preserve R6-R9, and store return value into R0
13585 *
13586 * Implicit input:
13587 * ctx == skb == R6 == CTX
13588 *
13589 * Explicit input:
13590 * SRC == any register
13591 * IMM == 32-bit immediate
13592 *
13593 * Output:
13594 * R0 - 8/16/32-bit skb data converted to cpu endianness
13595 */
58e2af8b 13596static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 13597{
638f5b90 13598 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 13599 static const int ctx_reg = BPF_REG_6;
ddd872bc 13600 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
13601 int i, err;
13602
7e40781c 13603 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 13604 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
13605 return -EINVAL;
13606 }
13607
e0cea7ce
DB
13608 if (!env->ops->gen_ld_abs) {
13609 verbose(env, "bpf verifier is misconfigured\n");
13610 return -EINVAL;
13611 }
13612
ddd872bc 13613 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 13614 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 13615 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 13616 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
13617 return -EINVAL;
13618 }
13619
13620 /* check whether implicit source operand (register R6) is readable */
6d4f151a 13621 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
13622 if (err)
13623 return err;
13624
fd978bf7
JS
13625 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13626 * gen_ld_abs() may terminate the program at runtime, leading to
13627 * reference leak.
13628 */
13629 err = check_reference_leak(env);
13630 if (err) {
13631 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13632 return err;
13633 }
13634
d0d78c1d 13635 if (env->cur_state->active_lock.ptr) {
d83525ca
AS
13636 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13637 return -EINVAL;
13638 }
13639
9bb00b28
YS
13640 if (env->cur_state->active_rcu_lock) {
13641 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13642 return -EINVAL;
13643 }
13644
6d4f151a 13645 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
13646 verbose(env,
13647 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
13648 return -EINVAL;
13649 }
13650
13651 if (mode == BPF_IND) {
13652 /* check explicit source operand */
dc503a8a 13653 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
13654 if (err)
13655 return err;
13656 }
13657
be80a1d3 13658 err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
6d4f151a
DB
13659 if (err < 0)
13660 return err;
13661
ddd872bc 13662 /* reset caller saved regs to unreadable */
dc503a8a 13663 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 13664 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
13665 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13666 }
ddd872bc
AS
13667
13668 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
13669 * the value fetched from the packet.
13670 * Already marked as written above.
ddd872bc 13671 */
61bd5218 13672 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
13673 /* ld_abs load up to 32-bit skb data. */
13674 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
13675 return 0;
13676}
13677
390ee7e2
AS
13678static int check_return_code(struct bpf_verifier_env *env)
13679{
5cf1e914 13680 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 13681 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
13682 struct bpf_reg_state *reg;
13683 struct tnum range = tnum_range(0, 1);
7e40781c 13684 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 13685 int err;
bfc6bb74
AS
13686 struct bpf_func_state *frame = env->cur_state->frame[0];
13687 const bool is_subprog = frame->subprogno;
27ae7997 13688
9e4e01df 13689 /* LSM and struct_ops func-ptr's return type could be "void" */
d1a6edec
SF
13690 if (!is_subprog) {
13691 switch (prog_type) {
13692 case BPF_PROG_TYPE_LSM:
13693 if (prog->expected_attach_type == BPF_LSM_CGROUP)
13694 /* See below, can be 0 or 0-1 depending on hook. */
13695 break;
13696 fallthrough;
13697 case BPF_PROG_TYPE_STRUCT_OPS:
13698 if (!prog->aux->attach_func_proto->type)
13699 return 0;
13700 break;
13701 default:
13702 break;
13703 }
13704 }
27ae7997 13705
8fb33b60 13706 /* eBPF calling convention is such that R0 is used
27ae7997
MKL
13707 * to return the value from eBPF program.
13708 * Make sure that it's readable at this time
13709 * of bpf_exit, which means that program wrote
13710 * something into it earlier
13711 */
13712 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13713 if (err)
13714 return err;
13715
13716 if (is_pointer_value(env, BPF_REG_0)) {
13717 verbose(env, "R0 leaks addr as return value\n");
13718 return -EACCES;
13719 }
390ee7e2 13720
f782e2c3 13721 reg = cur_regs(env) + BPF_REG_0;
bfc6bb74
AS
13722
13723 if (frame->in_async_callback_fn) {
13724 /* enforce return zero from async callbacks like timer */
13725 if (reg->type != SCALAR_VALUE) {
13726 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
c25b2ae1 13727 reg_type_str(env, reg->type));
bfc6bb74
AS
13728 return -EINVAL;
13729 }
13730
13731 if (!tnum_in(tnum_const(0), reg->var_off)) {
13732 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13733 return -EINVAL;
13734 }
13735 return 0;
13736 }
13737
f782e2c3
DB
13738 if (is_subprog) {
13739 if (reg->type != SCALAR_VALUE) {
13740 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
c25b2ae1 13741 reg_type_str(env, reg->type));
f782e2c3
DB
13742 return -EINVAL;
13743 }
13744 return 0;
13745 }
13746
7e40781c 13747 switch (prog_type) {
983695fa
DB
13748 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13749 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
13750 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13751 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13752 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13753 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13754 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 13755 range = tnum_range(1, 1);
77241217
SF
13756 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13757 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13758 range = tnum_range(0, 3);
ed4ed404 13759 break;
390ee7e2 13760 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 13761 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13762 range = tnum_range(0, 3);
13763 enforce_attach_type_range = tnum_range(2, 3);
13764 }
ed4ed404 13765 break;
390ee7e2
AS
13766 case BPF_PROG_TYPE_CGROUP_SOCK:
13767 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 13768 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 13769 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 13770 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 13771 break;
15ab09bd
AS
13772 case BPF_PROG_TYPE_RAW_TRACEPOINT:
13773 if (!env->prog->aux->attach_btf_id)
13774 return 0;
13775 range = tnum_const(0);
13776 break;
15d83c4d 13777 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
13778 switch (env->prog->expected_attach_type) {
13779 case BPF_TRACE_FENTRY:
13780 case BPF_TRACE_FEXIT:
13781 range = tnum_const(0);
13782 break;
13783 case BPF_TRACE_RAW_TP:
13784 case BPF_MODIFY_RETURN:
15d83c4d 13785 return 0;
2ec0616e
DB
13786 case BPF_TRACE_ITER:
13787 break;
e92888c7
YS
13788 default:
13789 return -ENOTSUPP;
13790 }
15d83c4d 13791 break;
e9ddbb77
JS
13792 case BPF_PROG_TYPE_SK_LOOKUP:
13793 range = tnum_range(SK_DROP, SK_PASS);
13794 break;
69fd337a
SF
13795
13796 case BPF_PROG_TYPE_LSM:
13797 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13798 /* Regular BPF_PROG_TYPE_LSM programs can return
13799 * any value.
13800 */
13801 return 0;
13802 }
13803 if (!env->prog->aux->attach_func_proto->type) {
13804 /* Make sure programs that attach to void
13805 * hooks don't try to modify return value.
13806 */
13807 range = tnum_range(1, 1);
13808 }
13809 break;
13810
e92888c7
YS
13811 case BPF_PROG_TYPE_EXT:
13812 /* freplace program can return anything as its return value
13813 * depends on the to-be-replaced kernel func or bpf program.
13814 */
390ee7e2
AS
13815 default:
13816 return 0;
13817 }
13818
390ee7e2 13819 if (reg->type != SCALAR_VALUE) {
61bd5218 13820 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
c25b2ae1 13821 reg_type_str(env, reg->type));
390ee7e2
AS
13822 return -EINVAL;
13823 }
13824
13825 if (!tnum_in(range, reg->var_off)) {
bc2591d6 13826 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
69fd337a 13827 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
d1a6edec 13828 prog_type == BPF_PROG_TYPE_LSM &&
69fd337a
SF
13829 !prog->aux->attach_func_proto->type)
13830 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
390ee7e2
AS
13831 return -EINVAL;
13832 }
5cf1e914 13833
13834 if (!tnum_is_unknown(enforce_attach_type_range) &&
13835 tnum_in(enforce_attach_type_range, reg->var_off))
13836 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
13837 return 0;
13838}
13839
475fb78f
AS
13840/* non-recursive DFS pseudo code
13841 * 1 procedure DFS-iterative(G,v):
13842 * 2 label v as discovered
13843 * 3 let S be a stack
13844 * 4 S.push(v)
13845 * 5 while S is not empty
b6d20799 13846 * 6 t <- S.peek()
475fb78f
AS
13847 * 7 if t is what we're looking for:
13848 * 8 return t
13849 * 9 for all edges e in G.adjacentEdges(t) do
13850 * 10 if edge e is already labelled
13851 * 11 continue with the next edge
13852 * 12 w <- G.adjacentVertex(t,e)
13853 * 13 if vertex w is not discovered and not explored
13854 * 14 label e as tree-edge
13855 * 15 label w as discovered
13856 * 16 S.push(w)
13857 * 17 continue at 5
13858 * 18 else if vertex w is discovered
13859 * 19 label e as back-edge
13860 * 20 else
13861 * 21 // vertex w is explored
13862 * 22 label e as forward- or cross-edge
13863 * 23 label t as explored
13864 * 24 S.pop()
13865 *
13866 * convention:
13867 * 0x10 - discovered
13868 * 0x11 - discovered and fall-through edge labelled
13869 * 0x12 - discovered and fall-through and branch edges labelled
13870 * 0x20 - explored
13871 */
13872
13873enum {
13874 DISCOVERED = 0x10,
13875 EXPLORED = 0x20,
13876 FALLTHROUGH = 1,
13877 BRANCH = 2,
13878};
13879
dc2a4ebc
AS
13880static u32 state_htab_size(struct bpf_verifier_env *env)
13881{
13882 return env->prog->len;
13883}
13884
5d839021
AS
13885static struct bpf_verifier_state_list **explored_state(
13886 struct bpf_verifier_env *env,
13887 int idx)
13888{
dc2a4ebc
AS
13889 struct bpf_verifier_state *cur = env->cur_state;
13890 struct bpf_func_state *state = cur->frame[cur->curframe];
13891
13892 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
13893}
13894
bffdeaa8 13895static void mark_prune_point(struct bpf_verifier_env *env, int idx)
5d839021 13896{
a8f500af 13897 env->insn_aux_data[idx].prune_point = true;
5d839021 13898}
f1bca824 13899
bffdeaa8
AN
13900static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13901{
13902 return env->insn_aux_data[insn_idx].prune_point;
13903}
13904
4b5ce570
AN
13905static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
13906{
13907 env->insn_aux_data[idx].force_checkpoint = true;
13908}
13909
13910static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
13911{
13912 return env->insn_aux_data[insn_idx].force_checkpoint;
13913}
13914
13915
59e2e27d
WAF
13916enum {
13917 DONE_EXPLORING = 0,
13918 KEEP_EXPLORING = 1,
13919};
13920
475fb78f
AS
13921/* t, w, e - match pseudo-code above:
13922 * t - index of current instruction
13923 * w - next instruction
13924 * e - edge
13925 */
2589726d
AS
13926static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13927 bool loop_ok)
475fb78f 13928{
7df737e9
AS
13929 int *insn_stack = env->cfg.insn_stack;
13930 int *insn_state = env->cfg.insn_state;
13931
475fb78f 13932 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 13933 return DONE_EXPLORING;
475fb78f
AS
13934
13935 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 13936 return DONE_EXPLORING;
475fb78f
AS
13937
13938 if (w < 0 || w >= env->prog->len) {
d9762e84 13939 verbose_linfo(env, t, "%d: ", t);
61bd5218 13940 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
13941 return -EINVAL;
13942 }
13943
bffdeaa8 13944 if (e == BRANCH) {
f1bca824 13945 /* mark branch target for state pruning */
bffdeaa8
AN
13946 mark_prune_point(env, w);
13947 mark_jmp_point(env, w);
13948 }
f1bca824 13949
475fb78f
AS
13950 if (insn_state[w] == 0) {
13951 /* tree-edge */
13952 insn_state[t] = DISCOVERED | e;
13953 insn_state[w] = DISCOVERED;
7df737e9 13954 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 13955 return -E2BIG;
7df737e9 13956 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 13957 return KEEP_EXPLORING;
475fb78f 13958 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 13959 if (loop_ok && env->bpf_capable)
59e2e27d 13960 return DONE_EXPLORING;
d9762e84
MKL
13961 verbose_linfo(env, t, "%d: ", t);
13962 verbose_linfo(env, w, "%d: ", w);
61bd5218 13963 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
13964 return -EINVAL;
13965 } else if (insn_state[w] == EXPLORED) {
13966 /* forward- or cross-edge */
13967 insn_state[t] = DISCOVERED | e;
13968 } else {
61bd5218 13969 verbose(env, "insn state internal bug\n");
475fb78f
AS
13970 return -EFAULT;
13971 }
59e2e27d
WAF
13972 return DONE_EXPLORING;
13973}
13974
dcb2288b 13975static int visit_func_call_insn(int t, struct bpf_insn *insns,
efdb22de
YS
13976 struct bpf_verifier_env *env,
13977 bool visit_callee)
13978{
13979 int ret;
13980
13981 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13982 if (ret)
13983 return ret;
13984
618945fb
AN
13985 mark_prune_point(env, t + 1);
13986 /* when we exit from subprog, we need to record non-linear history */
13987 mark_jmp_point(env, t + 1);
13988
efdb22de 13989 if (visit_callee) {
bffdeaa8 13990 mark_prune_point(env, t);
86fc6ee6
AS
13991 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13992 /* It's ok to allow recursion from CFG point of
13993 * view. __check_func_call() will do the actual
13994 * check.
13995 */
13996 bpf_pseudo_func(insns + t));
efdb22de
YS
13997 }
13998 return ret;
13999}
14000
59e2e27d
WAF
14001/* Visits the instruction at index t and returns one of the following:
14002 * < 0 - an error occurred
14003 * DONE_EXPLORING - the instruction was fully explored
14004 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14005 */
dcb2288b 14006static int visit_insn(int t, struct bpf_verifier_env *env)
59e2e27d 14007{
653ae3a8 14008 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
59e2e27d
WAF
14009 int ret;
14010
653ae3a8 14011 if (bpf_pseudo_func(insn))
dcb2288b 14012 return visit_func_call_insn(t, insns, env, true);
69c087ba 14013
59e2e27d 14014 /* All non-branch instructions have a single fall-through edge. */
653ae3a8
AN
14015 if (BPF_CLASS(insn->code) != BPF_JMP &&
14016 BPF_CLASS(insn->code) != BPF_JMP32)
59e2e27d
WAF
14017 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14018
653ae3a8 14019 switch (BPF_OP(insn->code)) {
59e2e27d
WAF
14020 case BPF_EXIT:
14021 return DONE_EXPLORING;
14022
14023 case BPF_CALL:
c1ee85a9 14024 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
618945fb
AN
14025 /* Mark this call insn as a prune point to trigger
14026 * is_state_visited() check before call itself is
14027 * processed by __check_func_call(). Otherwise new
14028 * async state will be pushed for further exploration.
bfc6bb74 14029 */
bffdeaa8 14030 mark_prune_point(env, t);
06accc87
AN
14031 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14032 struct bpf_kfunc_call_arg_meta meta;
14033
14034 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
4b5ce570 14035 if (ret == 0 && is_iter_next_kfunc(&meta)) {
06accc87 14036 mark_prune_point(env, t);
4b5ce570
AN
14037 /* Checking and saving state checkpoints at iter_next() call
14038 * is crucial for fast convergence of open-coded iterator loop
14039 * logic, so we need to force it. If we don't do that,
14040 * is_state_visited() might skip saving a checkpoint, causing
14041 * unnecessarily long sequence of not checkpointed
14042 * instructions and jumps, leading to exhaustion of jump
14043 * history buffer, and potentially other undesired outcomes.
14044 * It is expected that with correct open-coded iterators
14045 * convergence will happen quickly, so we don't run a risk of
14046 * exhausting memory.
14047 */
14048 mark_force_checkpoint(env, t);
14049 }
06accc87 14050 }
653ae3a8 14051 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
14052
14053 case BPF_JA:
653ae3a8 14054 if (BPF_SRC(insn->code) != BPF_K)
59e2e27d
WAF
14055 return -EINVAL;
14056
14057 /* unconditional jump with single edge */
653ae3a8 14058 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
59e2e27d
WAF
14059 true);
14060 if (ret)
14061 return ret;
14062
653ae3a8
AN
14063 mark_prune_point(env, t + insn->off + 1);
14064 mark_jmp_point(env, t + insn->off + 1);
59e2e27d
WAF
14065
14066 return ret;
14067
14068 default:
14069 /* conditional jump with two edges */
bffdeaa8 14070 mark_prune_point(env, t);
618945fb 14071
59e2e27d
WAF
14072 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14073 if (ret)
14074 return ret;
14075
653ae3a8 14076 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
59e2e27d 14077 }
475fb78f
AS
14078}
14079
14080/* non-recursive depth-first-search to detect loops in BPF program
14081 * loop == back-edge in directed graph
14082 */
58e2af8b 14083static int check_cfg(struct bpf_verifier_env *env)
475fb78f 14084{
475fb78f 14085 int insn_cnt = env->prog->len;
7df737e9 14086 int *insn_stack, *insn_state;
475fb78f 14087 int ret = 0;
59e2e27d 14088 int i;
475fb78f 14089
7df737e9 14090 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
14091 if (!insn_state)
14092 return -ENOMEM;
14093
7df737e9 14094 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 14095 if (!insn_stack) {
71dde681 14096 kvfree(insn_state);
475fb78f
AS
14097 return -ENOMEM;
14098 }
14099
14100 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14101 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 14102 env->cfg.cur_stack = 1;
475fb78f 14103
59e2e27d
WAF
14104 while (env->cfg.cur_stack > 0) {
14105 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 14106
dcb2288b 14107 ret = visit_insn(t, env);
59e2e27d
WAF
14108 switch (ret) {
14109 case DONE_EXPLORING:
14110 insn_state[t] = EXPLORED;
14111 env->cfg.cur_stack--;
14112 break;
14113 case KEEP_EXPLORING:
14114 break;
14115 default:
14116 if (ret > 0) {
14117 verbose(env, "visit_insn internal bug\n");
14118 ret = -EFAULT;
475fb78f 14119 }
475fb78f 14120 goto err_free;
59e2e27d 14121 }
475fb78f
AS
14122 }
14123
59e2e27d 14124 if (env->cfg.cur_stack < 0) {
61bd5218 14125 verbose(env, "pop stack internal bug\n");
475fb78f
AS
14126 ret = -EFAULT;
14127 goto err_free;
14128 }
475fb78f 14129
475fb78f
AS
14130 for (i = 0; i < insn_cnt; i++) {
14131 if (insn_state[i] != EXPLORED) {
61bd5218 14132 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
14133 ret = -EINVAL;
14134 goto err_free;
14135 }
14136 }
14137 ret = 0; /* cfg looks good */
14138
14139err_free:
71dde681
AS
14140 kvfree(insn_state);
14141 kvfree(insn_stack);
7df737e9 14142 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
14143 return ret;
14144}
14145
09b28d76
AS
14146static int check_abnormal_return(struct bpf_verifier_env *env)
14147{
14148 int i;
14149
14150 for (i = 1; i < env->subprog_cnt; i++) {
14151 if (env->subprog_info[i].has_ld_abs) {
14152 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14153 return -EINVAL;
14154 }
14155 if (env->subprog_info[i].has_tail_call) {
14156 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14157 return -EINVAL;
14158 }
14159 }
14160 return 0;
14161}
14162
838e9690
YS
14163/* The minimum supported BTF func info size */
14164#define MIN_BPF_FUNCINFO_SIZE 8
14165#define MAX_FUNCINFO_REC_SIZE 252
14166
c454a46b
MKL
14167static int check_btf_func(struct bpf_verifier_env *env,
14168 const union bpf_attr *attr,
af2ac3e1 14169 bpfptr_t uattr)
838e9690 14170{
09b28d76 14171 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 14172 u32 i, nfuncs, urec_size, min_size;
838e9690 14173 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 14174 struct bpf_func_info *krecord;
8c1b6e69 14175 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
14176 struct bpf_prog *prog;
14177 const struct btf *btf;
af2ac3e1 14178 bpfptr_t urecord;
d0b2818e 14179 u32 prev_offset = 0;
09b28d76 14180 bool scalar_return;
e7ed83d6 14181 int ret = -ENOMEM;
838e9690
YS
14182
14183 nfuncs = attr->func_info_cnt;
09b28d76
AS
14184 if (!nfuncs) {
14185 if (check_abnormal_return(env))
14186 return -EINVAL;
838e9690 14187 return 0;
09b28d76 14188 }
838e9690
YS
14189
14190 if (nfuncs != env->subprog_cnt) {
14191 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14192 return -EINVAL;
14193 }
14194
14195 urec_size = attr->func_info_rec_size;
14196 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14197 urec_size > MAX_FUNCINFO_REC_SIZE ||
14198 urec_size % sizeof(u32)) {
14199 verbose(env, "invalid func info rec size %u\n", urec_size);
14200 return -EINVAL;
14201 }
14202
c454a46b
MKL
14203 prog = env->prog;
14204 btf = prog->aux->btf;
838e9690 14205
af2ac3e1 14206 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
838e9690
YS
14207 min_size = min_t(u32, krec_size, urec_size);
14208
ba64e7d8 14209 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
14210 if (!krecord)
14211 return -ENOMEM;
8c1b6e69
AS
14212 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14213 if (!info_aux)
14214 goto err_free;
ba64e7d8 14215
838e9690
YS
14216 for (i = 0; i < nfuncs; i++) {
14217 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14218 if (ret) {
14219 if (ret == -E2BIG) {
14220 verbose(env, "nonzero tailing record in func info");
14221 /* set the size kernel expects so loader can zero
14222 * out the rest of the record.
14223 */
af2ac3e1
AS
14224 if (copy_to_bpfptr_offset(uattr,
14225 offsetof(union bpf_attr, func_info_rec_size),
14226 &min_size, sizeof(min_size)))
838e9690
YS
14227 ret = -EFAULT;
14228 }
c454a46b 14229 goto err_free;
838e9690
YS
14230 }
14231
af2ac3e1 14232 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
838e9690 14233 ret = -EFAULT;
c454a46b 14234 goto err_free;
838e9690
YS
14235 }
14236
d30d42e0 14237 /* check insn_off */
09b28d76 14238 ret = -EINVAL;
838e9690 14239 if (i == 0) {
d30d42e0 14240 if (krecord[i].insn_off) {
838e9690 14241 verbose(env,
d30d42e0
MKL
14242 "nonzero insn_off %u for the first func info record",
14243 krecord[i].insn_off);
c454a46b 14244 goto err_free;
838e9690 14245 }
d30d42e0 14246 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
14247 verbose(env,
14248 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 14249 krecord[i].insn_off, prev_offset);
c454a46b 14250 goto err_free;
838e9690
YS
14251 }
14252
d30d42e0 14253 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 14254 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 14255 goto err_free;
838e9690
YS
14256 }
14257
14258 /* check type_id */
ba64e7d8 14259 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 14260 if (!type || !btf_type_is_func(type)) {
838e9690 14261 verbose(env, "invalid type id %d in func info",
ba64e7d8 14262 krecord[i].type_id);
c454a46b 14263 goto err_free;
838e9690 14264 }
51c39bb1 14265 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
14266
14267 func_proto = btf_type_by_id(btf, type->type);
14268 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14269 /* btf_func_check() already verified it during BTF load */
14270 goto err_free;
14271 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14272 scalar_return =
6089fb32 14273 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
09b28d76
AS
14274 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14275 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14276 goto err_free;
14277 }
14278 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14279 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14280 goto err_free;
14281 }
14282
d30d42e0 14283 prev_offset = krecord[i].insn_off;
af2ac3e1 14284 bpfptr_add(&urecord, urec_size);
838e9690
YS
14285 }
14286
ba64e7d8
YS
14287 prog->aux->func_info = krecord;
14288 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 14289 prog->aux->func_info_aux = info_aux;
838e9690
YS
14290 return 0;
14291
c454a46b 14292err_free:
ba64e7d8 14293 kvfree(krecord);
8c1b6e69 14294 kfree(info_aux);
838e9690
YS
14295 return ret;
14296}
14297
ba64e7d8
YS
14298static void adjust_btf_func(struct bpf_verifier_env *env)
14299{
8c1b6e69 14300 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
14301 int i;
14302
8c1b6e69 14303 if (!aux->func_info)
ba64e7d8
YS
14304 return;
14305
14306 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 14307 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
14308}
14309
1b773d00 14310#define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
c454a46b
MKL
14311#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
14312
14313static int check_btf_line(struct bpf_verifier_env *env,
14314 const union bpf_attr *attr,
af2ac3e1 14315 bpfptr_t uattr)
c454a46b
MKL
14316{
14317 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14318 struct bpf_subprog_info *sub;
14319 struct bpf_line_info *linfo;
14320 struct bpf_prog *prog;
14321 const struct btf *btf;
af2ac3e1 14322 bpfptr_t ulinfo;
c454a46b
MKL
14323 int err;
14324
14325 nr_linfo = attr->line_info_cnt;
14326 if (!nr_linfo)
14327 return 0;
0e6491b5
BC
14328 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14329 return -EINVAL;
c454a46b
MKL
14330
14331 rec_size = attr->line_info_rec_size;
14332 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14333 rec_size > MAX_LINEINFO_REC_SIZE ||
14334 rec_size & (sizeof(u32) - 1))
14335 return -EINVAL;
14336
14337 /* Need to zero it in case the userspace may
14338 * pass in a smaller bpf_line_info object.
14339 */
14340 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14341 GFP_KERNEL | __GFP_NOWARN);
14342 if (!linfo)
14343 return -ENOMEM;
14344
14345 prog = env->prog;
14346 btf = prog->aux->btf;
14347
14348 s = 0;
14349 sub = env->subprog_info;
af2ac3e1 14350 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
c454a46b
MKL
14351 expected_size = sizeof(struct bpf_line_info);
14352 ncopy = min_t(u32, expected_size, rec_size);
14353 for (i = 0; i < nr_linfo; i++) {
14354 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14355 if (err) {
14356 if (err == -E2BIG) {
14357 verbose(env, "nonzero tailing record in line_info");
af2ac3e1
AS
14358 if (copy_to_bpfptr_offset(uattr,
14359 offsetof(union bpf_attr, line_info_rec_size),
14360 &expected_size, sizeof(expected_size)))
c454a46b
MKL
14361 err = -EFAULT;
14362 }
14363 goto err_free;
14364 }
14365
af2ac3e1 14366 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
c454a46b
MKL
14367 err = -EFAULT;
14368 goto err_free;
14369 }
14370
14371 /*
14372 * Check insn_off to ensure
14373 * 1) strictly increasing AND
14374 * 2) bounded by prog->len
14375 *
14376 * The linfo[0].insn_off == 0 check logically falls into
14377 * the later "missing bpf_line_info for func..." case
14378 * because the first linfo[0].insn_off must be the
14379 * first sub also and the first sub must have
14380 * subprog_info[0].start == 0.
14381 */
14382 if ((i && linfo[i].insn_off <= prev_offset) ||
14383 linfo[i].insn_off >= prog->len) {
14384 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14385 i, linfo[i].insn_off, prev_offset,
14386 prog->len);
14387 err = -EINVAL;
14388 goto err_free;
14389 }
14390
fdbaa0be
MKL
14391 if (!prog->insnsi[linfo[i].insn_off].code) {
14392 verbose(env,
14393 "Invalid insn code at line_info[%u].insn_off\n",
14394 i);
14395 err = -EINVAL;
14396 goto err_free;
14397 }
14398
23127b33
MKL
14399 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14400 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
14401 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14402 err = -EINVAL;
14403 goto err_free;
14404 }
14405
14406 if (s != env->subprog_cnt) {
14407 if (linfo[i].insn_off == sub[s].start) {
14408 sub[s].linfo_idx = i;
14409 s++;
14410 } else if (sub[s].start < linfo[i].insn_off) {
14411 verbose(env, "missing bpf_line_info for func#%u\n", s);
14412 err = -EINVAL;
14413 goto err_free;
14414 }
14415 }
14416
14417 prev_offset = linfo[i].insn_off;
af2ac3e1 14418 bpfptr_add(&ulinfo, rec_size);
c454a46b
MKL
14419 }
14420
14421 if (s != env->subprog_cnt) {
14422 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14423 env->subprog_cnt - s, s);
14424 err = -EINVAL;
14425 goto err_free;
14426 }
14427
14428 prog->aux->linfo = linfo;
14429 prog->aux->nr_linfo = nr_linfo;
14430
14431 return 0;
14432
14433err_free:
14434 kvfree(linfo);
14435 return err;
14436}
14437
fbd94c7a
AS
14438#define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
14439#define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
14440
14441static int check_core_relo(struct bpf_verifier_env *env,
14442 const union bpf_attr *attr,
14443 bpfptr_t uattr)
14444{
14445 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14446 struct bpf_core_relo core_relo = {};
14447 struct bpf_prog *prog = env->prog;
14448 const struct btf *btf = prog->aux->btf;
14449 struct bpf_core_ctx ctx = {
14450 .log = &env->log,
14451 .btf = btf,
14452 };
14453 bpfptr_t u_core_relo;
14454 int err;
14455
14456 nr_core_relo = attr->core_relo_cnt;
14457 if (!nr_core_relo)
14458 return 0;
14459 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14460 return -EINVAL;
14461
14462 rec_size = attr->core_relo_rec_size;
14463 if (rec_size < MIN_CORE_RELO_SIZE ||
14464 rec_size > MAX_CORE_RELO_SIZE ||
14465 rec_size % sizeof(u32))
14466 return -EINVAL;
14467
14468 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14469 expected_size = sizeof(struct bpf_core_relo);
14470 ncopy = min_t(u32, expected_size, rec_size);
14471
14472 /* Unlike func_info and line_info, copy and apply each CO-RE
14473 * relocation record one at a time.
14474 */
14475 for (i = 0; i < nr_core_relo; i++) {
14476 /* future proofing when sizeof(bpf_core_relo) changes */
14477 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14478 if (err) {
14479 if (err == -E2BIG) {
14480 verbose(env, "nonzero tailing record in core_relo");
14481 if (copy_to_bpfptr_offset(uattr,
14482 offsetof(union bpf_attr, core_relo_rec_size),
14483 &expected_size, sizeof(expected_size)))
14484 err = -EFAULT;
14485 }
14486 break;
14487 }
14488
14489 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14490 err = -EFAULT;
14491 break;
14492 }
14493
14494 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14495 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14496 i, core_relo.insn_off, prog->len);
14497 err = -EINVAL;
14498 break;
14499 }
14500
14501 err = bpf_core_apply(&ctx, &core_relo, i,
14502 &prog->insnsi[core_relo.insn_off / 8]);
14503 if (err)
14504 break;
14505 bpfptr_add(&u_core_relo, rec_size);
14506 }
14507 return err;
14508}
14509
c454a46b
MKL
14510static int check_btf_info(struct bpf_verifier_env *env,
14511 const union bpf_attr *attr,
af2ac3e1 14512 bpfptr_t uattr)
c454a46b
MKL
14513{
14514 struct btf *btf;
14515 int err;
14516
09b28d76
AS
14517 if (!attr->func_info_cnt && !attr->line_info_cnt) {
14518 if (check_abnormal_return(env))
14519 return -EINVAL;
c454a46b 14520 return 0;
09b28d76 14521 }
c454a46b
MKL
14522
14523 btf = btf_get_by_fd(attr->prog_btf_fd);
14524 if (IS_ERR(btf))
14525 return PTR_ERR(btf);
350a5c4d
AS
14526 if (btf_is_kernel(btf)) {
14527 btf_put(btf);
14528 return -EACCES;
14529 }
c454a46b
MKL
14530 env->prog->aux->btf = btf;
14531
14532 err = check_btf_func(env, attr, uattr);
14533 if (err)
14534 return err;
14535
14536 err = check_btf_line(env, attr, uattr);
14537 if (err)
14538 return err;
14539
fbd94c7a
AS
14540 err = check_core_relo(env, attr, uattr);
14541 if (err)
14542 return err;
14543
c454a46b 14544 return 0;
ba64e7d8
YS
14545}
14546
f1174f77
EC
14547/* check %cur's range satisfies %old's */
14548static bool range_within(struct bpf_reg_state *old,
14549 struct bpf_reg_state *cur)
14550{
b03c9f9f
EC
14551 return old->umin_value <= cur->umin_value &&
14552 old->umax_value >= cur->umax_value &&
14553 old->smin_value <= cur->smin_value &&
fd675184
DB
14554 old->smax_value >= cur->smax_value &&
14555 old->u32_min_value <= cur->u32_min_value &&
14556 old->u32_max_value >= cur->u32_max_value &&
14557 old->s32_min_value <= cur->s32_min_value &&
14558 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
14559}
14560
f1174f77
EC
14561/* If in the old state two registers had the same id, then they need to have
14562 * the same id in the new state as well. But that id could be different from
14563 * the old state, so we need to track the mapping from old to new ids.
14564 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14565 * regs with old id 5 must also have new id 9 for the new state to be safe. But
14566 * regs with a different old id could still have new id 9, we don't care about
14567 * that.
14568 * So we look through our idmap to see if this old id has been seen before. If
14569 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 14570 */
c9e73e3d 14571static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
969bf05e 14572{
f1174f77 14573 unsigned int i;
969bf05e 14574
4633a006
AN
14575 /* either both IDs should be set or both should be zero */
14576 if (!!old_id != !!cur_id)
14577 return false;
14578
14579 if (old_id == 0) /* cur_id == 0 as well */
14580 return true;
14581
c9e73e3d 14582 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
f1174f77
EC
14583 if (!idmap[i].old) {
14584 /* Reached an empty slot; haven't seen this id before */
14585 idmap[i].old = old_id;
14586 idmap[i].cur = cur_id;
14587 return true;
14588 }
14589 if (idmap[i].old == old_id)
14590 return idmap[i].cur == cur_id;
14591 }
14592 /* We ran out of idmap slots, which should be impossible */
14593 WARN_ON_ONCE(1);
14594 return false;
14595}
14596
9242b5f5
AS
14597static void clean_func_state(struct bpf_verifier_env *env,
14598 struct bpf_func_state *st)
14599{
14600 enum bpf_reg_liveness live;
14601 int i, j;
14602
14603 for (i = 0; i < BPF_REG_FP; i++) {
14604 live = st->regs[i].live;
14605 /* liveness must not touch this register anymore */
14606 st->regs[i].live |= REG_LIVE_DONE;
14607 if (!(live & REG_LIVE_READ))
14608 /* since the register is unused, clear its state
14609 * to make further comparison simpler
14610 */
f54c7898 14611 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
14612 }
14613
14614 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14615 live = st->stack[i].spilled_ptr.live;
14616 /* liveness must not touch this stack slot anymore */
14617 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14618 if (!(live & REG_LIVE_READ)) {
f54c7898 14619 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
14620 for (j = 0; j < BPF_REG_SIZE; j++)
14621 st->stack[i].slot_type[j] = STACK_INVALID;
14622 }
14623 }
14624}
14625
14626static void clean_verifier_state(struct bpf_verifier_env *env,
14627 struct bpf_verifier_state *st)
14628{
14629 int i;
14630
14631 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14632 /* all regs in this state in all frames were already marked */
14633 return;
14634
14635 for (i = 0; i <= st->curframe; i++)
14636 clean_func_state(env, st->frame[i]);
14637}
14638
14639/* the parentage chains form a tree.
14640 * the verifier states are added to state lists at given insn and
14641 * pushed into state stack for future exploration.
14642 * when the verifier reaches bpf_exit insn some of the verifer states
14643 * stored in the state lists have their final liveness state already,
14644 * but a lot of states will get revised from liveness point of view when
14645 * the verifier explores other branches.
14646 * Example:
14647 * 1: r0 = 1
14648 * 2: if r1 == 100 goto pc+1
14649 * 3: r0 = 2
14650 * 4: exit
14651 * when the verifier reaches exit insn the register r0 in the state list of
14652 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14653 * of insn 2 and goes exploring further. At the insn 4 it will walk the
14654 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14655 *
14656 * Since the verifier pushes the branch states as it sees them while exploring
14657 * the program the condition of walking the branch instruction for the second
14658 * time means that all states below this branch were already explored and
8fb33b60 14659 * their final liveness marks are already propagated.
9242b5f5
AS
14660 * Hence when the verifier completes the search of state list in is_state_visited()
14661 * we can call this clean_live_states() function to mark all liveness states
14662 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14663 * will not be used.
14664 * This function also clears the registers and stack for states that !READ
14665 * to simplify state merging.
14666 *
14667 * Important note here that walking the same branch instruction in the callee
14668 * doesn't meant that the states are DONE. The verifier has to compare
14669 * the callsites
14670 */
14671static void clean_live_states(struct bpf_verifier_env *env, int insn,
14672 struct bpf_verifier_state *cur)
14673{
14674 struct bpf_verifier_state_list *sl;
14675 int i;
14676
5d839021 14677 sl = *explored_state(env, insn);
a8f500af 14678 while (sl) {
2589726d
AS
14679 if (sl->state.branches)
14680 goto next;
dc2a4ebc
AS
14681 if (sl->state.insn_idx != insn ||
14682 sl->state.curframe != cur->curframe)
9242b5f5
AS
14683 goto next;
14684 for (i = 0; i <= cur->curframe; i++)
14685 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14686 goto next;
14687 clean_verifier_state(env, &sl->state);
14688next:
14689 sl = sl->next;
14690 }
14691}
14692
4a95c85c 14693static bool regs_exact(const struct bpf_reg_state *rold,
4633a006
AN
14694 const struct bpf_reg_state *rcur,
14695 struct bpf_id_pair *idmap)
4a95c85c 14696{
4633a006
AN
14697 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
14698 check_ids(rold->id, rcur->id, idmap) &&
14699 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
4a95c85c
AN
14700}
14701
f1174f77 14702/* Returns true if (rold safe implies rcur safe) */
e042aa53
DB
14703static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14704 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
f1174f77 14705{
dc503a8a
EC
14706 if (!(rold->live & REG_LIVE_READ))
14707 /* explored state didn't use this */
14708 return true;
f1174f77
EC
14709 if (rold->type == NOT_INIT)
14710 /* explored state can't have used this */
969bf05e 14711 return true;
f1174f77
EC
14712 if (rcur->type == NOT_INIT)
14713 return false;
7f4ce97c 14714
910f6999
AN
14715 /* Enforce that register types have to match exactly, including their
14716 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14717 * rule.
14718 *
14719 * One can make a point that using a pointer register as unbounded
14720 * SCALAR would be technically acceptable, but this could lead to
14721 * pointer leaks because scalars are allowed to leak while pointers
14722 * are not. We could make this safe in special cases if root is
14723 * calling us, but it's probably not worth the hassle.
14724 *
14725 * Also, register types that are *not* MAYBE_NULL could technically be
14726 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14727 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14728 * to the same map).
7f4ce97c
AN
14729 * However, if the old MAYBE_NULL register then got NULL checked,
14730 * doing so could have affected others with the same id, and we can't
14731 * check for that because we lost the id when we converted to
14732 * a non-MAYBE_NULL variant.
14733 * So, as a general rule we don't allow mixing MAYBE_NULL and
910f6999 14734 * non-MAYBE_NULL registers as well.
7f4ce97c 14735 */
910f6999 14736 if (rold->type != rcur->type)
7f4ce97c
AN
14737 return false;
14738
c25b2ae1 14739 switch (base_type(rold->type)) {
f1174f77 14740 case SCALAR_VALUE:
4633a006 14741 if (regs_exact(rold, rcur, idmap))
7c884339 14742 return true;
e042aa53
DB
14743 if (env->explore_alu_limits)
14744 return false;
910f6999
AN
14745 if (!rold->precise)
14746 return true;
14747 /* new val must satisfy old val knowledge */
14748 return range_within(rold, rcur) &&
14749 tnum_in(rold->var_off, rcur->var_off);
69c087ba 14750 case PTR_TO_MAP_KEY:
f1174f77 14751 case PTR_TO_MAP_VALUE:
567da5d2
AN
14752 case PTR_TO_MEM:
14753 case PTR_TO_BUF:
14754 case PTR_TO_TP_BUFFER:
1b688a19
EC
14755 /* If the new min/max/var_off satisfy the old ones and
14756 * everything else matches, we are OK.
1b688a19 14757 */
a73bf9f2 14758 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
1b688a19 14759 range_within(rold, rcur) &&
4ea2bb15 14760 tnum_in(rold->var_off, rcur->var_off) &&
567da5d2
AN
14761 check_ids(rold->id, rcur->id, idmap) &&
14762 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
de8f3a83 14763 case PTR_TO_PACKET_META:
f1174f77 14764 case PTR_TO_PACKET:
f1174f77
EC
14765 /* We must have at least as much range as the old ptr
14766 * did, so that any accesses which were safe before are
14767 * still safe. This is true even if old range < old off,
14768 * since someone could have accessed through (ptr - k), or
14769 * even done ptr -= k in a register, to get a safe access.
14770 */
14771 if (rold->range > rcur->range)
14772 return false;
14773 /* If the offsets don't match, we can't trust our alignment;
14774 * nor can we be sure that we won't fall out of range.
14775 */
14776 if (rold->off != rcur->off)
14777 return false;
14778 /* id relations must be preserved */
4633a006 14779 if (!check_ids(rold->id, rcur->id, idmap))
f1174f77
EC
14780 return false;
14781 /* new val must satisfy old val knowledge */
14782 return range_within(rold, rcur) &&
14783 tnum_in(rold->var_off, rcur->var_off);
7c884339
EZ
14784 case PTR_TO_STACK:
14785 /* two stack pointers are equal only if they're pointing to
14786 * the same stack frame, since fp-8 in foo != fp-8 in bar
f1174f77 14787 */
4633a006 14788 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
f1174f77 14789 default:
4633a006 14790 return regs_exact(rold, rcur, idmap);
f1174f77 14791 }
969bf05e
AS
14792}
14793
e042aa53
DB
14794static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14795 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
638f5b90
AS
14796{
14797 int i, spi;
14798
638f5b90
AS
14799 /* walk slots of the explored stack and ignore any additional
14800 * slots in the current stack, since explored(safe) state
14801 * didn't use them
14802 */
14803 for (i = 0; i < old->allocated_stack; i++) {
06accc87
AN
14804 struct bpf_reg_state *old_reg, *cur_reg;
14805
638f5b90
AS
14806 spi = i / BPF_REG_SIZE;
14807
b233920c
AS
14808 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14809 i += BPF_REG_SIZE - 1;
cc2b14d5 14810 /* explored state didn't use this */
fd05e57b 14811 continue;
b233920c 14812 }
cc2b14d5 14813
638f5b90
AS
14814 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14815 continue;
19e2dbb7 14816
6715df8d
EZ
14817 if (env->allow_uninit_stack &&
14818 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14819 continue;
14820
19e2dbb7
AS
14821 /* explored stack has more populated slots than current stack
14822 * and these slots were used
14823 */
14824 if (i >= cur->allocated_stack)
14825 return false;
14826
cc2b14d5
AS
14827 /* if old state was safe with misc data in the stack
14828 * it will be safe with zero-initialized stack.
14829 * The opposite is not true
14830 */
14831 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14832 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14833 continue;
638f5b90
AS
14834 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14835 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14836 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 14837 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
14838 * this verifier states are not equivalent,
14839 * return false to continue verification of this path
14840 */
14841 return false;
27113c59 14842 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
638f5b90 14843 continue;
d6fefa11
KKD
14844 /* Both old and cur are having same slot_type */
14845 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14846 case STACK_SPILL:
638f5b90
AS
14847 /* when explored and current stack slot are both storing
14848 * spilled registers, check that stored pointers types
14849 * are the same as well.
14850 * Ex: explored safe path could have stored
14851 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14852 * but current path has stored:
14853 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14854 * such verifier states are not equivalent.
14855 * return false to continue verification of this path
14856 */
d6fefa11
KKD
14857 if (!regsafe(env, &old->stack[spi].spilled_ptr,
14858 &cur->stack[spi].spilled_ptr, idmap))
14859 return false;
14860 break;
14861 case STACK_DYNPTR:
d6fefa11
KKD
14862 old_reg = &old->stack[spi].spilled_ptr;
14863 cur_reg = &cur->stack[spi].spilled_ptr;
14864 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14865 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14866 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14867 return false;
14868 break;
06accc87
AN
14869 case STACK_ITER:
14870 old_reg = &old->stack[spi].spilled_ptr;
14871 cur_reg = &cur->stack[spi].spilled_ptr;
14872 /* iter.depth is not compared between states as it
14873 * doesn't matter for correctness and would otherwise
14874 * prevent convergence; we maintain it only to prevent
14875 * infinite loop check triggering, see
14876 * iter_active_depths_differ()
14877 */
14878 if (old_reg->iter.btf != cur_reg->iter.btf ||
14879 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
14880 old_reg->iter.state != cur_reg->iter.state ||
14881 /* ignore {old_reg,cur_reg}->iter.depth, see above */
14882 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14883 return false;
14884 break;
d6fefa11
KKD
14885 case STACK_MISC:
14886 case STACK_ZERO:
14887 case STACK_INVALID:
14888 continue;
14889 /* Ensure that new unhandled slot types return false by default */
14890 default:
638f5b90 14891 return false;
d6fefa11 14892 }
638f5b90
AS
14893 }
14894 return true;
14895}
14896
e8f55fcf
AN
14897static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14898 struct bpf_id_pair *idmap)
fd978bf7 14899{
e8f55fcf
AN
14900 int i;
14901
fd978bf7
JS
14902 if (old->acquired_refs != cur->acquired_refs)
14903 return false;
e8f55fcf
AN
14904
14905 for (i = 0; i < old->acquired_refs; i++) {
14906 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14907 return false;
14908 }
14909
14910 return true;
fd978bf7
JS
14911}
14912
f1bca824
AS
14913/* compare two verifier states
14914 *
14915 * all states stored in state_list are known to be valid, since
14916 * verifier reached 'bpf_exit' instruction through them
14917 *
14918 * this function is called when verifier exploring different branches of
14919 * execution popped from the state stack. If it sees an old state that has
14920 * more strict register state and more strict stack state then this execution
14921 * branch doesn't need to be explored further, since verifier already
14922 * concluded that more strict state leads to valid finish.
14923 *
14924 * Therefore two states are equivalent if register state is more conservative
14925 * and explored stack state is more conservative than the current one.
14926 * Example:
14927 * explored current
14928 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14929 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14930 *
14931 * In other words if current stack state (one being explored) has more
14932 * valid slots than old one that already passed validation, it means
14933 * the verifier can stop exploring and conclude that current state is valid too
14934 *
14935 * Similarly with registers. If explored state has register type as invalid
14936 * whereas register type in current state is meaningful, it means that
14937 * the current state will reach 'bpf_exit' instruction safely
14938 */
c9e73e3d 14939static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
f4d7e40a 14940 struct bpf_func_state *cur)
f1bca824
AS
14941{
14942 int i;
14943
c9e73e3d 14944 for (i = 0; i < MAX_BPF_REG; i++)
e042aa53
DB
14945 if (!regsafe(env, &old->regs[i], &cur->regs[i],
14946 env->idmap_scratch))
c9e73e3d 14947 return false;
f1bca824 14948
e042aa53 14949 if (!stacksafe(env, old, cur, env->idmap_scratch))
c9e73e3d 14950 return false;
fd978bf7 14951
e8f55fcf 14952 if (!refsafe(old, cur, env->idmap_scratch))
c9e73e3d
LB
14953 return false;
14954
14955 return true;
f1bca824
AS
14956}
14957
f4d7e40a
AS
14958static bool states_equal(struct bpf_verifier_env *env,
14959 struct bpf_verifier_state *old,
14960 struct bpf_verifier_state *cur)
14961{
14962 int i;
14963
14964 if (old->curframe != cur->curframe)
14965 return false;
14966
5dd9cdbc
EZ
14967 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14968
979d63d5
DB
14969 /* Verification state from speculative execution simulation
14970 * must never prune a non-speculative execution one.
14971 */
14972 if (old->speculative && !cur->speculative)
14973 return false;
14974
4ea2bb15
EZ
14975 if (old->active_lock.ptr != cur->active_lock.ptr)
14976 return false;
14977
14978 /* Old and cur active_lock's have to be either both present
14979 * or both absent.
14980 */
14981 if (!!old->active_lock.id != !!cur->active_lock.id)
14982 return false;
14983
14984 if (old->active_lock.id &&
14985 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
d83525ca
AS
14986 return false;
14987
9bb00b28 14988 if (old->active_rcu_lock != cur->active_rcu_lock)
d83525ca
AS
14989 return false;
14990
f4d7e40a
AS
14991 /* for states to be equal callsites have to be the same
14992 * and all frame states need to be equivalent
14993 */
14994 for (i = 0; i <= old->curframe; i++) {
14995 if (old->frame[i]->callsite != cur->frame[i]->callsite)
14996 return false;
c9e73e3d 14997 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
f4d7e40a
AS
14998 return false;
14999 }
15000 return true;
15001}
15002
5327ed3d
JW
15003/* Return 0 if no propagation happened. Return negative error code if error
15004 * happened. Otherwise, return the propagated bit.
15005 */
55e7f3b5
JW
15006static int propagate_liveness_reg(struct bpf_verifier_env *env,
15007 struct bpf_reg_state *reg,
15008 struct bpf_reg_state *parent_reg)
15009{
5327ed3d
JW
15010 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15011 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
15012 int err;
15013
5327ed3d
JW
15014 /* When comes here, read flags of PARENT_REG or REG could be any of
15015 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15016 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15017 */
15018 if (parent_flag == REG_LIVE_READ64 ||
15019 /* Or if there is no read flag from REG. */
15020 !flag ||
15021 /* Or if the read flag from REG is the same as PARENT_REG. */
15022 parent_flag == flag)
55e7f3b5
JW
15023 return 0;
15024
5327ed3d 15025 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
15026 if (err)
15027 return err;
15028
5327ed3d 15029 return flag;
55e7f3b5
JW
15030}
15031
8e9cd9ce 15032/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
15033 * straight-line code between a state and its parent. When we arrive at an
15034 * equivalent state (jump target or such) we didn't arrive by the straight-line
15035 * code, so read marks in the state must propagate to the parent regardless
15036 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 15037 * in mark_reg_read() is for.
8e9cd9ce 15038 */
f4d7e40a
AS
15039static int propagate_liveness(struct bpf_verifier_env *env,
15040 const struct bpf_verifier_state *vstate,
15041 struct bpf_verifier_state *vparent)
dc503a8a 15042{
3f8cafa4 15043 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 15044 struct bpf_func_state *state, *parent;
3f8cafa4 15045 int i, frame, err = 0;
dc503a8a 15046
f4d7e40a
AS
15047 if (vparent->curframe != vstate->curframe) {
15048 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15049 vparent->curframe, vstate->curframe);
15050 return -EFAULT;
15051 }
dc503a8a
EC
15052 /* Propagate read liveness of registers... */
15053 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 15054 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
15055 parent = vparent->frame[frame];
15056 state = vstate->frame[frame];
15057 parent_reg = parent->regs;
15058 state_reg = state->regs;
83d16312
JK
15059 /* We don't need to worry about FP liveness, it's read-only */
15060 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
15061 err = propagate_liveness_reg(env, &state_reg[i],
15062 &parent_reg[i]);
5327ed3d 15063 if (err < 0)
3f8cafa4 15064 return err;
5327ed3d
JW
15065 if (err == REG_LIVE_READ64)
15066 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 15067 }
f4d7e40a 15068
1b04aee7 15069 /* Propagate stack slots. */
f4d7e40a
AS
15070 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15071 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
15072 parent_reg = &parent->stack[i].spilled_ptr;
15073 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
15074 err = propagate_liveness_reg(env, state_reg,
15075 parent_reg);
5327ed3d 15076 if (err < 0)
3f8cafa4 15077 return err;
dc503a8a
EC
15078 }
15079 }
5327ed3d 15080 return 0;
dc503a8a
EC
15081}
15082
a3ce685d
AS
15083/* find precise scalars in the previous equivalent state and
15084 * propagate them into the current state
15085 */
15086static int propagate_precision(struct bpf_verifier_env *env,
15087 const struct bpf_verifier_state *old)
15088{
15089 struct bpf_reg_state *state_reg;
15090 struct bpf_func_state *state;
529409ea 15091 int i, err = 0, fr;
a3ce685d 15092
529409ea
AN
15093 for (fr = old->curframe; fr >= 0; fr--) {
15094 state = old->frame[fr];
15095 state_reg = state->regs;
15096 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15097 if (state_reg->type != SCALAR_VALUE ||
52c2b005
AN
15098 !state_reg->precise ||
15099 !(state_reg->live & REG_LIVE_READ))
529409ea
AN
15100 continue;
15101 if (env->log.level & BPF_LOG_LEVEL2)
34f0677e 15102 verbose(env, "frame %d: propagating r%d\n", fr, i);
529409ea
AN
15103 err = mark_chain_precision_frame(env, fr, i);
15104 if (err < 0)
15105 return err;
15106 }
a3ce685d 15107
529409ea
AN
15108 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15109 if (!is_spilled_reg(&state->stack[i]))
15110 continue;
15111 state_reg = &state->stack[i].spilled_ptr;
15112 if (state_reg->type != SCALAR_VALUE ||
52c2b005
AN
15113 !state_reg->precise ||
15114 !(state_reg->live & REG_LIVE_READ))
529409ea
AN
15115 continue;
15116 if (env->log.level & BPF_LOG_LEVEL2)
15117 verbose(env, "frame %d: propagating fp%d\n",
34f0677e 15118 fr, (-i - 1) * BPF_REG_SIZE);
529409ea
AN
15119 err = mark_chain_precision_stack_frame(env, fr, i);
15120 if (err < 0)
15121 return err;
15122 }
a3ce685d
AS
15123 }
15124 return 0;
15125}
15126
2589726d
AS
15127static bool states_maybe_looping(struct bpf_verifier_state *old,
15128 struct bpf_verifier_state *cur)
15129{
15130 struct bpf_func_state *fold, *fcur;
15131 int i, fr = cur->curframe;
15132
15133 if (old->curframe != fr)
15134 return false;
15135
15136 fold = old->frame[fr];
15137 fcur = cur->frame[fr];
15138 for (i = 0; i < MAX_BPF_REG; i++)
15139 if (memcmp(&fold->regs[i], &fcur->regs[i],
15140 offsetof(struct bpf_reg_state, parent)))
15141 return false;
15142 return true;
15143}
15144
06accc87
AN
15145static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15146{
15147 return env->insn_aux_data[insn_idx].is_iter_next;
15148}
15149
15150/* is_state_visited() handles iter_next() (see process_iter_next_call() for
15151 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15152 * states to match, which otherwise would look like an infinite loop. So while
15153 * iter_next() calls are taken care of, we still need to be careful and
15154 * prevent erroneous and too eager declaration of "ininite loop", when
15155 * iterators are involved.
15156 *
15157 * Here's a situation in pseudo-BPF assembly form:
15158 *
15159 * 0: again: ; set up iter_next() call args
15160 * 1: r1 = &it ; <CHECKPOINT HERE>
15161 * 2: call bpf_iter_num_next ; this is iter_next() call
15162 * 3: if r0 == 0 goto done
15163 * 4: ... something useful here ...
15164 * 5: goto again ; another iteration
15165 * 6: done:
15166 * 7: r1 = &it
15167 * 8: call bpf_iter_num_destroy ; clean up iter state
15168 * 9: exit
15169 *
15170 * This is a typical loop. Let's assume that we have a prune point at 1:,
15171 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15172 * again`, assuming other heuristics don't get in a way).
15173 *
15174 * When we first time come to 1:, let's say we have some state X. We proceed
15175 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15176 * Now we come back to validate that forked ACTIVE state. We proceed through
15177 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15178 * are converging. But the problem is that we don't know that yet, as this
15179 * convergence has to happen at iter_next() call site only. So if nothing is
15180 * done, at 1: verifier will use bounded loop logic and declare infinite
15181 * looping (and would be *technically* correct, if not for iterator's
15182 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15183 * don't want that. So what we do in process_iter_next_call() when we go on
15184 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15185 * a different iteration. So when we suspect an infinite loop, we additionally
15186 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15187 * pretend we are not looping and wait for next iter_next() call.
15188 *
15189 * This only applies to ACTIVE state. In DRAINED state we don't expect to
15190 * loop, because that would actually mean infinite loop, as DRAINED state is
15191 * "sticky", and so we'll keep returning into the same instruction with the
15192 * same state (at least in one of possible code paths).
15193 *
15194 * This approach allows to keep infinite loop heuristic even in the face of
15195 * active iterator. E.g., C snippet below is and will be detected as
15196 * inifintely looping:
15197 *
15198 * struct bpf_iter_num it;
15199 * int *p, x;
15200 *
15201 * bpf_iter_num_new(&it, 0, 10);
15202 * while ((p = bpf_iter_num_next(&t))) {
15203 * x = p;
15204 * while (x--) {} // <<-- infinite loop here
15205 * }
15206 *
15207 */
15208static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15209{
15210 struct bpf_reg_state *slot, *cur_slot;
15211 struct bpf_func_state *state;
15212 int i, fr;
15213
15214 for (fr = old->curframe; fr >= 0; fr--) {
15215 state = old->frame[fr];
15216 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15217 if (state->stack[i].slot_type[0] != STACK_ITER)
15218 continue;
15219
15220 slot = &state->stack[i].spilled_ptr;
15221 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15222 continue;
15223
15224 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15225 if (cur_slot->iter.depth != slot->iter.depth)
15226 return true;
15227 }
15228 }
15229 return false;
15230}
2589726d 15231
58e2af8b 15232static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 15233{
58e2af8b 15234 struct bpf_verifier_state_list *new_sl;
9f4686c4 15235 struct bpf_verifier_state_list *sl, **pprev;
679c782d 15236 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 15237 int i, j, err, states_cnt = 0;
4b5ce570
AN
15238 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15239 bool add_new_state = force_new_state;
f1bca824 15240
2589726d
AS
15241 /* bpf progs typically have pruning point every 4 instructions
15242 * http://vger.kernel.org/bpfconf2019.html#session-1
15243 * Do not add new state for future pruning if the verifier hasn't seen
15244 * at least 2 jumps and at least 8 instructions.
15245 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15246 * In tests that amounts to up to 50% reduction into total verifier
15247 * memory consumption and 20% verifier time speedup.
15248 */
15249 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15250 env->insn_processed - env->prev_insn_processed >= 8)
15251 add_new_state = true;
15252
a8f500af
AS
15253 pprev = explored_state(env, insn_idx);
15254 sl = *pprev;
15255
9242b5f5
AS
15256 clean_live_states(env, insn_idx, cur);
15257
a8f500af 15258 while (sl) {
dc2a4ebc
AS
15259 states_cnt++;
15260 if (sl->state.insn_idx != insn_idx)
15261 goto next;
bfc6bb74 15262
2589726d 15263 if (sl->state.branches) {
bfc6bb74
AS
15264 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15265
15266 if (frame->in_async_callback_fn &&
15267 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15268 /* Different async_entry_cnt means that the verifier is
15269 * processing another entry into async callback.
15270 * Seeing the same state is not an indication of infinite
15271 * loop or infinite recursion.
15272 * But finding the same state doesn't mean that it's safe
15273 * to stop processing the current state. The previous state
15274 * hasn't yet reached bpf_exit, since state.branches > 0.
15275 * Checking in_async_callback_fn alone is not enough either.
15276 * Since the verifier still needs to catch infinite loops
15277 * inside async callbacks.
15278 */
06accc87
AN
15279 goto skip_inf_loop_check;
15280 }
15281 /* BPF open-coded iterators loop detection is special.
15282 * states_maybe_looping() logic is too simplistic in detecting
15283 * states that *might* be equivalent, because it doesn't know
15284 * about ID remapping, so don't even perform it.
15285 * See process_iter_next_call() and iter_active_depths_differ()
15286 * for overview of the logic. When current and one of parent
15287 * states are detected as equivalent, it's a good thing: we prove
15288 * convergence and can stop simulating further iterations.
15289 * It's safe to assume that iterator loop will finish, taking into
15290 * account iter_next() contract of eventually returning
15291 * sticky NULL result.
15292 */
15293 if (is_iter_next_insn(env, insn_idx)) {
15294 if (states_equal(env, &sl->state, cur)) {
15295 struct bpf_func_state *cur_frame;
15296 struct bpf_reg_state *iter_state, *iter_reg;
15297 int spi;
15298
15299 cur_frame = cur->frame[cur->curframe];
15300 /* btf_check_iter_kfuncs() enforces that
15301 * iter state pointer is always the first arg
15302 */
15303 iter_reg = &cur_frame->regs[BPF_REG_1];
15304 /* current state is valid due to states_equal(),
15305 * so we can assume valid iter and reg state,
15306 * no need for extra (re-)validations
15307 */
15308 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15309 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15310 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15311 goto hit;
15312 }
15313 goto skip_inf_loop_check;
15314 }
15315 /* attempt to detect infinite loop to avoid unnecessary doomed work */
15316 if (states_maybe_looping(&sl->state, cur) &&
15317 states_equal(env, &sl->state, cur) &&
15318 !iter_active_depths_differ(&sl->state, cur)) {
2589726d
AS
15319 verbose_linfo(env, insn_idx, "; ");
15320 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15321 return -EINVAL;
15322 }
15323 /* if the verifier is processing a loop, avoid adding new state
15324 * too often, since different loop iterations have distinct
15325 * states and may not help future pruning.
15326 * This threshold shouldn't be too low to make sure that
15327 * a loop with large bound will be rejected quickly.
15328 * The most abusive loop will be:
15329 * r1 += 1
15330 * if r1 < 1000000 goto pc-2
15331 * 1M insn_procssed limit / 100 == 10k peak states.
15332 * This threshold shouldn't be too high either, since states
15333 * at the end of the loop are likely to be useful in pruning.
15334 */
06accc87 15335skip_inf_loop_check:
4b5ce570 15336 if (!force_new_state &&
98ddcf38 15337 env->jmps_processed - env->prev_jmps_processed < 20 &&
2589726d
AS
15338 env->insn_processed - env->prev_insn_processed < 100)
15339 add_new_state = false;
15340 goto miss;
15341 }
638f5b90 15342 if (states_equal(env, &sl->state, cur)) {
06accc87 15343hit:
9f4686c4 15344 sl->hit_cnt++;
f1bca824 15345 /* reached equivalent register/stack state,
dc503a8a
EC
15346 * prune the search.
15347 * Registers read by the continuation are read by us.
8e9cd9ce
EC
15348 * If we have any write marks in env->cur_state, they
15349 * will prevent corresponding reads in the continuation
15350 * from reaching our parent (an explored_state). Our
15351 * own state will get the read marks recorded, but
15352 * they'll be immediately forgotten as we're pruning
15353 * this state and will pop a new one.
f1bca824 15354 */
f4d7e40a 15355 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
15356
15357 /* if previous state reached the exit with precision and
15358 * current state is equivalent to it (except precsion marks)
15359 * the precision needs to be propagated back in
15360 * the current state.
15361 */
15362 err = err ? : push_jmp_history(env, cur);
15363 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
15364 if (err)
15365 return err;
f1bca824 15366 return 1;
dc503a8a 15367 }
2589726d
AS
15368miss:
15369 /* when new state is not going to be added do not increase miss count.
15370 * Otherwise several loop iterations will remove the state
15371 * recorded earlier. The goal of these heuristics is to have
15372 * states from some iterations of the loop (some in the beginning
15373 * and some at the end) to help pruning.
15374 */
15375 if (add_new_state)
15376 sl->miss_cnt++;
9f4686c4
AS
15377 /* heuristic to determine whether this state is beneficial
15378 * to keep checking from state equivalence point of view.
15379 * Higher numbers increase max_states_per_insn and verification time,
15380 * but do not meaningfully decrease insn_processed.
15381 */
15382 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15383 /* the state is unlikely to be useful. Remove it to
15384 * speed up verification
15385 */
15386 *pprev = sl->next;
15387 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
15388 u32 br = sl->state.branches;
15389
15390 WARN_ONCE(br,
15391 "BUG live_done but branches_to_explore %d\n",
15392 br);
9f4686c4
AS
15393 free_verifier_state(&sl->state, false);
15394 kfree(sl);
15395 env->peak_states--;
15396 } else {
15397 /* cannot free this state, since parentage chain may
15398 * walk it later. Add it for free_list instead to
15399 * be freed at the end of verification
15400 */
15401 sl->next = env->free_list;
15402 env->free_list = sl;
15403 }
15404 sl = *pprev;
15405 continue;
15406 }
dc2a4ebc 15407next:
9f4686c4
AS
15408 pprev = &sl->next;
15409 sl = *pprev;
f1bca824
AS
15410 }
15411
06ee7115
AS
15412 if (env->max_states_per_insn < states_cnt)
15413 env->max_states_per_insn = states_cnt;
15414
2c78ee89 15415 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
a095f421 15416 return 0;
ceefbc96 15417
2589726d 15418 if (!add_new_state)
a095f421 15419 return 0;
ceefbc96 15420
2589726d
AS
15421 /* There were no equivalent states, remember the current one.
15422 * Technically the current state is not proven to be safe yet,
f4d7e40a 15423 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 15424 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 15425 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
15426 * again on the way to bpf_exit.
15427 * When looping the sl->state.branches will be > 0 and this state
15428 * will not be considered for equivalence until branches == 0.
f1bca824 15429 */
638f5b90 15430 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
15431 if (!new_sl)
15432 return -ENOMEM;
06ee7115
AS
15433 env->total_states++;
15434 env->peak_states++;
2589726d
AS
15435 env->prev_jmps_processed = env->jmps_processed;
15436 env->prev_insn_processed = env->insn_processed;
f1bca824 15437
7a830b53
AN
15438 /* forget precise markings we inherited, see __mark_chain_precision */
15439 if (env->bpf_capable)
15440 mark_all_scalars_imprecise(env, cur);
15441
f1bca824 15442 /* add new state to the head of linked list */
679c782d
EC
15443 new = &new_sl->state;
15444 err = copy_verifier_state(new, cur);
1969db47 15445 if (err) {
679c782d 15446 free_verifier_state(new, false);
1969db47
AS
15447 kfree(new_sl);
15448 return err;
15449 }
dc2a4ebc 15450 new->insn_idx = insn_idx;
2589726d
AS
15451 WARN_ONCE(new->branches != 1,
15452 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 15453
2589726d 15454 cur->parent = new;
b5dc0163
AS
15455 cur->first_insn_idx = insn_idx;
15456 clear_jmp_history(cur);
5d839021
AS
15457 new_sl->next = *explored_state(env, insn_idx);
15458 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
15459 /* connect new state to parentage chain. Current frame needs all
15460 * registers connected. Only r6 - r9 of the callers are alive (pushed
15461 * to the stack implicitly by JITs) so in callers' frames connect just
15462 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15463 * the state of the call instruction (with WRITTEN set), and r0 comes
15464 * from callee with its full parentage chain, anyway.
15465 */
8e9cd9ce
EC
15466 /* clear write marks in current state: the writes we did are not writes
15467 * our child did, so they don't screen off its reads from us.
15468 * (There are no read marks in current state, because reads always mark
15469 * their parent and current state never has children yet. Only
15470 * explored_states can get read marks.)
15471 */
eea1c227
AS
15472 for (j = 0; j <= cur->curframe; j++) {
15473 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15474 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15475 for (i = 0; i < BPF_REG_FP; i++)
15476 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15477 }
f4d7e40a
AS
15478
15479 /* all stack frames are accessible from callee, clear them all */
15480 for (j = 0; j <= cur->curframe; j++) {
15481 struct bpf_func_state *frame = cur->frame[j];
679c782d 15482 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 15483
679c782d 15484 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 15485 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
15486 frame->stack[i].spilled_ptr.parent =
15487 &newframe->stack[i].spilled_ptr;
15488 }
f4d7e40a 15489 }
f1bca824
AS
15490 return 0;
15491}
15492
c64b7983
JS
15493/* Return true if it's OK to have the same insn return a different type. */
15494static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15495{
c25b2ae1 15496 switch (base_type(type)) {
c64b7983
JS
15497 case PTR_TO_CTX:
15498 case PTR_TO_SOCKET:
46f8bc92 15499 case PTR_TO_SOCK_COMMON:
655a51e5 15500 case PTR_TO_TCP_SOCK:
fada7fdc 15501 case PTR_TO_XDP_SOCK:
2a02759e 15502 case PTR_TO_BTF_ID:
c64b7983
JS
15503 return false;
15504 default:
15505 return true;
15506 }
15507}
15508
15509/* If an instruction was previously used with particular pointer types, then we
15510 * need to be careful to avoid cases such as the below, where it may be ok
15511 * for one branch accessing the pointer, but not ok for the other branch:
15512 *
15513 * R1 = sock_ptr
15514 * goto X;
15515 * ...
15516 * R1 = some_other_valid_ptr;
15517 * goto X;
15518 * ...
15519 * R2 = *(u32 *)(R1 + 0);
15520 */
15521static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15522{
15523 return src != prev && (!reg_type_mismatch_ok(src) ||
15524 !reg_type_mismatch_ok(prev));
15525}
15526
0d80a619
EZ
15527static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15528 bool allow_trust_missmatch)
15529{
15530 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15531
15532 if (*prev_type == NOT_INIT) {
15533 /* Saw a valid insn
15534 * dst_reg = *(u32 *)(src_reg + off)
15535 * save type to validate intersecting paths
15536 */
15537 *prev_type = type;
15538 } else if (reg_type_mismatch(type, *prev_type)) {
15539 /* Abuser program is trying to use the same insn
15540 * dst_reg = *(u32*) (src_reg + off)
15541 * with different pointer types:
15542 * src_reg == ctx in one branch and
15543 * src_reg == stack|map in some other branch.
15544 * Reject it.
15545 */
15546 if (allow_trust_missmatch &&
15547 base_type(type) == PTR_TO_BTF_ID &&
15548 base_type(*prev_type) == PTR_TO_BTF_ID) {
15549 /*
15550 * Have to support a use case when one path through
15551 * the program yields TRUSTED pointer while another
15552 * is UNTRUSTED. Fallback to UNTRUSTED to generate
15553 * BPF_PROBE_MEM.
15554 */
15555 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15556 } else {
15557 verbose(env, "same insn cannot be used with different pointers\n");
15558 return -EINVAL;
15559 }
15560 }
15561
15562 return 0;
15563}
15564
58e2af8b 15565static int do_check(struct bpf_verifier_env *env)
17a52670 15566{
6f8a57cc 15567 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 15568 struct bpf_verifier_state *state = env->cur_state;
17a52670 15569 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 15570 struct bpf_reg_state *regs;
06ee7115 15571 int insn_cnt = env->prog->len;
17a52670 15572 bool do_print_state = false;
b5dc0163 15573 int prev_insn_idx = -1;
17a52670 15574
17a52670
AS
15575 for (;;) {
15576 struct bpf_insn *insn;
15577 u8 class;
15578 int err;
15579
b5dc0163 15580 env->prev_insn_idx = prev_insn_idx;
c08435ec 15581 if (env->insn_idx >= insn_cnt) {
61bd5218 15582 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 15583 env->insn_idx, insn_cnt);
17a52670
AS
15584 return -EFAULT;
15585 }
15586
c08435ec 15587 insn = &insns[env->insn_idx];
17a52670
AS
15588 class = BPF_CLASS(insn->code);
15589
06ee7115 15590 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
15591 verbose(env,
15592 "BPF program is too large. Processed %d insn\n",
06ee7115 15593 env->insn_processed);
17a52670
AS
15594 return -E2BIG;
15595 }
15596
a095f421
AN
15597 state->last_insn_idx = env->prev_insn_idx;
15598
15599 if (is_prune_point(env, env->insn_idx)) {
15600 err = is_state_visited(env, env->insn_idx);
15601 if (err < 0)
15602 return err;
15603 if (err == 1) {
15604 /* found equivalent state, can prune the search */
15605 if (env->log.level & BPF_LOG_LEVEL) {
15606 if (do_print_state)
15607 verbose(env, "\nfrom %d to %d%s: safe\n",
15608 env->prev_insn_idx, env->insn_idx,
15609 env->cur_state->speculative ?
15610 " (speculative execution)" : "");
15611 else
15612 verbose(env, "%d: safe\n", env->insn_idx);
15613 }
15614 goto process_bpf_exit;
f1bca824 15615 }
a095f421
AN
15616 }
15617
15618 if (is_jmp_point(env, env->insn_idx)) {
15619 err = push_jmp_history(env, state);
15620 if (err)
15621 return err;
f1bca824
AS
15622 }
15623
c3494801
AS
15624 if (signal_pending(current))
15625 return -EAGAIN;
15626
3c2ce60b
DB
15627 if (need_resched())
15628 cond_resched();
15629
2e576648
CL
15630 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
15631 verbose(env, "\nfrom %d to %d%s:",
15632 env->prev_insn_idx, env->insn_idx,
15633 env->cur_state->speculative ?
15634 " (speculative execution)" : "");
15635 print_verifier_state(env, state->frame[state->curframe], true);
17a52670
AS
15636 do_print_state = false;
15637 }
15638
06ee7115 15639 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 15640 const struct bpf_insn_cbs cbs = {
e6ac2450 15641 .cb_call = disasm_kfunc_name,
7105e828 15642 .cb_print = verbose,
abe08840 15643 .private_data = env,
7105e828
DB
15644 };
15645
2e576648
CL
15646 if (verifier_state_scratched(env))
15647 print_insn_state(env, state->frame[state->curframe]);
15648
c08435ec 15649 verbose_linfo(env, env->insn_idx, "; ");
2e576648 15650 env->prev_log_len = env->log.len_used;
c08435ec 15651 verbose(env, "%d: ", env->insn_idx);
abe08840 15652 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2e576648
CL
15653 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
15654 env->prev_log_len = env->log.len_used;
17a52670
AS
15655 }
15656
9d03ebc7 15657 if (bpf_prog_is_offloaded(env->prog->aux)) {
c08435ec
DB
15658 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
15659 env->prev_insn_idx);
cae1927c
JK
15660 if (err)
15661 return err;
15662 }
13a27dfc 15663
638f5b90 15664 regs = cur_regs(env);
fe9a5ca7 15665 sanitize_mark_insn_seen(env);
b5dc0163 15666 prev_insn_idx = env->insn_idx;
fd978bf7 15667
17a52670 15668 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 15669 err = check_alu_op(env, insn);
17a52670
AS
15670 if (err)
15671 return err;
15672
15673 } else if (class == BPF_LDX) {
0d80a619 15674 enum bpf_reg_type src_reg_type;
9bac3d6d
AS
15675
15676 /* check for reserved fields is already done */
15677
17a52670 15678 /* check src operand */
dc503a8a 15679 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
15680 if (err)
15681 return err;
15682
dc503a8a 15683 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
15684 if (err)
15685 return err;
15686
725f9dcd
AS
15687 src_reg_type = regs[insn->src_reg].type;
15688
17a52670
AS
15689 /* check that memory (src_reg + off) is readable,
15690 * the state of dst_reg will be updated by this func
15691 */
c08435ec
DB
15692 err = check_mem_access(env, env->insn_idx, insn->src_reg,
15693 insn->off, BPF_SIZE(insn->code),
15694 BPF_READ, insn->dst_reg, false);
17a52670
AS
15695 if (err)
15696 return err;
15697
0d80a619
EZ
15698 err = save_aux_ptr_type(env, src_reg_type, true);
15699 if (err)
15700 return err;
17a52670 15701 } else if (class == BPF_STX) {
0d80a619 15702 enum bpf_reg_type dst_reg_type;
d691f9e8 15703
91c960b0
BJ
15704 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15705 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
15706 if (err)
15707 return err;
c08435ec 15708 env->insn_idx++;
17a52670
AS
15709 continue;
15710 }
15711
5ca419f2
BJ
15712 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15713 verbose(env, "BPF_STX uses reserved fields\n");
15714 return -EINVAL;
15715 }
15716
17a52670 15717 /* check src1 operand */
dc503a8a 15718 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
15719 if (err)
15720 return err;
15721 /* check src2 operand */
dc503a8a 15722 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
15723 if (err)
15724 return err;
15725
d691f9e8
AS
15726 dst_reg_type = regs[insn->dst_reg].type;
15727
17a52670 15728 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
15729 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15730 insn->off, BPF_SIZE(insn->code),
15731 BPF_WRITE, insn->src_reg, false);
17a52670
AS
15732 if (err)
15733 return err;
15734
0d80a619
EZ
15735 err = save_aux_ptr_type(env, dst_reg_type, false);
15736 if (err)
15737 return err;
17a52670 15738 } else if (class == BPF_ST) {
0d80a619
EZ
15739 enum bpf_reg_type dst_reg_type;
15740
17a52670
AS
15741 if (BPF_MODE(insn->code) != BPF_MEM ||
15742 insn->src_reg != BPF_REG_0) {
61bd5218 15743 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
15744 return -EINVAL;
15745 }
15746 /* check src operand */
dc503a8a 15747 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
15748 if (err)
15749 return err;
15750
0d80a619 15751 dst_reg_type = regs[insn->dst_reg].type;
f37a8cb8 15752
17a52670 15753 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
15754 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15755 insn->off, BPF_SIZE(insn->code),
15756 BPF_WRITE, -1, false);
17a52670
AS
15757 if (err)
15758 return err;
15759
0d80a619
EZ
15760 err = save_aux_ptr_type(env, dst_reg_type, false);
15761 if (err)
15762 return err;
092ed096 15763 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
15764 u8 opcode = BPF_OP(insn->code);
15765
2589726d 15766 env->jmps_processed++;
17a52670
AS
15767 if (opcode == BPF_CALL) {
15768 if (BPF_SRC(insn->code) != BPF_K ||
2357672c
KKD
15769 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15770 && insn->off != 0) ||
f4d7e40a 15771 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
15772 insn->src_reg != BPF_PSEUDO_CALL &&
15773 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
15774 insn->dst_reg != BPF_REG_0 ||
15775 class == BPF_JMP32) {
61bd5218 15776 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
15777 return -EINVAL;
15778 }
15779
8cab76ec
KKD
15780 if (env->cur_state->active_lock.ptr) {
15781 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15782 (insn->src_reg == BPF_PSEUDO_CALL) ||
15783 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
cd6791b4 15784 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
8cab76ec
KKD
15785 verbose(env, "function calls are not allowed while holding a lock\n");
15786 return -EINVAL;
15787 }
d83525ca 15788 }
f4d7e40a 15789 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 15790 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450 15791 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
5c073f26 15792 err = check_kfunc_call(env, insn, &env->insn_idx);
f4d7e40a 15793 else
69c087ba 15794 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
15795 if (err)
15796 return err;
553a64a8
AN
15797
15798 mark_reg_scratched(env, BPF_REG_0);
17a52670
AS
15799 } else if (opcode == BPF_JA) {
15800 if (BPF_SRC(insn->code) != BPF_K ||
15801 insn->imm != 0 ||
15802 insn->src_reg != BPF_REG_0 ||
092ed096
JW
15803 insn->dst_reg != BPF_REG_0 ||
15804 class == BPF_JMP32) {
61bd5218 15805 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
15806 return -EINVAL;
15807 }
15808
c08435ec 15809 env->insn_idx += insn->off + 1;
17a52670
AS
15810 continue;
15811
15812 } else if (opcode == BPF_EXIT) {
15813 if (BPF_SRC(insn->code) != BPF_K ||
15814 insn->imm != 0 ||
15815 insn->src_reg != BPF_REG_0 ||
092ed096
JW
15816 insn->dst_reg != BPF_REG_0 ||
15817 class == BPF_JMP32) {
61bd5218 15818 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
15819 return -EINVAL;
15820 }
15821
5d92ddc3
DM
15822 if (env->cur_state->active_lock.ptr &&
15823 !in_rbtree_lock_required_cb(env)) {
d83525ca
AS
15824 verbose(env, "bpf_spin_unlock is missing\n");
15825 return -EINVAL;
15826 }
15827
9bb00b28
YS
15828 if (env->cur_state->active_rcu_lock) {
15829 verbose(env, "bpf_rcu_read_unlock is missing\n");
15830 return -EINVAL;
15831 }
15832
9d9d00ac
KKD
15833 /* We must do check_reference_leak here before
15834 * prepare_func_exit to handle the case when
15835 * state->curframe > 0, it may be a callback
15836 * function, for which reference_state must
15837 * match caller reference state when it exits.
15838 */
15839 err = check_reference_leak(env);
15840 if (err)
15841 return err;
15842
f4d7e40a
AS
15843 if (state->curframe) {
15844 /* exit from nested function */
c08435ec 15845 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
15846 if (err)
15847 return err;
15848 do_print_state = true;
15849 continue;
15850 }
15851
390ee7e2
AS
15852 err = check_return_code(env);
15853 if (err)
15854 return err;
f1bca824 15855process_bpf_exit:
0f55f9ed 15856 mark_verifier_state_scratched(env);
2589726d 15857 update_branch_counts(env, env->cur_state);
b5dc0163 15858 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 15859 &env->insn_idx, pop_log);
638f5b90
AS
15860 if (err < 0) {
15861 if (err != -ENOENT)
15862 return err;
17a52670
AS
15863 break;
15864 } else {
15865 do_print_state = true;
15866 continue;
15867 }
15868 } else {
c08435ec 15869 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
15870 if (err)
15871 return err;
15872 }
15873 } else if (class == BPF_LD) {
15874 u8 mode = BPF_MODE(insn->code);
15875
15876 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
15877 err = check_ld_abs(env, insn);
15878 if (err)
15879 return err;
15880
17a52670
AS
15881 } else if (mode == BPF_IMM) {
15882 err = check_ld_imm(env, insn);
15883 if (err)
15884 return err;
15885
c08435ec 15886 env->insn_idx++;
fe9a5ca7 15887 sanitize_mark_insn_seen(env);
17a52670 15888 } else {
61bd5218 15889 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
15890 return -EINVAL;
15891 }
15892 } else {
61bd5218 15893 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
15894 return -EINVAL;
15895 }
15896
c08435ec 15897 env->insn_idx++;
17a52670
AS
15898 }
15899
15900 return 0;
15901}
15902
541c3bad
AN
15903static int find_btf_percpu_datasec(struct btf *btf)
15904{
15905 const struct btf_type *t;
15906 const char *tname;
15907 int i, n;
15908
15909 /*
15910 * Both vmlinux and module each have their own ".data..percpu"
15911 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15912 * types to look at only module's own BTF types.
15913 */
15914 n = btf_nr_types(btf);
15915 if (btf_is_module(btf))
15916 i = btf_nr_types(btf_vmlinux);
15917 else
15918 i = 1;
15919
15920 for(; i < n; i++) {
15921 t = btf_type_by_id(btf, i);
15922 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15923 continue;
15924
15925 tname = btf_name_by_offset(btf, t->name_off);
15926 if (!strcmp(tname, ".data..percpu"))
15927 return i;
15928 }
15929
15930 return -ENOENT;
15931}
15932
4976b718
HL
15933/* replace pseudo btf_id with kernel symbol address */
15934static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15935 struct bpf_insn *insn,
15936 struct bpf_insn_aux_data *aux)
15937{
eaa6bcb7
HL
15938 const struct btf_var_secinfo *vsi;
15939 const struct btf_type *datasec;
541c3bad 15940 struct btf_mod_pair *btf_mod;
4976b718
HL
15941 const struct btf_type *t;
15942 const char *sym_name;
eaa6bcb7 15943 bool percpu = false;
f16e6313 15944 u32 type, id = insn->imm;
541c3bad 15945 struct btf *btf;
f16e6313 15946 s32 datasec_id;
4976b718 15947 u64 addr;
541c3bad 15948 int i, btf_fd, err;
4976b718 15949
541c3bad
AN
15950 btf_fd = insn[1].imm;
15951 if (btf_fd) {
15952 btf = btf_get_by_fd(btf_fd);
15953 if (IS_ERR(btf)) {
15954 verbose(env, "invalid module BTF object FD specified.\n");
15955 return -EINVAL;
15956 }
15957 } else {
15958 if (!btf_vmlinux) {
15959 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15960 return -EINVAL;
15961 }
15962 btf = btf_vmlinux;
15963 btf_get(btf);
4976b718
HL
15964 }
15965
541c3bad 15966 t = btf_type_by_id(btf, id);
4976b718
HL
15967 if (!t) {
15968 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
15969 err = -ENOENT;
15970 goto err_put;
4976b718
HL
15971 }
15972
58aa2afb
AS
15973 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
15974 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
541c3bad
AN
15975 err = -EINVAL;
15976 goto err_put;
4976b718
HL
15977 }
15978
541c3bad 15979 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
15980 addr = kallsyms_lookup_name(sym_name);
15981 if (!addr) {
15982 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15983 sym_name);
541c3bad
AN
15984 err = -ENOENT;
15985 goto err_put;
4976b718 15986 }
58aa2afb
AS
15987 insn[0].imm = (u32)addr;
15988 insn[1].imm = addr >> 32;
15989
15990 if (btf_type_is_func(t)) {
15991 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15992 aux->btf_var.mem_size = 0;
15993 goto check_btf;
15994 }
4976b718 15995
541c3bad 15996 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 15997 if (datasec_id > 0) {
541c3bad 15998 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
15999 for_each_vsi(i, datasec, vsi) {
16000 if (vsi->type == id) {
16001 percpu = true;
16002 break;
16003 }
16004 }
16005 }
16006
4976b718 16007 type = t->type;
541c3bad 16008 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7 16009 if (percpu) {
5844101a 16010 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
541c3bad 16011 aux->btf_var.btf = btf;
eaa6bcb7
HL
16012 aux->btf_var.btf_id = type;
16013 } else if (!btf_type_is_struct(t)) {
4976b718
HL
16014 const struct btf_type *ret;
16015 const char *tname;
16016 u32 tsize;
16017
16018 /* resolve the type size of ksym. */
541c3bad 16019 ret = btf_resolve_size(btf, t, &tsize);
4976b718 16020 if (IS_ERR(ret)) {
541c3bad 16021 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
16022 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16023 tname, PTR_ERR(ret));
541c3bad
AN
16024 err = -EINVAL;
16025 goto err_put;
4976b718 16026 }
34d3a78c 16027 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
4976b718
HL
16028 aux->btf_var.mem_size = tsize;
16029 } else {
16030 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 16031 aux->btf_var.btf = btf;
4976b718
HL
16032 aux->btf_var.btf_id = type;
16033 }
58aa2afb 16034check_btf:
541c3bad
AN
16035 /* check whether we recorded this BTF (and maybe module) already */
16036 for (i = 0; i < env->used_btf_cnt; i++) {
16037 if (env->used_btfs[i].btf == btf) {
16038 btf_put(btf);
16039 return 0;
16040 }
16041 }
16042
16043 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16044 err = -E2BIG;
16045 goto err_put;
16046 }
16047
16048 btf_mod = &env->used_btfs[env->used_btf_cnt];
16049 btf_mod->btf = btf;
16050 btf_mod->module = NULL;
16051
16052 /* if we reference variables from kernel module, bump its refcount */
16053 if (btf_is_module(btf)) {
16054 btf_mod->module = btf_try_get_module(btf);
16055 if (!btf_mod->module) {
16056 err = -ENXIO;
16057 goto err_put;
16058 }
16059 }
16060
16061 env->used_btf_cnt++;
16062
4976b718 16063 return 0;
541c3bad
AN
16064err_put:
16065 btf_put(btf);
16066 return err;
4976b718
HL
16067}
16068
d83525ca
AS
16069static bool is_tracing_prog_type(enum bpf_prog_type type)
16070{
16071 switch (type) {
16072 case BPF_PROG_TYPE_KPROBE:
16073 case BPF_PROG_TYPE_TRACEPOINT:
16074 case BPF_PROG_TYPE_PERF_EVENT:
16075 case BPF_PROG_TYPE_RAW_TRACEPOINT:
5002615a 16076 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
d83525ca
AS
16077 return true;
16078 default:
16079 return false;
16080 }
16081}
16082
61bd5218
JK
16083static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16084 struct bpf_map *map,
fdc15d38
AS
16085 struct bpf_prog *prog)
16086
16087{
7e40781c 16088 enum bpf_prog_type prog_type = resolve_prog_type(prog);
a3884572 16089
9c395c1b
DM
16090 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16091 btf_record_has_field(map->record, BPF_RB_ROOT)) {
f0c5941f 16092 if (is_tracing_prog_type(prog_type)) {
9c395c1b 16093 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
f0c5941f
KKD
16094 return -EINVAL;
16095 }
16096 }
16097
db559117 16098 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
9e7a4d98
KS
16099 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16100 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16101 return -EINVAL;
16102 }
16103
16104 if (is_tracing_prog_type(prog_type)) {
16105 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16106 return -EINVAL;
16107 }
16108
16109 if (prog->aux->sleepable) {
16110 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16111 return -EINVAL;
16112 }
d83525ca
AS
16113 }
16114
db559117 16115 if (btf_record_has_field(map->record, BPF_TIMER)) {
5e0bc308
DB
16116 if (is_tracing_prog_type(prog_type)) {
16117 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16118 return -EINVAL;
16119 }
16120 }
16121
9d03ebc7 16122 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
09728266 16123 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
16124 verbose(env, "offload device mismatch between prog and map\n");
16125 return -EINVAL;
16126 }
16127
85d33df3
MKL
16128 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16129 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16130 return -EINVAL;
16131 }
16132
1e6c62a8
AS
16133 if (prog->aux->sleepable)
16134 switch (map->map_type) {
16135 case BPF_MAP_TYPE_HASH:
16136 case BPF_MAP_TYPE_LRU_HASH:
16137 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
16138 case BPF_MAP_TYPE_PERCPU_HASH:
16139 case BPF_MAP_TYPE_PERCPU_ARRAY:
16140 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16141 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16142 case BPF_MAP_TYPE_HASH_OF_MAPS:
ba90c2cc 16143 case BPF_MAP_TYPE_RINGBUF:
583c1f42 16144 case BPF_MAP_TYPE_USER_RINGBUF:
0fe4b381
KS
16145 case BPF_MAP_TYPE_INODE_STORAGE:
16146 case BPF_MAP_TYPE_SK_STORAGE:
16147 case BPF_MAP_TYPE_TASK_STORAGE:
2c40d97d 16148 case BPF_MAP_TYPE_CGRP_STORAGE:
ba90c2cc 16149 break;
1e6c62a8
AS
16150 default:
16151 verbose(env,
2c40d97d 16152 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
1e6c62a8
AS
16153 return -EINVAL;
16154 }
16155
fdc15d38
AS
16156 return 0;
16157}
16158
b741f163
RG
16159static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16160{
16161 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16162 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16163}
16164
4976b718
HL
16165/* find and rewrite pseudo imm in ld_imm64 instructions:
16166 *
16167 * 1. if it accesses map FD, replace it with actual map pointer.
16168 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16169 *
16170 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 16171 */
4976b718 16172static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
16173{
16174 struct bpf_insn *insn = env->prog->insnsi;
16175 int insn_cnt = env->prog->len;
fdc15d38 16176 int i, j, err;
0246e64d 16177
f1f7714e 16178 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
16179 if (err)
16180 return err;
16181
0246e64d 16182 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 16183 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 16184 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 16185 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
16186 return -EINVAL;
16187 }
16188
0246e64d 16189 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 16190 struct bpf_insn_aux_data *aux;
0246e64d
AS
16191 struct bpf_map *map;
16192 struct fd f;
d8eca5bb 16193 u64 addr;
387544bf 16194 u32 fd;
0246e64d
AS
16195
16196 if (i == insn_cnt - 1 || insn[1].code != 0 ||
16197 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16198 insn[1].off != 0) {
61bd5218 16199 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
16200 return -EINVAL;
16201 }
16202
d8eca5bb 16203 if (insn[0].src_reg == 0)
0246e64d
AS
16204 /* valid generic load 64-bit imm */
16205 goto next_insn;
16206
4976b718
HL
16207 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16208 aux = &env->insn_aux_data[i];
16209 err = check_pseudo_btf_id(env, insn, aux);
16210 if (err)
16211 return err;
16212 goto next_insn;
16213 }
16214
69c087ba
YS
16215 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16216 aux = &env->insn_aux_data[i];
16217 aux->ptr_type = PTR_TO_FUNC;
16218 goto next_insn;
16219 }
16220
d8eca5bb
DB
16221 /* In final convert_pseudo_ld_imm64() step, this is
16222 * converted into regular 64-bit imm load insn.
16223 */
387544bf
AS
16224 switch (insn[0].src_reg) {
16225 case BPF_PSEUDO_MAP_VALUE:
16226 case BPF_PSEUDO_MAP_IDX_VALUE:
16227 break;
16228 case BPF_PSEUDO_MAP_FD:
16229 case BPF_PSEUDO_MAP_IDX:
16230 if (insn[1].imm == 0)
16231 break;
16232 fallthrough;
16233 default:
16234 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
16235 return -EINVAL;
16236 }
16237
387544bf
AS
16238 switch (insn[0].src_reg) {
16239 case BPF_PSEUDO_MAP_IDX_VALUE:
16240 case BPF_PSEUDO_MAP_IDX:
16241 if (bpfptr_is_null(env->fd_array)) {
16242 verbose(env, "fd_idx without fd_array is invalid\n");
16243 return -EPROTO;
16244 }
16245 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16246 insn[0].imm * sizeof(fd),
16247 sizeof(fd)))
16248 return -EFAULT;
16249 break;
16250 default:
16251 fd = insn[0].imm;
16252 break;
16253 }
16254
16255 f = fdget(fd);
c2101297 16256 map = __bpf_map_get(f);
0246e64d 16257 if (IS_ERR(map)) {
61bd5218 16258 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 16259 insn[0].imm);
0246e64d
AS
16260 return PTR_ERR(map);
16261 }
16262
61bd5218 16263 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
16264 if (err) {
16265 fdput(f);
16266 return err;
16267 }
16268
d8eca5bb 16269 aux = &env->insn_aux_data[i];
387544bf
AS
16270 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16271 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
d8eca5bb
DB
16272 addr = (unsigned long)map;
16273 } else {
16274 u32 off = insn[1].imm;
16275
16276 if (off >= BPF_MAX_VAR_OFF) {
16277 verbose(env, "direct value offset of %u is not allowed\n", off);
16278 fdput(f);
16279 return -EINVAL;
16280 }
16281
16282 if (!map->ops->map_direct_value_addr) {
16283 verbose(env, "no direct value access support for this map type\n");
16284 fdput(f);
16285 return -EINVAL;
16286 }
16287
16288 err = map->ops->map_direct_value_addr(map, &addr, off);
16289 if (err) {
16290 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16291 map->value_size, off);
16292 fdput(f);
16293 return err;
16294 }
16295
16296 aux->map_off = off;
16297 addr += off;
16298 }
16299
16300 insn[0].imm = (u32)addr;
16301 insn[1].imm = addr >> 32;
0246e64d
AS
16302
16303 /* check whether we recorded this map already */
d8eca5bb 16304 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 16305 if (env->used_maps[j] == map) {
d8eca5bb 16306 aux->map_index = j;
0246e64d
AS
16307 fdput(f);
16308 goto next_insn;
16309 }
d8eca5bb 16310 }
0246e64d
AS
16311
16312 if (env->used_map_cnt >= MAX_USED_MAPS) {
16313 fdput(f);
16314 return -E2BIG;
16315 }
16316
0246e64d
AS
16317 /* hold the map. If the program is rejected by verifier,
16318 * the map will be released by release_maps() or it
16319 * will be used by the valid program until it's unloaded
ab7f5bf0 16320 * and all maps are released in free_used_maps()
0246e64d 16321 */
1e0bd5a0 16322 bpf_map_inc(map);
d8eca5bb
DB
16323
16324 aux->map_index = env->used_map_cnt;
92117d84
AS
16325 env->used_maps[env->used_map_cnt++] = map;
16326
b741f163 16327 if (bpf_map_is_cgroup_storage(map) &&
e4730423 16328 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 16329 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
16330 fdput(f);
16331 return -EBUSY;
16332 }
16333
0246e64d
AS
16334 fdput(f);
16335next_insn:
16336 insn++;
16337 i++;
5e581dad
DB
16338 continue;
16339 }
16340
16341 /* Basic sanity check before we invest more work here. */
16342 if (!bpf_opcode_in_insntable(insn->code)) {
16343 verbose(env, "unknown opcode %02x\n", insn->code);
16344 return -EINVAL;
0246e64d
AS
16345 }
16346 }
16347
16348 /* now all pseudo BPF_LD_IMM64 instructions load valid
16349 * 'struct bpf_map *' into a register instead of user map_fd.
16350 * These pointers will be used later by verifier to validate map access.
16351 */
16352 return 0;
16353}
16354
16355/* drop refcnt of maps used by the rejected program */
58e2af8b 16356static void release_maps(struct bpf_verifier_env *env)
0246e64d 16357{
a2ea0746
DB
16358 __bpf_free_used_maps(env->prog->aux, env->used_maps,
16359 env->used_map_cnt);
0246e64d
AS
16360}
16361
541c3bad
AN
16362/* drop refcnt of maps used by the rejected program */
16363static void release_btfs(struct bpf_verifier_env *env)
16364{
16365 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16366 env->used_btf_cnt);
16367}
16368
0246e64d 16369/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 16370static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
16371{
16372 struct bpf_insn *insn = env->prog->insnsi;
16373 int insn_cnt = env->prog->len;
16374 int i;
16375
69c087ba
YS
16376 for (i = 0; i < insn_cnt; i++, insn++) {
16377 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16378 continue;
16379 if (insn->src_reg == BPF_PSEUDO_FUNC)
16380 continue;
16381 insn->src_reg = 0;
16382 }
0246e64d
AS
16383}
16384
8041902d
AS
16385/* single env->prog->insni[off] instruction was replaced with the range
16386 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
16387 * [0, off) and [off, end) to new locations, so the patched range stays zero
16388 */
75f0fc7b
HF
16389static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16390 struct bpf_insn_aux_data *new_data,
16391 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d 16392{
75f0fc7b 16393 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
b325fbca 16394 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 16395 u32 old_seen = old_data[off].seen;
b325fbca 16396 u32 prog_len;
c131187d 16397 int i;
8041902d 16398
b325fbca
JW
16399 /* aux info at OFF always needs adjustment, no matter fast path
16400 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16401 * original insn at old prog.
16402 */
16403 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16404
8041902d 16405 if (cnt == 1)
75f0fc7b 16406 return;
b325fbca 16407 prog_len = new_prog->len;
75f0fc7b 16408
8041902d
AS
16409 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16410 memcpy(new_data + off + cnt - 1, old_data + off,
16411 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 16412 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
16413 /* Expand insni[off]'s seen count to the patched range. */
16414 new_data[i].seen = old_seen;
b325fbca
JW
16415 new_data[i].zext_dst = insn_has_def32(env, insn + i);
16416 }
8041902d
AS
16417 env->insn_aux_data = new_data;
16418 vfree(old_data);
8041902d
AS
16419}
16420
cc8b0b92
AS
16421static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16422{
16423 int i;
16424
16425 if (len == 1)
16426 return;
4cb3d99c
JW
16427 /* NOTE: fake 'exit' subprog should be updated as well. */
16428 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 16429 if (env->subprog_info[i].start <= off)
cc8b0b92 16430 continue;
9c8105bd 16431 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
16432 }
16433}
16434
7506d211 16435static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
a748c697
MF
16436{
16437 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16438 int i, sz = prog->aux->size_poke_tab;
16439 struct bpf_jit_poke_descriptor *desc;
16440
16441 for (i = 0; i < sz; i++) {
16442 desc = &tab[i];
7506d211
JF
16443 if (desc->insn_idx <= off)
16444 continue;
a748c697
MF
16445 desc->insn_idx += len - 1;
16446 }
16447}
16448
8041902d
AS
16449static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16450 const struct bpf_insn *patch, u32 len)
16451{
16452 struct bpf_prog *new_prog;
75f0fc7b
HF
16453 struct bpf_insn_aux_data *new_data = NULL;
16454
16455 if (len > 1) {
16456 new_data = vzalloc(array_size(env->prog->len + len - 1,
16457 sizeof(struct bpf_insn_aux_data)));
16458 if (!new_data)
16459 return NULL;
16460 }
8041902d
AS
16461
16462 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
16463 if (IS_ERR(new_prog)) {
16464 if (PTR_ERR(new_prog) == -ERANGE)
16465 verbose(env,
16466 "insn %d cannot be patched due to 16-bit range\n",
16467 env->insn_aux_data[off].orig_idx);
75f0fc7b 16468 vfree(new_data);
8041902d 16469 return NULL;
4f73379e 16470 }
75f0fc7b 16471 adjust_insn_aux_data(env, new_data, new_prog, off, len);
cc8b0b92 16472 adjust_subprog_starts(env, off, len);
7506d211 16473 adjust_poke_descs(new_prog, off, len);
8041902d
AS
16474 return new_prog;
16475}
16476
52875a04
JK
16477static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16478 u32 off, u32 cnt)
16479{
16480 int i, j;
16481
16482 /* find first prog starting at or after off (first to remove) */
16483 for (i = 0; i < env->subprog_cnt; i++)
16484 if (env->subprog_info[i].start >= off)
16485 break;
16486 /* find first prog starting at or after off + cnt (first to stay) */
16487 for (j = i; j < env->subprog_cnt; j++)
16488 if (env->subprog_info[j].start >= off + cnt)
16489 break;
16490 /* if j doesn't start exactly at off + cnt, we are just removing
16491 * the front of previous prog
16492 */
16493 if (env->subprog_info[j].start != off + cnt)
16494 j--;
16495
16496 if (j > i) {
16497 struct bpf_prog_aux *aux = env->prog->aux;
16498 int move;
16499
16500 /* move fake 'exit' subprog as well */
16501 move = env->subprog_cnt + 1 - j;
16502
16503 memmove(env->subprog_info + i,
16504 env->subprog_info + j,
16505 sizeof(*env->subprog_info) * move);
16506 env->subprog_cnt -= j - i;
16507
16508 /* remove func_info */
16509 if (aux->func_info) {
16510 move = aux->func_info_cnt - j;
16511
16512 memmove(aux->func_info + i,
16513 aux->func_info + j,
16514 sizeof(*aux->func_info) * move);
16515 aux->func_info_cnt -= j - i;
16516 /* func_info->insn_off is set after all code rewrites,
16517 * in adjust_btf_func() - no need to adjust
16518 */
16519 }
16520 } else {
16521 /* convert i from "first prog to remove" to "first to adjust" */
16522 if (env->subprog_info[i].start == off)
16523 i++;
16524 }
16525
16526 /* update fake 'exit' subprog as well */
16527 for (; i <= env->subprog_cnt; i++)
16528 env->subprog_info[i].start -= cnt;
16529
16530 return 0;
16531}
16532
16533static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16534 u32 cnt)
16535{
16536 struct bpf_prog *prog = env->prog;
16537 u32 i, l_off, l_cnt, nr_linfo;
16538 struct bpf_line_info *linfo;
16539
16540 nr_linfo = prog->aux->nr_linfo;
16541 if (!nr_linfo)
16542 return 0;
16543
16544 linfo = prog->aux->linfo;
16545
16546 /* find first line info to remove, count lines to be removed */
16547 for (i = 0; i < nr_linfo; i++)
16548 if (linfo[i].insn_off >= off)
16549 break;
16550
16551 l_off = i;
16552 l_cnt = 0;
16553 for (; i < nr_linfo; i++)
16554 if (linfo[i].insn_off < off + cnt)
16555 l_cnt++;
16556 else
16557 break;
16558
16559 /* First live insn doesn't match first live linfo, it needs to "inherit"
16560 * last removed linfo. prog is already modified, so prog->len == off
16561 * means no live instructions after (tail of the program was removed).
16562 */
16563 if (prog->len != off && l_cnt &&
16564 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16565 l_cnt--;
16566 linfo[--i].insn_off = off + cnt;
16567 }
16568
16569 /* remove the line info which refer to the removed instructions */
16570 if (l_cnt) {
16571 memmove(linfo + l_off, linfo + i,
16572 sizeof(*linfo) * (nr_linfo - i));
16573
16574 prog->aux->nr_linfo -= l_cnt;
16575 nr_linfo = prog->aux->nr_linfo;
16576 }
16577
16578 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
16579 for (i = l_off; i < nr_linfo; i++)
16580 linfo[i].insn_off -= cnt;
16581
16582 /* fix up all subprogs (incl. 'exit') which start >= off */
16583 for (i = 0; i <= env->subprog_cnt; i++)
16584 if (env->subprog_info[i].linfo_idx > l_off) {
16585 /* program may have started in the removed region but
16586 * may not be fully removed
16587 */
16588 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
16589 env->subprog_info[i].linfo_idx -= l_cnt;
16590 else
16591 env->subprog_info[i].linfo_idx = l_off;
16592 }
16593
16594 return 0;
16595}
16596
16597static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
16598{
16599 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16600 unsigned int orig_prog_len = env->prog->len;
16601 int err;
16602
9d03ebc7 16603 if (bpf_prog_is_offloaded(env->prog->aux))
08ca90af
JK
16604 bpf_prog_offload_remove_insns(env, off, cnt);
16605
52875a04
JK
16606 err = bpf_remove_insns(env->prog, off, cnt);
16607 if (err)
16608 return err;
16609
16610 err = adjust_subprog_starts_after_remove(env, off, cnt);
16611 if (err)
16612 return err;
16613
16614 err = bpf_adj_linfo_after_remove(env, off, cnt);
16615 if (err)
16616 return err;
16617
16618 memmove(aux_data + off, aux_data + off + cnt,
16619 sizeof(*aux_data) * (orig_prog_len - off - cnt));
16620
16621 return 0;
16622}
16623
2a5418a1
DB
16624/* The verifier does more data flow analysis than llvm and will not
16625 * explore branches that are dead at run time. Malicious programs can
16626 * have dead code too. Therefore replace all dead at-run-time code
16627 * with 'ja -1'.
16628 *
16629 * Just nops are not optimal, e.g. if they would sit at the end of the
16630 * program and through another bug we would manage to jump there, then
16631 * we'd execute beyond program memory otherwise. Returning exception
16632 * code also wouldn't work since we can have subprogs where the dead
16633 * code could be located.
c131187d
AS
16634 */
16635static void sanitize_dead_code(struct bpf_verifier_env *env)
16636{
16637 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 16638 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
16639 struct bpf_insn *insn = env->prog->insnsi;
16640 const int insn_cnt = env->prog->len;
16641 int i;
16642
16643 for (i = 0; i < insn_cnt; i++) {
16644 if (aux_data[i].seen)
16645 continue;
2a5418a1 16646 memcpy(insn + i, &trap, sizeof(trap));
45c709f8 16647 aux_data[i].zext_dst = false;
c131187d
AS
16648 }
16649}
16650
e2ae4ca2
JK
16651static bool insn_is_cond_jump(u8 code)
16652{
16653 u8 op;
16654
092ed096
JW
16655 if (BPF_CLASS(code) == BPF_JMP32)
16656 return true;
16657
e2ae4ca2
JK
16658 if (BPF_CLASS(code) != BPF_JMP)
16659 return false;
16660
16661 op = BPF_OP(code);
16662 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
16663}
16664
16665static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
16666{
16667 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16668 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16669 struct bpf_insn *insn = env->prog->insnsi;
16670 const int insn_cnt = env->prog->len;
16671 int i;
16672
16673 for (i = 0; i < insn_cnt; i++, insn++) {
16674 if (!insn_is_cond_jump(insn->code))
16675 continue;
16676
16677 if (!aux_data[i + 1].seen)
16678 ja.off = insn->off;
16679 else if (!aux_data[i + 1 + insn->off].seen)
16680 ja.off = 0;
16681 else
16682 continue;
16683
9d03ebc7 16684 if (bpf_prog_is_offloaded(env->prog->aux))
08ca90af
JK
16685 bpf_prog_offload_replace_insn(env, i, &ja);
16686
e2ae4ca2
JK
16687 memcpy(insn, &ja, sizeof(ja));
16688 }
16689}
16690
52875a04
JK
16691static int opt_remove_dead_code(struct bpf_verifier_env *env)
16692{
16693 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16694 int insn_cnt = env->prog->len;
16695 int i, err;
16696
16697 for (i = 0; i < insn_cnt; i++) {
16698 int j;
16699
16700 j = 0;
16701 while (i + j < insn_cnt && !aux_data[i + j].seen)
16702 j++;
16703 if (!j)
16704 continue;
16705
16706 err = verifier_remove_insns(env, i, j);
16707 if (err)
16708 return err;
16709 insn_cnt = env->prog->len;
16710 }
16711
16712 return 0;
16713}
16714
a1b14abc
JK
16715static int opt_remove_nops(struct bpf_verifier_env *env)
16716{
16717 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16718 struct bpf_insn *insn = env->prog->insnsi;
16719 int insn_cnt = env->prog->len;
16720 int i, err;
16721
16722 for (i = 0; i < insn_cnt; i++) {
16723 if (memcmp(&insn[i], &ja, sizeof(ja)))
16724 continue;
16725
16726 err = verifier_remove_insns(env, i, 1);
16727 if (err)
16728 return err;
16729 insn_cnt--;
16730 i--;
16731 }
16732
16733 return 0;
16734}
16735
d6c2308c
JW
16736static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16737 const union bpf_attr *attr)
a4b1d3c1 16738{
d6c2308c 16739 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 16740 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 16741 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 16742 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 16743 struct bpf_prog *new_prog;
d6c2308c 16744 bool rnd_hi32;
a4b1d3c1 16745
d6c2308c 16746 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 16747 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
16748 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16749 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16750 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
16751 for (i = 0; i < len; i++) {
16752 int adj_idx = i + delta;
16753 struct bpf_insn insn;
83a28819 16754 int load_reg;
a4b1d3c1 16755
d6c2308c 16756 insn = insns[adj_idx];
83a28819 16757 load_reg = insn_def_regno(&insn);
d6c2308c
JW
16758 if (!aux[adj_idx].zext_dst) {
16759 u8 code, class;
16760 u32 imm_rnd;
16761
16762 if (!rnd_hi32)
16763 continue;
16764
16765 code = insn.code;
16766 class = BPF_CLASS(code);
83a28819 16767 if (load_reg == -1)
d6c2308c
JW
16768 continue;
16769
16770 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
16771 * BPF_STX + SRC_OP, so it is safe to pass NULL
16772 * here.
d6c2308c 16773 */
83a28819 16774 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
16775 if (class == BPF_LD &&
16776 BPF_MODE(code) == BPF_IMM)
16777 i++;
16778 continue;
16779 }
16780
16781 /* ctx load could be transformed into wider load. */
16782 if (class == BPF_LDX &&
16783 aux[adj_idx].ptr_type == PTR_TO_CTX)
16784 continue;
16785
a251c17a 16786 imm_rnd = get_random_u32();
d6c2308c
JW
16787 rnd_hi32_patch[0] = insn;
16788 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 16789 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
16790 patch = rnd_hi32_patch;
16791 patch_len = 4;
16792 goto apply_patch_buffer;
16793 }
16794
39491867
BJ
16795 /* Add in an zero-extend instruction if a) the JIT has requested
16796 * it or b) it's a CMPXCHG.
16797 *
16798 * The latter is because: BPF_CMPXCHG always loads a value into
16799 * R0, therefore always zero-extends. However some archs'
16800 * equivalent instruction only does this load when the
16801 * comparison is successful. This detail of CMPXCHG is
16802 * orthogonal to the general zero-extension behaviour of the
16803 * CPU, so it's treated independently of bpf_jit_needs_zext.
16804 */
16805 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
16806 continue;
16807
d35af0a7
BT
16808 /* Zero-extension is done by the caller. */
16809 if (bpf_pseudo_kfunc_call(&insn))
16810 continue;
16811
83a28819
IL
16812 if (WARN_ON(load_reg == -1)) {
16813 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16814 return -EFAULT;
b2e37a71
IL
16815 }
16816
a4b1d3c1 16817 zext_patch[0] = insn;
b2e37a71
IL
16818 zext_patch[1].dst_reg = load_reg;
16819 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
16820 patch = zext_patch;
16821 patch_len = 2;
16822apply_patch_buffer:
16823 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
16824 if (!new_prog)
16825 return -ENOMEM;
16826 env->prog = new_prog;
16827 insns = new_prog->insnsi;
16828 aux = env->insn_aux_data;
d6c2308c 16829 delta += patch_len - 1;
a4b1d3c1
JW
16830 }
16831
16832 return 0;
16833}
16834
c64b7983
JS
16835/* convert load instructions that access fields of a context type into a
16836 * sequence of instructions that access fields of the underlying structure:
16837 * struct __sk_buff -> struct sk_buff
16838 * struct bpf_sock_ops -> struct sock
9bac3d6d 16839 */
58e2af8b 16840static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 16841{
00176a34 16842 const struct bpf_verifier_ops *ops = env->ops;
f96da094 16843 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 16844 const int insn_cnt = env->prog->len;
36bbef52 16845 struct bpf_insn insn_buf[16], *insn;
46f53a65 16846 u32 target_size, size_default, off;
9bac3d6d 16847 struct bpf_prog *new_prog;
d691f9e8 16848 enum bpf_access_type type;
f96da094 16849 bool is_narrower_load;
9bac3d6d 16850
b09928b9
DB
16851 if (ops->gen_prologue || env->seen_direct_write) {
16852 if (!ops->gen_prologue) {
16853 verbose(env, "bpf verifier is misconfigured\n");
16854 return -EINVAL;
16855 }
36bbef52
DB
16856 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16857 env->prog);
16858 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 16859 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
16860 return -EINVAL;
16861 } else if (cnt) {
8041902d 16862 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
16863 if (!new_prog)
16864 return -ENOMEM;
8041902d 16865
36bbef52 16866 env->prog = new_prog;
3df126f3 16867 delta += cnt - 1;
36bbef52
DB
16868 }
16869 }
16870
9d03ebc7 16871 if (bpf_prog_is_offloaded(env->prog->aux))
9bac3d6d
AS
16872 return 0;
16873
3df126f3 16874 insn = env->prog->insnsi + delta;
36bbef52 16875
9bac3d6d 16876 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
16877 bpf_convert_ctx_access_t convert_ctx_access;
16878
62c7989b
DB
16879 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16880 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16881 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
2039f26f 16882 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
d691f9e8 16883 type = BPF_READ;
2039f26f
DB
16884 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16885 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16886 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16887 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16888 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16889 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16890 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16891 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
d691f9e8 16892 type = BPF_WRITE;
2039f26f 16893 } else {
9bac3d6d 16894 continue;
2039f26f 16895 }
9bac3d6d 16896
af86ca4e 16897 if (type == BPF_WRITE &&
2039f26f 16898 env->insn_aux_data[i + delta].sanitize_stack_spill) {
af86ca4e 16899 struct bpf_insn patch[] = {
af86ca4e 16900 *insn,
2039f26f 16901 BPF_ST_NOSPEC(),
af86ca4e
AS
16902 };
16903
16904 cnt = ARRAY_SIZE(patch);
16905 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16906 if (!new_prog)
16907 return -ENOMEM;
16908
16909 delta += cnt - 1;
16910 env->prog = new_prog;
16911 insn = new_prog->insnsi + i + delta;
16912 continue;
16913 }
16914
6efe152d 16915 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
c64b7983
JS
16916 case PTR_TO_CTX:
16917 if (!ops->convert_ctx_access)
16918 continue;
16919 convert_ctx_access = ops->convert_ctx_access;
16920 break;
16921 case PTR_TO_SOCKET:
46f8bc92 16922 case PTR_TO_SOCK_COMMON:
c64b7983
JS
16923 convert_ctx_access = bpf_sock_convert_ctx_access;
16924 break;
655a51e5
MKL
16925 case PTR_TO_TCP_SOCK:
16926 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16927 break;
fada7fdc
JL
16928 case PTR_TO_XDP_SOCK:
16929 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16930 break;
2a02759e 16931 case PTR_TO_BTF_ID:
6efe152d 16932 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
282de143
KKD
16933 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16934 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16935 * be said once it is marked PTR_UNTRUSTED, hence we must handle
16936 * any faults for loads into such types. BPF_WRITE is disallowed
16937 * for this case.
16938 */
16939 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
27ae7997
MKL
16940 if (type == BPF_READ) {
16941 insn->code = BPF_LDX | BPF_PROBE_MEM |
16942 BPF_SIZE((insn)->code);
16943 env->prog->aux->num_exentries++;
2a02759e 16944 }
2a02759e 16945 continue;
c64b7983 16946 default:
9bac3d6d 16947 continue;
c64b7983 16948 }
9bac3d6d 16949
31fd8581 16950 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 16951 size = BPF_LDST_BYTES(insn);
31fd8581
YS
16952
16953 /* If the read access is a narrower load of the field,
16954 * convert to a 4/8-byte load, to minimum program type specific
16955 * convert_ctx_access changes. If conversion is successful,
16956 * we will apply proper mask to the result.
16957 */
f96da094 16958 is_narrower_load = size < ctx_field_size;
46f53a65
AI
16959 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16960 off = insn->off;
31fd8581 16961 if (is_narrower_load) {
f96da094
DB
16962 u8 size_code;
16963
16964 if (type == BPF_WRITE) {
61bd5218 16965 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
16966 return -EINVAL;
16967 }
31fd8581 16968
f96da094 16969 size_code = BPF_H;
31fd8581
YS
16970 if (ctx_field_size == 4)
16971 size_code = BPF_W;
16972 else if (ctx_field_size == 8)
16973 size_code = BPF_DW;
f96da094 16974
bc23105c 16975 insn->off = off & ~(size_default - 1);
31fd8581
YS
16976 insn->code = BPF_LDX | BPF_MEM | size_code;
16977 }
f96da094
DB
16978
16979 target_size = 0;
c64b7983
JS
16980 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16981 &target_size);
f96da094
DB
16982 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16983 (ctx_field_size && !target_size)) {
61bd5218 16984 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
16985 return -EINVAL;
16986 }
f96da094
DB
16987
16988 if (is_narrower_load && size < target_size) {
d895a0f1
IL
16989 u8 shift = bpf_ctx_narrow_access_offset(
16990 off, size, size_default) * 8;
d7af7e49
AI
16991 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16992 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
16993 return -EINVAL;
16994 }
46f53a65
AI
16995 if (ctx_field_size <= 4) {
16996 if (shift)
16997 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
16998 insn->dst_reg,
16999 shift);
31fd8581 17000 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 17001 (1 << size * 8) - 1);
46f53a65
AI
17002 } else {
17003 if (shift)
17004 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17005 insn->dst_reg,
17006 shift);
31fd8581 17007 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 17008 (1ULL << size * 8) - 1);
46f53a65 17009 }
31fd8581 17010 }
9bac3d6d 17011
8041902d 17012 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
17013 if (!new_prog)
17014 return -ENOMEM;
17015
3df126f3 17016 delta += cnt - 1;
9bac3d6d
AS
17017
17018 /* keep walking new program and skip insns we just inserted */
17019 env->prog = new_prog;
3df126f3 17020 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
17021 }
17022
17023 return 0;
17024}
17025
1c2a088a
AS
17026static int jit_subprogs(struct bpf_verifier_env *env)
17027{
17028 struct bpf_prog *prog = env->prog, **func, *tmp;
17029 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 17030 struct bpf_map *map_ptr;
7105e828 17031 struct bpf_insn *insn;
1c2a088a 17032 void *old_bpf_func;
c4c0bdc0 17033 int err, num_exentries;
1c2a088a 17034
f910cefa 17035 if (env->subprog_cnt <= 1)
1c2a088a
AS
17036 return 0;
17037
7105e828 17038 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
3990ed4c 17039 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
69c087ba 17040 continue;
69c087ba 17041
c7a89784
DB
17042 /* Upon error here we cannot fall back to interpreter but
17043 * need a hard reject of the program. Thus -EFAULT is
17044 * propagated in any case.
17045 */
1c2a088a
AS
17046 subprog = find_subprog(env, i + insn->imm + 1);
17047 if (subprog < 0) {
17048 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17049 i + insn->imm + 1);
17050 return -EFAULT;
17051 }
17052 /* temporarily remember subprog id inside insn instead of
17053 * aux_data, since next loop will split up all insns into funcs
17054 */
f910cefa 17055 insn->off = subprog;
1c2a088a
AS
17056 /* remember original imm in case JIT fails and fallback
17057 * to interpreter will be needed
17058 */
17059 env->insn_aux_data[i].call_imm = insn->imm;
17060 /* point imm to __bpf_call_base+1 from JITs point of view */
17061 insn->imm = 1;
3990ed4c
MKL
17062 if (bpf_pseudo_func(insn))
17063 /* jit (e.g. x86_64) may emit fewer instructions
17064 * if it learns a u32 imm is the same as a u64 imm.
17065 * Force a non zero here.
17066 */
17067 insn[1].imm = 1;
1c2a088a
AS
17068 }
17069
c454a46b
MKL
17070 err = bpf_prog_alloc_jited_linfo(prog);
17071 if (err)
17072 goto out_undo_insn;
17073
17074 err = -ENOMEM;
6396bb22 17075 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 17076 if (!func)
c7a89784 17077 goto out_undo_insn;
1c2a088a 17078
f910cefa 17079 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 17080 subprog_start = subprog_end;
4cb3d99c 17081 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
17082
17083 len = subprog_end - subprog_start;
fb7dd8bc 17084 /* bpf_prog_run() doesn't call subprogs directly,
492ecee8
AS
17085 * hence main prog stats include the runtime of subprogs.
17086 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 17087 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
17088 */
17089 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
17090 if (!func[i])
17091 goto out_free;
17092 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17093 len * sizeof(struct bpf_insn));
4f74d809 17094 func[i]->type = prog->type;
1c2a088a 17095 func[i]->len = len;
4f74d809
DB
17096 if (bpf_prog_calc_tag(func[i]))
17097 goto out_free;
1c2a088a 17098 func[i]->is_func = 1;
ba64e7d8 17099 func[i]->aux->func_idx = i;
f263a814 17100 /* Below members will be freed only at prog->aux */
ba64e7d8
YS
17101 func[i]->aux->btf = prog->aux->btf;
17102 func[i]->aux->func_info = prog->aux->func_info;
9c7c48d6 17103 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
f263a814
JF
17104 func[i]->aux->poke_tab = prog->aux->poke_tab;
17105 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
ba64e7d8 17106
a748c697 17107 for (j = 0; j < prog->aux->size_poke_tab; j++) {
f263a814 17108 struct bpf_jit_poke_descriptor *poke;
a748c697 17109
f263a814
JF
17110 poke = &prog->aux->poke_tab[j];
17111 if (poke->insn_idx < subprog_end &&
17112 poke->insn_idx >= subprog_start)
17113 poke->aux = func[i]->aux;
a748c697
MF
17114 }
17115
1c2a088a 17116 func[i]->aux->name[0] = 'F';
9c8105bd 17117 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 17118 func[i]->jit_requested = 1;
d2a3b7c5 17119 func[i]->blinding_requested = prog->blinding_requested;
e6ac2450 17120 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
2357672c 17121 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
c454a46b
MKL
17122 func[i]->aux->linfo = prog->aux->linfo;
17123 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17124 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17125 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
17126 num_exentries = 0;
17127 insn = func[i]->insnsi;
17128 for (j = 0; j < func[i]->len; j++, insn++) {
17129 if (BPF_CLASS(insn->code) == BPF_LDX &&
17130 BPF_MODE(insn->code) == BPF_PROBE_MEM)
17131 num_exentries++;
17132 }
17133 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 17134 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
17135 func[i] = bpf_int_jit_compile(func[i]);
17136 if (!func[i]->jited) {
17137 err = -ENOTSUPP;
17138 goto out_free;
17139 }
17140 cond_resched();
17141 }
a748c697 17142
1c2a088a
AS
17143 /* at this point all bpf functions were successfully JITed
17144 * now populate all bpf_calls with correct addresses and
17145 * run last pass of JIT
17146 */
f910cefa 17147 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
17148 insn = func[i]->insnsi;
17149 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba 17150 if (bpf_pseudo_func(insn)) {
3990ed4c 17151 subprog = insn->off;
69c087ba
YS
17152 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17153 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17154 continue;
17155 }
23a2d70c 17156 if (!bpf_pseudo_call(insn))
1c2a088a
AS
17157 continue;
17158 subprog = insn->off;
3d717fad 17159 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
1c2a088a 17160 }
2162fed4
SD
17161
17162 /* we use the aux data to keep a list of the start addresses
17163 * of the JITed images for each function in the program
17164 *
17165 * for some architectures, such as powerpc64, the imm field
17166 * might not be large enough to hold the offset of the start
17167 * address of the callee's JITed image from __bpf_call_base
17168 *
17169 * in such cases, we can lookup the start address of a callee
17170 * by using its subprog id, available from the off field of
17171 * the call instruction, as an index for this list
17172 */
17173 func[i]->aux->func = func;
17174 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 17175 }
f910cefa 17176 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
17177 old_bpf_func = func[i]->bpf_func;
17178 tmp = bpf_int_jit_compile(func[i]);
17179 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17180 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 17181 err = -ENOTSUPP;
1c2a088a
AS
17182 goto out_free;
17183 }
17184 cond_resched();
17185 }
17186
17187 /* finally lock prog and jit images for all functions and
17188 * populate kallsysm
17189 */
f910cefa 17190 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
17191 bpf_prog_lock_ro(func[i]);
17192 bpf_prog_kallsyms_add(func[i]);
17193 }
7105e828
DB
17194
17195 /* Last step: make now unused interpreter insns from main
17196 * prog consistent for later dump requests, so they can
17197 * later look the same as if they were interpreted only.
17198 */
17199 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
17200 if (bpf_pseudo_func(insn)) {
17201 insn[0].imm = env->insn_aux_data[i].call_imm;
3990ed4c
MKL
17202 insn[1].imm = insn->off;
17203 insn->off = 0;
69c087ba
YS
17204 continue;
17205 }
23a2d70c 17206 if (!bpf_pseudo_call(insn))
7105e828
DB
17207 continue;
17208 insn->off = env->insn_aux_data[i].call_imm;
17209 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 17210 insn->imm = subprog;
7105e828
DB
17211 }
17212
1c2a088a
AS
17213 prog->jited = 1;
17214 prog->bpf_func = func[0]->bpf_func;
d00c6473 17215 prog->jited_len = func[0]->jited_len;
1c2a088a 17216 prog->aux->func = func;
f910cefa 17217 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 17218 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
17219 return 0;
17220out_free:
f263a814
JF
17221 /* We failed JIT'ing, so at this point we need to unregister poke
17222 * descriptors from subprogs, so that kernel is not attempting to
17223 * patch it anymore as we're freeing the subprog JIT memory.
17224 */
17225 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17226 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17227 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17228 }
17229 /* At this point we're guaranteed that poke descriptors are not
17230 * live anymore. We can just unlink its descriptor table as it's
17231 * released with the main prog.
17232 */
a748c697
MF
17233 for (i = 0; i < env->subprog_cnt; i++) {
17234 if (!func[i])
17235 continue;
f263a814 17236 func[i]->aux->poke_tab = NULL;
a748c697
MF
17237 bpf_jit_free(func[i]);
17238 }
1c2a088a 17239 kfree(func);
c7a89784 17240out_undo_insn:
1c2a088a
AS
17241 /* cleanup main prog to be interpreted */
17242 prog->jit_requested = 0;
d2a3b7c5 17243 prog->blinding_requested = 0;
1c2a088a 17244 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 17245 if (!bpf_pseudo_call(insn))
1c2a088a
AS
17246 continue;
17247 insn->off = 0;
17248 insn->imm = env->insn_aux_data[i].call_imm;
17249 }
e16301fb 17250 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
17251 return err;
17252}
17253
1ea47e01
AS
17254static int fixup_call_args(struct bpf_verifier_env *env)
17255{
19d28fbd 17256#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
17257 struct bpf_prog *prog = env->prog;
17258 struct bpf_insn *insn = prog->insnsi;
e6ac2450 17259 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 17260 int i, depth;
19d28fbd 17261#endif
e4052d06 17262 int err = 0;
1ea47e01 17263
e4052d06 17264 if (env->prog->jit_requested &&
9d03ebc7 17265 !bpf_prog_is_offloaded(env->prog->aux)) {
19d28fbd
DM
17266 err = jit_subprogs(env);
17267 if (err == 0)
1c2a088a 17268 return 0;
c7a89784
DB
17269 if (err == -EFAULT)
17270 return err;
19d28fbd
DM
17271 }
17272#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
17273 if (has_kfunc_call) {
17274 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17275 return -EINVAL;
17276 }
e411901c
MF
17277 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17278 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17279 * have to be rejected, since interpreter doesn't support them yet.
17280 */
17281 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17282 return -EINVAL;
17283 }
1ea47e01 17284 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
17285 if (bpf_pseudo_func(insn)) {
17286 /* When JIT fails the progs with callback calls
17287 * have to be rejected, since interpreter doesn't support them yet.
17288 */
17289 verbose(env, "callbacks are not allowed in non-JITed programs\n");
17290 return -EINVAL;
17291 }
17292
23a2d70c 17293 if (!bpf_pseudo_call(insn))
1ea47e01
AS
17294 continue;
17295 depth = get_callee_stack_depth(env, insn, i);
17296 if (depth < 0)
17297 return depth;
17298 bpf_patch_call_args(insn, depth);
17299 }
19d28fbd
DM
17300 err = 0;
17301#endif
17302 return err;
1ea47e01
AS
17303}
17304
958cf2e2
KKD
17305static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17306 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
e6ac2450
MKL
17307{
17308 const struct bpf_kfunc_desc *desc;
3d76a4d3 17309 void *xdp_kfunc;
e6ac2450 17310
a5d82727
KKD
17311 if (!insn->imm) {
17312 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17313 return -EINVAL;
17314 }
17315
3d76a4d3
SF
17316 *cnt = 0;
17317
17318 if (bpf_dev_bound_kfunc_id(insn->imm)) {
17319 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
17320 if (xdp_kfunc) {
17321 insn->imm = BPF_CALL_IMM(xdp_kfunc);
17322 return 0;
17323 }
17324
17325 /* fallback to default kfunc when not supported by netdev */
17326 }
17327
e6ac2450 17328 /* insn->imm has the btf func_id. Replace it with
c2cc0ce7 17329 * an address (relative to __bpf_call_base).
e6ac2450 17330 */
2357672c 17331 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
e6ac2450
MKL
17332 if (!desc) {
17333 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17334 insn->imm);
17335 return -EFAULT;
17336 }
17337
17338 insn->imm = desc->imm;
958cf2e2
KKD
17339 if (insn->off)
17340 return 0;
17341 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17342 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17343 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17344 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
e6ac2450 17345
958cf2e2
KKD
17346 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17347 insn_buf[1] = addr[0];
17348 insn_buf[2] = addr[1];
17349 insn_buf[3] = *insn;
17350 *cnt = 4;
ac9f0605
KKD
17351 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
17352 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17353 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17354
17355 insn_buf[0] = addr[0];
17356 insn_buf[1] = addr[1];
17357 insn_buf[2] = *insn;
17358 *cnt = 3;
a35b9af4
YS
17359 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17360 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
fd264ca0
YS
17361 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17362 *cnt = 1;
b5964b96
JK
17363 } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17364 bool seen_direct_write = env->seen_direct_write;
17365 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17366
17367 if (is_rdonly)
17368 insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
17369
17370 /* restore env->seen_direct_write to its original value, since
17371 * may_access_direct_pkt_data mutates it
17372 */
17373 env->seen_direct_write = seen_direct_write;
958cf2e2 17374 }
e6ac2450
MKL
17375 return 0;
17376}
17377
e6ac5933
BJ
17378/* Do various post-verification rewrites in a single program pass.
17379 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 17380 */
e6ac5933 17381static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 17382{
79741b3b 17383 struct bpf_prog *prog = env->prog;
f92c1e18 17384 enum bpf_attach_type eatype = prog->expected_attach_type;
9b99edca 17385 enum bpf_prog_type prog_type = resolve_prog_type(prog);
79741b3b 17386 struct bpf_insn *insn = prog->insnsi;
e245c5c6 17387 const struct bpf_func_proto *fn;
79741b3b 17388 const int insn_cnt = prog->len;
09772d92 17389 const struct bpf_map_ops *ops;
c93552c4 17390 struct bpf_insn_aux_data *aux;
81ed18ab
AS
17391 struct bpf_insn insn_buf[16];
17392 struct bpf_prog *new_prog;
17393 struct bpf_map *map_ptr;
d2e4c1e6 17394 int i, ret, cnt, delta = 0;
e245c5c6 17395
79741b3b 17396 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 17397 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
17398 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17399 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17400 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 17401 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 17402 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
17403 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17404 struct bpf_insn *patchlet;
17405 struct bpf_insn chk_and_div[] = {
9b00f1b7 17406 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
17407 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17408 BPF_JNE | BPF_K, insn->src_reg,
17409 0, 2, 0),
f6b1b3bf
DB
17410 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17411 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17412 *insn,
17413 };
e88b2c6e 17414 struct bpf_insn chk_and_mod[] = {
9b00f1b7 17415 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
17416 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17417 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 17418 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 17419 *insn,
9b00f1b7
DB
17420 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17421 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 17422 };
f6b1b3bf 17423
e88b2c6e
DB
17424 patchlet = isdiv ? chk_and_div : chk_and_mod;
17425 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 17426 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
17427
17428 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
17429 if (!new_prog)
17430 return -ENOMEM;
17431
17432 delta += cnt - 1;
17433 env->prog = prog = new_prog;
17434 insn = new_prog->insnsi + i + delta;
17435 continue;
17436 }
17437
e6ac5933 17438 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
17439 if (BPF_CLASS(insn->code) == BPF_LD &&
17440 (BPF_MODE(insn->code) == BPF_ABS ||
17441 BPF_MODE(insn->code) == BPF_IND)) {
17442 cnt = env->ops->gen_ld_abs(insn, insn_buf);
17443 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17444 verbose(env, "bpf verifier is misconfigured\n");
17445 return -EINVAL;
17446 }
17447
17448 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17449 if (!new_prog)
17450 return -ENOMEM;
17451
17452 delta += cnt - 1;
17453 env->prog = prog = new_prog;
17454 insn = new_prog->insnsi + i + delta;
17455 continue;
17456 }
17457
e6ac5933 17458 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
17459 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17460 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17461 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17462 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 17463 struct bpf_insn *patch = &insn_buf[0];
801c6058 17464 bool issrc, isneg, isimm;
979d63d5
DB
17465 u32 off_reg;
17466
17467 aux = &env->insn_aux_data[i + delta];
3612af78
DB
17468 if (!aux->alu_state ||
17469 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
17470 continue;
17471
17472 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17473 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17474 BPF_ALU_SANITIZE_SRC;
801c6058 17475 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
17476
17477 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
17478 if (isimm) {
17479 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17480 } else {
17481 if (isneg)
17482 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17483 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17484 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17485 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17486 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17487 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17488 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17489 }
b9b34ddb
DB
17490 if (!issrc)
17491 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17492 insn->src_reg = BPF_REG_AX;
979d63d5
DB
17493 if (isneg)
17494 insn->code = insn->code == code_add ?
17495 code_sub : code_add;
17496 *patch++ = *insn;
801c6058 17497 if (issrc && isneg && !isimm)
979d63d5
DB
17498 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17499 cnt = patch - insn_buf;
17500
17501 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17502 if (!new_prog)
17503 return -ENOMEM;
17504
17505 delta += cnt - 1;
17506 env->prog = prog = new_prog;
17507 insn = new_prog->insnsi + i + delta;
17508 continue;
17509 }
17510
79741b3b
AS
17511 if (insn->code != (BPF_JMP | BPF_CALL))
17512 continue;
cc8b0b92
AS
17513 if (insn->src_reg == BPF_PSEUDO_CALL)
17514 continue;
e6ac2450 17515 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
958cf2e2 17516 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
e6ac2450
MKL
17517 if (ret)
17518 return ret;
958cf2e2
KKD
17519 if (cnt == 0)
17520 continue;
17521
17522 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17523 if (!new_prog)
17524 return -ENOMEM;
17525
17526 delta += cnt - 1;
17527 env->prog = prog = new_prog;
17528 insn = new_prog->insnsi + i + delta;
e6ac2450
MKL
17529 continue;
17530 }
e245c5c6 17531
79741b3b
AS
17532 if (insn->imm == BPF_FUNC_get_route_realm)
17533 prog->dst_needed = 1;
17534 if (insn->imm == BPF_FUNC_get_prandom_u32)
17535 bpf_user_rnd_init_once();
9802d865
JB
17536 if (insn->imm == BPF_FUNC_override_return)
17537 prog->kprobe_override = 1;
79741b3b 17538 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
17539 /* If we tail call into other programs, we
17540 * cannot make any assumptions since they can
17541 * be replaced dynamically during runtime in
17542 * the program array.
17543 */
17544 prog->cb_access = 1;
e411901c
MF
17545 if (!allow_tail_call_in_subprogs(env))
17546 prog->aux->stack_depth = MAX_BPF_STACK;
17547 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 17548
79741b3b 17549 /* mark bpf_tail_call as different opcode to avoid
8fb33b60 17550 * conditional branch in the interpreter for every normal
79741b3b
AS
17551 * call and to prevent accidental JITing by JIT compiler
17552 * that doesn't support bpf_tail_call yet
e245c5c6 17553 */
79741b3b 17554 insn->imm = 0;
71189fa9 17555 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 17556
c93552c4 17557 aux = &env->insn_aux_data[i + delta];
d2a3b7c5 17558 if (env->bpf_capable && !prog->blinding_requested &&
cc52d914 17559 prog->jit_requested &&
d2e4c1e6
DB
17560 !bpf_map_key_poisoned(aux) &&
17561 !bpf_map_ptr_poisoned(aux) &&
17562 !bpf_map_ptr_unpriv(aux)) {
17563 struct bpf_jit_poke_descriptor desc = {
17564 .reason = BPF_POKE_REASON_TAIL_CALL,
17565 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
17566 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 17567 .insn_idx = i + delta,
d2e4c1e6
DB
17568 };
17569
17570 ret = bpf_jit_add_poke_descriptor(prog, &desc);
17571 if (ret < 0) {
17572 verbose(env, "adding tail call poke descriptor failed\n");
17573 return ret;
17574 }
17575
17576 insn->imm = ret + 1;
17577 continue;
17578 }
17579
c93552c4
DB
17580 if (!bpf_map_ptr_unpriv(aux))
17581 continue;
17582
b2157399
AS
17583 /* instead of changing every JIT dealing with tail_call
17584 * emit two extra insns:
17585 * if (index >= max_entries) goto out;
17586 * index &= array->index_mask;
17587 * to avoid out-of-bounds cpu speculation
17588 */
c93552c4 17589 if (bpf_map_ptr_poisoned(aux)) {
40950343 17590 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
17591 return -EINVAL;
17592 }
c93552c4 17593
d2e4c1e6 17594 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
17595 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
17596 map_ptr->max_entries, 2);
17597 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
17598 container_of(map_ptr,
17599 struct bpf_array,
17600 map)->index_mask);
17601 insn_buf[2] = *insn;
17602 cnt = 3;
17603 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17604 if (!new_prog)
17605 return -ENOMEM;
17606
17607 delta += cnt - 1;
17608 env->prog = prog = new_prog;
17609 insn = new_prog->insnsi + i + delta;
79741b3b
AS
17610 continue;
17611 }
e245c5c6 17612
b00628b1
AS
17613 if (insn->imm == BPF_FUNC_timer_set_callback) {
17614 /* The verifier will process callback_fn as many times as necessary
17615 * with different maps and the register states prepared by
17616 * set_timer_callback_state will be accurate.
17617 *
17618 * The following use case is valid:
17619 * map1 is shared by prog1, prog2, prog3.
17620 * prog1 calls bpf_timer_init for some map1 elements
17621 * prog2 calls bpf_timer_set_callback for some map1 elements.
17622 * Those that were not bpf_timer_init-ed will return -EINVAL.
17623 * prog3 calls bpf_timer_start for some map1 elements.
17624 * Those that were not both bpf_timer_init-ed and
17625 * bpf_timer_set_callback-ed will return -EINVAL.
17626 */
17627 struct bpf_insn ld_addrs[2] = {
17628 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
17629 };
17630
17631 insn_buf[0] = ld_addrs[0];
17632 insn_buf[1] = ld_addrs[1];
17633 insn_buf[2] = *insn;
17634 cnt = 3;
17635
17636 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17637 if (!new_prog)
17638 return -ENOMEM;
17639
17640 delta += cnt - 1;
17641 env->prog = prog = new_prog;
17642 insn = new_prog->insnsi + i + delta;
17643 goto patch_call_imm;
17644 }
17645
9bb00b28
YS
17646 if (is_storage_get_function(insn->imm)) {
17647 if (!env->prog->aux->sleepable ||
17648 env->insn_aux_data[i + delta].storage_get_func_atomic)
d56c9fe6 17649 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
9bb00b28
YS
17650 else
17651 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
b00fa38a
JK
17652 insn_buf[1] = *insn;
17653 cnt = 2;
17654
17655 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17656 if (!new_prog)
17657 return -ENOMEM;
17658
17659 delta += cnt - 1;
17660 env->prog = prog = new_prog;
17661 insn = new_prog->insnsi + i + delta;
17662 goto patch_call_imm;
17663 }
17664
89c63074 17665 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
17666 * and other inlining handlers are currently limited to 64 bit
17667 * only.
89c63074 17668 */
60b58afc 17669 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
17670 (insn->imm == BPF_FUNC_map_lookup_elem ||
17671 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
17672 insn->imm == BPF_FUNC_map_delete_elem ||
17673 insn->imm == BPF_FUNC_map_push_elem ||
17674 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f 17675 insn->imm == BPF_FUNC_map_peek_elem ||
0640c77c 17676 insn->imm == BPF_FUNC_redirect_map ||
07343110
FZ
17677 insn->imm == BPF_FUNC_for_each_map_elem ||
17678 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
c93552c4
DB
17679 aux = &env->insn_aux_data[i + delta];
17680 if (bpf_map_ptr_poisoned(aux))
17681 goto patch_call_imm;
17682
d2e4c1e6 17683 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
17684 ops = map_ptr->ops;
17685 if (insn->imm == BPF_FUNC_map_lookup_elem &&
17686 ops->map_gen_lookup) {
17687 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
17688 if (cnt == -EOPNOTSUPP)
17689 goto patch_map_ops_generic;
17690 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
17691 verbose(env, "bpf verifier is misconfigured\n");
17692 return -EINVAL;
17693 }
81ed18ab 17694
09772d92
DB
17695 new_prog = bpf_patch_insn_data(env, i + delta,
17696 insn_buf, cnt);
17697 if (!new_prog)
17698 return -ENOMEM;
81ed18ab 17699
09772d92
DB
17700 delta += cnt - 1;
17701 env->prog = prog = new_prog;
17702 insn = new_prog->insnsi + i + delta;
17703 continue;
17704 }
81ed18ab 17705
09772d92
DB
17706 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17707 (void *(*)(struct bpf_map *map, void *key))NULL));
17708 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
d7ba4cc9 17709 (long (*)(struct bpf_map *map, void *key))NULL));
09772d92 17710 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
d7ba4cc9 17711 (long (*)(struct bpf_map *map, void *key, void *value,
09772d92 17712 u64 flags))NULL));
84430d42 17713 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
d7ba4cc9 17714 (long (*)(struct bpf_map *map, void *value,
84430d42
DB
17715 u64 flags))NULL));
17716 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
d7ba4cc9 17717 (long (*)(struct bpf_map *map, void *value))NULL));
84430d42 17718 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
d7ba4cc9 17719 (long (*)(struct bpf_map *map, void *value))NULL));
e6a4750f 17720 BUILD_BUG_ON(!__same_type(ops->map_redirect,
d7ba4cc9 17721 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
0640c77c 17722 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
d7ba4cc9 17723 (long (*)(struct bpf_map *map,
0640c77c
AI
17724 bpf_callback_t callback_fn,
17725 void *callback_ctx,
17726 u64 flags))NULL));
07343110
FZ
17727 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17728 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
e6a4750f 17729
4a8f87e6 17730patch_map_ops_generic:
09772d92
DB
17731 switch (insn->imm) {
17732 case BPF_FUNC_map_lookup_elem:
3d717fad 17733 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
09772d92
DB
17734 continue;
17735 case BPF_FUNC_map_update_elem:
3d717fad 17736 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
09772d92
DB
17737 continue;
17738 case BPF_FUNC_map_delete_elem:
3d717fad 17739 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
09772d92 17740 continue;
84430d42 17741 case BPF_FUNC_map_push_elem:
3d717fad 17742 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
84430d42
DB
17743 continue;
17744 case BPF_FUNC_map_pop_elem:
3d717fad 17745 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
84430d42
DB
17746 continue;
17747 case BPF_FUNC_map_peek_elem:
3d717fad 17748 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
84430d42 17749 continue;
e6a4750f 17750 case BPF_FUNC_redirect_map:
3d717fad 17751 insn->imm = BPF_CALL_IMM(ops->map_redirect);
e6a4750f 17752 continue;
0640c77c
AI
17753 case BPF_FUNC_for_each_map_elem:
17754 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
e6a4750f 17755 continue;
07343110
FZ
17756 case BPF_FUNC_map_lookup_percpu_elem:
17757 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17758 continue;
09772d92 17759 }
81ed18ab 17760
09772d92 17761 goto patch_call_imm;
81ed18ab
AS
17762 }
17763
e6ac5933 17764 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
17765 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17766 insn->imm == BPF_FUNC_jiffies64) {
17767 struct bpf_insn ld_jiffies_addr[2] = {
17768 BPF_LD_IMM64(BPF_REG_0,
17769 (unsigned long)&jiffies),
17770 };
17771
17772 insn_buf[0] = ld_jiffies_addr[0];
17773 insn_buf[1] = ld_jiffies_addr[1];
17774 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17775 BPF_REG_0, 0);
17776 cnt = 3;
17777
17778 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17779 cnt);
17780 if (!new_prog)
17781 return -ENOMEM;
17782
17783 delta += cnt - 1;
17784 env->prog = prog = new_prog;
17785 insn = new_prog->insnsi + i + delta;
17786 continue;
17787 }
17788
f92c1e18
JO
17789 /* Implement bpf_get_func_arg inline. */
17790 if (prog_type == BPF_PROG_TYPE_TRACING &&
17791 insn->imm == BPF_FUNC_get_func_arg) {
17792 /* Load nr_args from ctx - 8 */
17793 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17794 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17795 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17796 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17797 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17798 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17799 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17800 insn_buf[7] = BPF_JMP_A(1);
17801 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17802 cnt = 9;
17803
17804 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17805 if (!new_prog)
17806 return -ENOMEM;
17807
17808 delta += cnt - 1;
17809 env->prog = prog = new_prog;
17810 insn = new_prog->insnsi + i + delta;
17811 continue;
17812 }
17813
17814 /* Implement bpf_get_func_ret inline. */
17815 if (prog_type == BPF_PROG_TYPE_TRACING &&
17816 insn->imm == BPF_FUNC_get_func_ret) {
17817 if (eatype == BPF_TRACE_FEXIT ||
17818 eatype == BPF_MODIFY_RETURN) {
17819 /* Load nr_args from ctx - 8 */
17820 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17821 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17822 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17823 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17824 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17825 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17826 cnt = 6;
17827 } else {
17828 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17829 cnt = 1;
17830 }
17831
17832 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17833 if (!new_prog)
17834 return -ENOMEM;
17835
17836 delta += cnt - 1;
17837 env->prog = prog = new_prog;
17838 insn = new_prog->insnsi + i + delta;
17839 continue;
17840 }
17841
17842 /* Implement get_func_arg_cnt inline. */
17843 if (prog_type == BPF_PROG_TYPE_TRACING &&
17844 insn->imm == BPF_FUNC_get_func_arg_cnt) {
17845 /* Load nr_args from ctx - 8 */
17846 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17847
17848 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17849 if (!new_prog)
17850 return -ENOMEM;
17851
17852 env->prog = prog = new_prog;
17853 insn = new_prog->insnsi + i + delta;
17854 continue;
17855 }
17856
f705ec76 17857 /* Implement bpf_get_func_ip inline. */
9b99edca
JO
17858 if (prog_type == BPF_PROG_TYPE_TRACING &&
17859 insn->imm == BPF_FUNC_get_func_ip) {
f92c1e18
JO
17860 /* Load IP address from ctx - 16 */
17861 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
9b99edca
JO
17862
17863 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17864 if (!new_prog)
17865 return -ENOMEM;
17866
17867 env->prog = prog = new_prog;
17868 insn = new_prog->insnsi + i + delta;
17869 continue;
17870 }
17871
81ed18ab 17872patch_call_imm:
5e43f899 17873 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
17874 /* all functions that have prototype and verifier allowed
17875 * programs to call them, must be real in-kernel functions
17876 */
17877 if (!fn->func) {
61bd5218
JK
17878 verbose(env,
17879 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
17880 func_id_name(insn->imm), insn->imm);
17881 return -EFAULT;
e245c5c6 17882 }
79741b3b 17883 insn->imm = fn->func - __bpf_call_base;
e245c5c6 17884 }
e245c5c6 17885
d2e4c1e6
DB
17886 /* Since poke tab is now finalized, publish aux to tracker. */
17887 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17888 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17889 if (!map_ptr->ops->map_poke_track ||
17890 !map_ptr->ops->map_poke_untrack ||
17891 !map_ptr->ops->map_poke_run) {
17892 verbose(env, "bpf verifier is misconfigured\n");
17893 return -EINVAL;
17894 }
17895
17896 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17897 if (ret < 0) {
17898 verbose(env, "tracking tail call prog failed\n");
17899 return ret;
17900 }
17901 }
17902
e6ac2450
MKL
17903 sort_kfunc_descs_by_imm(env->prog);
17904
79741b3b
AS
17905 return 0;
17906}
e245c5c6 17907
1ade2371
EZ
17908static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17909 int position,
17910 s32 stack_base,
17911 u32 callback_subprogno,
17912 u32 *cnt)
17913{
17914 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17915 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17916 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17917 int reg_loop_max = BPF_REG_6;
17918 int reg_loop_cnt = BPF_REG_7;
17919 int reg_loop_ctx = BPF_REG_8;
17920
17921 struct bpf_prog *new_prog;
17922 u32 callback_start;
17923 u32 call_insn_offset;
17924 s32 callback_offset;
17925
17926 /* This represents an inlined version of bpf_iter.c:bpf_loop,
17927 * be careful to modify this code in sync.
17928 */
17929 struct bpf_insn insn_buf[] = {
17930 /* Return error and jump to the end of the patch if
17931 * expected number of iterations is too big.
17932 */
17933 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17934 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17935 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17936 /* spill R6, R7, R8 to use these as loop vars */
17937 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17938 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17939 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17940 /* initialize loop vars */
17941 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17942 BPF_MOV32_IMM(reg_loop_cnt, 0),
17943 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17944 /* loop header,
17945 * if reg_loop_cnt >= reg_loop_max skip the loop body
17946 */
17947 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17948 /* callback call,
17949 * correct callback offset would be set after patching
17950 */
17951 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17952 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17953 BPF_CALL_REL(0),
17954 /* increment loop counter */
17955 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17956 /* jump to loop header if callback returned 0 */
17957 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17958 /* return value of bpf_loop,
17959 * set R0 to the number of iterations
17960 */
17961 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17962 /* restore original values of R6, R7, R8 */
17963 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17964 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17965 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17966 };
17967
17968 *cnt = ARRAY_SIZE(insn_buf);
17969 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17970 if (!new_prog)
17971 return new_prog;
17972
17973 /* callback start is known only after patching */
17974 callback_start = env->subprog_info[callback_subprogno].start;
17975 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17976 call_insn_offset = position + 12;
17977 callback_offset = callback_start - call_insn_offset - 1;
fb4e3b33 17978 new_prog->insnsi[call_insn_offset].imm = callback_offset;
1ade2371
EZ
17979
17980 return new_prog;
17981}
17982
17983static bool is_bpf_loop_call(struct bpf_insn *insn)
17984{
17985 return insn->code == (BPF_JMP | BPF_CALL) &&
17986 insn->src_reg == 0 &&
17987 insn->imm == BPF_FUNC_loop;
17988}
17989
17990/* For all sub-programs in the program (including main) check
17991 * insn_aux_data to see if there are bpf_loop calls that require
17992 * inlining. If such calls are found the calls are replaced with a
17993 * sequence of instructions produced by `inline_bpf_loop` function and
17994 * subprog stack_depth is increased by the size of 3 registers.
17995 * This stack space is used to spill values of the R6, R7, R8. These
17996 * registers are used to store the loop bound, counter and context
17997 * variables.
17998 */
17999static int optimize_bpf_loop(struct bpf_verifier_env *env)
18000{
18001 struct bpf_subprog_info *subprogs = env->subprog_info;
18002 int i, cur_subprog = 0, cnt, delta = 0;
18003 struct bpf_insn *insn = env->prog->insnsi;
18004 int insn_cnt = env->prog->len;
18005 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18006 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18007 u16 stack_depth_extra = 0;
18008
18009 for (i = 0; i < insn_cnt; i++, insn++) {
18010 struct bpf_loop_inline_state *inline_state =
18011 &env->insn_aux_data[i + delta].loop_inline_state;
18012
18013 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18014 struct bpf_prog *new_prog;
18015
18016 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18017 new_prog = inline_bpf_loop(env,
18018 i + delta,
18019 -(stack_depth + stack_depth_extra),
18020 inline_state->callback_subprogno,
18021 &cnt);
18022 if (!new_prog)
18023 return -ENOMEM;
18024
18025 delta += cnt - 1;
18026 env->prog = new_prog;
18027 insn = new_prog->insnsi + i + delta;
18028 }
18029
18030 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18031 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18032 cur_subprog++;
18033 stack_depth = subprogs[cur_subprog].stack_depth;
18034 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18035 stack_depth_extra = 0;
18036 }
18037 }
18038
18039 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18040
18041 return 0;
18042}
18043
58e2af8b 18044static void free_states(struct bpf_verifier_env *env)
f1bca824 18045{
58e2af8b 18046 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
18047 int i;
18048
9f4686c4
AS
18049 sl = env->free_list;
18050 while (sl) {
18051 sln = sl->next;
18052 free_verifier_state(&sl->state, false);
18053 kfree(sl);
18054 sl = sln;
18055 }
51c39bb1 18056 env->free_list = NULL;
9f4686c4 18057
f1bca824
AS
18058 if (!env->explored_states)
18059 return;
18060
dc2a4ebc 18061 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
18062 sl = env->explored_states[i];
18063
a8f500af
AS
18064 while (sl) {
18065 sln = sl->next;
18066 free_verifier_state(&sl->state, false);
18067 kfree(sl);
18068 sl = sln;
18069 }
51c39bb1 18070 env->explored_states[i] = NULL;
f1bca824 18071 }
51c39bb1 18072}
f1bca824 18073
51c39bb1
AS
18074static int do_check_common(struct bpf_verifier_env *env, int subprog)
18075{
6f8a57cc 18076 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
18077 struct bpf_verifier_state *state;
18078 struct bpf_reg_state *regs;
18079 int ret, i;
18080
18081 env->prev_linfo = NULL;
18082 env->pass_cnt++;
18083
18084 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18085 if (!state)
18086 return -ENOMEM;
18087 state->curframe = 0;
18088 state->speculative = false;
18089 state->branches = 1;
18090 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18091 if (!state->frame[0]) {
18092 kfree(state);
18093 return -ENOMEM;
18094 }
18095 env->cur_state = state;
18096 init_func_state(env, state->frame[0],
18097 BPF_MAIN_FUNC /* callsite */,
18098 0 /* frameno */,
18099 subprog);
be2ef816
AN
18100 state->first_insn_idx = env->subprog_info[subprog].start;
18101 state->last_insn_idx = -1;
51c39bb1
AS
18102
18103 regs = state->frame[state->curframe]->regs;
be8704ff 18104 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
18105 ret = btf_prepare_func_args(env, subprog, regs);
18106 if (ret)
18107 goto out;
18108 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18109 if (regs[i].type == PTR_TO_CTX)
18110 mark_reg_known_zero(env, regs, i);
18111 else if (regs[i].type == SCALAR_VALUE)
18112 mark_reg_unknown(env, regs, i);
cf9f2f8d 18113 else if (base_type(regs[i].type) == PTR_TO_MEM) {
e5069b9c
DB
18114 const u32 mem_size = regs[i].mem_size;
18115
18116 mark_reg_known_zero(env, regs, i);
18117 regs[i].mem_size = mem_size;
18118 regs[i].id = ++env->id_gen;
18119 }
51c39bb1
AS
18120 }
18121 } else {
18122 /* 1st arg to a function */
18123 regs[BPF_REG_1].type = PTR_TO_CTX;
18124 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 18125 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
18126 if (ret == -EFAULT)
18127 /* unlikely verifier bug. abort.
18128 * ret == 0 and ret < 0 are sadly acceptable for
18129 * main() function due to backward compatibility.
18130 * Like socket filter program may be written as:
18131 * int bpf_prog(struct pt_regs *ctx)
18132 * and never dereference that ctx in the program.
18133 * 'struct pt_regs' is a type mismatch for socket
18134 * filter that should be using 'struct __sk_buff'.
18135 */
18136 goto out;
18137 }
18138
18139 ret = do_check(env);
18140out:
f59bbfc2
AS
18141 /* check for NULL is necessary, since cur_state can be freed inside
18142 * do_check() under memory pressure.
18143 */
18144 if (env->cur_state) {
18145 free_verifier_state(env->cur_state, true);
18146 env->cur_state = NULL;
18147 }
6f8a57cc
AN
18148 while (!pop_stack(env, NULL, NULL, false));
18149 if (!ret && pop_log)
18150 bpf_vlog_reset(&env->log, 0);
51c39bb1 18151 free_states(env);
51c39bb1
AS
18152 return ret;
18153}
18154
18155/* Verify all global functions in a BPF program one by one based on their BTF.
18156 * All global functions must pass verification. Otherwise the whole program is rejected.
18157 * Consider:
18158 * int bar(int);
18159 * int foo(int f)
18160 * {
18161 * return bar(f);
18162 * }
18163 * int bar(int b)
18164 * {
18165 * ...
18166 * }
18167 * foo() will be verified first for R1=any_scalar_value. During verification it
18168 * will be assumed that bar() already verified successfully and call to bar()
18169 * from foo() will be checked for type match only. Later bar() will be verified
18170 * independently to check that it's safe for R1=any_scalar_value.
18171 */
18172static int do_check_subprogs(struct bpf_verifier_env *env)
18173{
18174 struct bpf_prog_aux *aux = env->prog->aux;
18175 int i, ret;
18176
18177 if (!aux->func_info)
18178 return 0;
18179
18180 for (i = 1; i < env->subprog_cnt; i++) {
18181 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18182 continue;
18183 env->insn_idx = env->subprog_info[i].start;
18184 WARN_ON_ONCE(env->insn_idx == 0);
18185 ret = do_check_common(env, i);
18186 if (ret) {
18187 return ret;
18188 } else if (env->log.level & BPF_LOG_LEVEL) {
18189 verbose(env,
18190 "Func#%d is safe for any args that match its prototype\n",
18191 i);
18192 }
18193 }
18194 return 0;
18195}
18196
18197static int do_check_main(struct bpf_verifier_env *env)
18198{
18199 int ret;
18200
18201 env->insn_idx = 0;
18202 ret = do_check_common(env, 0);
18203 if (!ret)
18204 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18205 return ret;
18206}
18207
18208
06ee7115
AS
18209static void print_verification_stats(struct bpf_verifier_env *env)
18210{
18211 int i;
18212
18213 if (env->log.level & BPF_LOG_STATS) {
18214 verbose(env, "verification time %lld usec\n",
18215 div_u64(env->verification_time, 1000));
18216 verbose(env, "stack depth ");
18217 for (i = 0; i < env->subprog_cnt; i++) {
18218 u32 depth = env->subprog_info[i].stack_depth;
18219
18220 verbose(env, "%d", depth);
18221 if (i + 1 < env->subprog_cnt)
18222 verbose(env, "+");
18223 }
18224 verbose(env, "\n");
18225 }
18226 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18227 "total_states %d peak_states %d mark_read %d\n",
18228 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18229 env->max_states_per_insn, env->total_states,
18230 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
18231}
18232
27ae7997
MKL
18233static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18234{
18235 const struct btf_type *t, *func_proto;
18236 const struct bpf_struct_ops *st_ops;
18237 const struct btf_member *member;
18238 struct bpf_prog *prog = env->prog;
18239 u32 btf_id, member_idx;
18240 const char *mname;
18241
12aa8a94
THJ
18242 if (!prog->gpl_compatible) {
18243 verbose(env, "struct ops programs must have a GPL compatible license\n");
18244 return -EINVAL;
18245 }
18246
27ae7997
MKL
18247 btf_id = prog->aux->attach_btf_id;
18248 st_ops = bpf_struct_ops_find(btf_id);
18249 if (!st_ops) {
18250 verbose(env, "attach_btf_id %u is not a supported struct\n",
18251 btf_id);
18252 return -ENOTSUPP;
18253 }
18254
18255 t = st_ops->type;
18256 member_idx = prog->expected_attach_type;
18257 if (member_idx >= btf_type_vlen(t)) {
18258 verbose(env, "attach to invalid member idx %u of struct %s\n",
18259 member_idx, st_ops->name);
18260 return -EINVAL;
18261 }
18262
18263 member = &btf_type_member(t)[member_idx];
18264 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18265 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18266 NULL);
18267 if (!func_proto) {
18268 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18269 mname, member_idx, st_ops->name);
18270 return -EINVAL;
18271 }
18272
18273 if (st_ops->check_member) {
51a52a29 18274 int err = st_ops->check_member(t, member, prog);
27ae7997
MKL
18275
18276 if (err) {
18277 verbose(env, "attach to unsupported member %s of struct %s\n",
18278 mname, st_ops->name);
18279 return err;
18280 }
18281 }
18282
18283 prog->aux->attach_func_proto = func_proto;
18284 prog->aux->attach_func_name = mname;
18285 env->ops = st_ops->verifier_ops;
18286
18287 return 0;
18288}
6ba43b76
KS
18289#define SECURITY_PREFIX "security_"
18290
f7b12b6f 18291static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 18292{
69191754 18293 if (within_error_injection_list(addr) ||
f7b12b6f 18294 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 18295 return 0;
6ba43b76 18296
6ba43b76
KS
18297 return -EINVAL;
18298}
27ae7997 18299
1e6c62a8
AS
18300/* list of non-sleepable functions that are otherwise on
18301 * ALLOW_ERROR_INJECTION list
18302 */
18303BTF_SET_START(btf_non_sleepable_error_inject)
18304/* Three functions below can be called from sleepable and non-sleepable context.
18305 * Assume non-sleepable from bpf safety point of view.
18306 */
9dd3d069 18307BTF_ID(func, __filemap_add_folio)
1e6c62a8
AS
18308BTF_ID(func, should_fail_alloc_page)
18309BTF_ID(func, should_failslab)
18310BTF_SET_END(btf_non_sleepable_error_inject)
18311
18312static int check_non_sleepable_error_inject(u32 btf_id)
18313{
18314 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18315}
18316
f7b12b6f
THJ
18317int bpf_check_attach_target(struct bpf_verifier_log *log,
18318 const struct bpf_prog *prog,
18319 const struct bpf_prog *tgt_prog,
18320 u32 btf_id,
18321 struct bpf_attach_target_info *tgt_info)
38207291 18322{
be8704ff 18323 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 18324 const char prefix[] = "btf_trace_";
5b92a28a 18325 int ret = 0, subprog = -1, i;
38207291 18326 const struct btf_type *t;
5b92a28a 18327 bool conservative = true;
38207291 18328 const char *tname;
5b92a28a 18329 struct btf *btf;
f7b12b6f 18330 long addr = 0;
31bf1dbc 18331 struct module *mod = NULL;
38207291 18332
f1b9509c 18333 if (!btf_id) {
efc68158 18334 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
18335 return -EINVAL;
18336 }
22dc4a0f 18337 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 18338 if (!btf) {
efc68158 18339 bpf_log(log,
5b92a28a
AS
18340 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18341 return -EINVAL;
18342 }
18343 t = btf_type_by_id(btf, btf_id);
f1b9509c 18344 if (!t) {
efc68158 18345 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
18346 return -EINVAL;
18347 }
5b92a28a 18348 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 18349 if (!tname) {
efc68158 18350 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
18351 return -EINVAL;
18352 }
5b92a28a
AS
18353 if (tgt_prog) {
18354 struct bpf_prog_aux *aux = tgt_prog->aux;
18355
fd7c211d
THJ
18356 if (bpf_prog_is_dev_bound(prog->aux) &&
18357 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18358 bpf_log(log, "Target program bound device mismatch");
3d76a4d3
SF
18359 return -EINVAL;
18360 }
18361
5b92a28a
AS
18362 for (i = 0; i < aux->func_info_cnt; i++)
18363 if (aux->func_info[i].type_id == btf_id) {
18364 subprog = i;
18365 break;
18366 }
18367 if (subprog == -1) {
efc68158 18368 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
18369 return -EINVAL;
18370 }
18371 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
18372 if (prog_extension) {
18373 if (conservative) {
efc68158 18374 bpf_log(log,
be8704ff
AS
18375 "Cannot replace static functions\n");
18376 return -EINVAL;
18377 }
18378 if (!prog->jit_requested) {
efc68158 18379 bpf_log(log,
be8704ff
AS
18380 "Extension programs should be JITed\n");
18381 return -EINVAL;
18382 }
be8704ff
AS
18383 }
18384 if (!tgt_prog->jited) {
efc68158 18385 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
18386 return -EINVAL;
18387 }
18388 if (tgt_prog->type == prog->type) {
18389 /* Cannot fentry/fexit another fentry/fexit program.
18390 * Cannot attach program extension to another extension.
18391 * It's ok to attach fentry/fexit to extension program.
18392 */
efc68158 18393 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
18394 return -EINVAL;
18395 }
18396 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18397 prog_extension &&
18398 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18399 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18400 /* Program extensions can extend all program types
18401 * except fentry/fexit. The reason is the following.
18402 * The fentry/fexit programs are used for performance
18403 * analysis, stats and can be attached to any program
18404 * type except themselves. When extension program is
18405 * replacing XDP function it is necessary to allow
18406 * performance analysis of all functions. Both original
18407 * XDP program and its program extension. Hence
18408 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18409 * allowed. If extending of fentry/fexit was allowed it
18410 * would be possible to create long call chain
18411 * fentry->extension->fentry->extension beyond
18412 * reasonable stack size. Hence extending fentry is not
18413 * allowed.
18414 */
efc68158 18415 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
18416 return -EINVAL;
18417 }
5b92a28a 18418 } else {
be8704ff 18419 if (prog_extension) {
efc68158 18420 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
18421 return -EINVAL;
18422 }
5b92a28a 18423 }
f1b9509c
AS
18424
18425 switch (prog->expected_attach_type) {
18426 case BPF_TRACE_RAW_TP:
5b92a28a 18427 if (tgt_prog) {
efc68158 18428 bpf_log(log,
5b92a28a
AS
18429 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18430 return -EINVAL;
18431 }
38207291 18432 if (!btf_type_is_typedef(t)) {
efc68158 18433 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
18434 btf_id);
18435 return -EINVAL;
18436 }
f1b9509c 18437 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 18438 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
18439 btf_id, tname);
18440 return -EINVAL;
18441 }
18442 tname += sizeof(prefix) - 1;
5b92a28a 18443 t = btf_type_by_id(btf, t->type);
38207291
MKL
18444 if (!btf_type_is_ptr(t))
18445 /* should never happen in valid vmlinux build */
18446 return -EINVAL;
5b92a28a 18447 t = btf_type_by_id(btf, t->type);
38207291
MKL
18448 if (!btf_type_is_func_proto(t))
18449 /* should never happen in valid vmlinux build */
18450 return -EINVAL;
18451
f7b12b6f 18452 break;
15d83c4d
YS
18453 case BPF_TRACE_ITER:
18454 if (!btf_type_is_func(t)) {
efc68158 18455 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
18456 btf_id);
18457 return -EINVAL;
18458 }
18459 t = btf_type_by_id(btf, t->type);
18460 if (!btf_type_is_func_proto(t))
18461 return -EINVAL;
f7b12b6f
THJ
18462 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18463 if (ret)
18464 return ret;
18465 break;
be8704ff
AS
18466 default:
18467 if (!prog_extension)
18468 return -EINVAL;
df561f66 18469 fallthrough;
ae240823 18470 case BPF_MODIFY_RETURN:
9e4e01df 18471 case BPF_LSM_MAC:
69fd337a 18472 case BPF_LSM_CGROUP:
fec56f58
AS
18473 case BPF_TRACE_FENTRY:
18474 case BPF_TRACE_FEXIT:
18475 if (!btf_type_is_func(t)) {
efc68158 18476 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
18477 btf_id);
18478 return -EINVAL;
18479 }
be8704ff 18480 if (prog_extension &&
efc68158 18481 btf_check_type_match(log, prog, btf, t))
be8704ff 18482 return -EINVAL;
5b92a28a 18483 t = btf_type_by_id(btf, t->type);
fec56f58
AS
18484 if (!btf_type_is_func_proto(t))
18485 return -EINVAL;
f7b12b6f 18486
4a1e7c0c
THJ
18487 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18488 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18489 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18490 return -EINVAL;
18491
f7b12b6f 18492 if (tgt_prog && conservative)
5b92a28a 18493 t = NULL;
f7b12b6f
THJ
18494
18495 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 18496 if (ret < 0)
f7b12b6f
THJ
18497 return ret;
18498
5b92a28a 18499 if (tgt_prog) {
e9eeec58
YS
18500 if (subprog == 0)
18501 addr = (long) tgt_prog->bpf_func;
18502 else
18503 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a 18504 } else {
31bf1dbc
VM
18505 if (btf_is_module(btf)) {
18506 mod = btf_try_get_module(btf);
18507 if (mod)
18508 addr = find_kallsyms_symbol_value(mod, tname);
18509 else
18510 addr = 0;
18511 } else {
18512 addr = kallsyms_lookup_name(tname);
18513 }
5b92a28a 18514 if (!addr) {
31bf1dbc 18515 module_put(mod);
efc68158 18516 bpf_log(log,
5b92a28a
AS
18517 "The address of function %s cannot be found\n",
18518 tname);
f7b12b6f 18519 return -ENOENT;
5b92a28a 18520 }
fec56f58 18521 }
18644cec 18522
1e6c62a8
AS
18523 if (prog->aux->sleepable) {
18524 ret = -EINVAL;
18525 switch (prog->type) {
18526 case BPF_PROG_TYPE_TRACING:
5b481aca
BT
18527
18528 /* fentry/fexit/fmod_ret progs can be sleepable if they are
1e6c62a8
AS
18529 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18530 */
18531 if (!check_non_sleepable_error_inject(btf_id) &&
18532 within_error_injection_list(addr))
18533 ret = 0;
5b481aca
BT
18534 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
18535 * in the fmodret id set with the KF_SLEEPABLE flag.
18536 */
18537 else {
18538 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
18539
18540 if (flags && (*flags & KF_SLEEPABLE))
18541 ret = 0;
18542 }
1e6c62a8
AS
18543 break;
18544 case BPF_PROG_TYPE_LSM:
18545 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
18546 * Only some of them are sleepable.
18547 */
423f1610 18548 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
18549 ret = 0;
18550 break;
18551 default:
18552 break;
18553 }
f7b12b6f 18554 if (ret) {
31bf1dbc 18555 module_put(mod);
f7b12b6f
THJ
18556 bpf_log(log, "%s is not sleepable\n", tname);
18557 return ret;
18558 }
1e6c62a8 18559 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 18560 if (tgt_prog) {
31bf1dbc 18561 module_put(mod);
efc68158 18562 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
18563 return -EINVAL;
18564 }
5b481aca
BT
18565 ret = -EINVAL;
18566 if (btf_kfunc_is_modify_return(btf, btf_id) ||
18567 !check_attach_modify_return(addr, tname))
18568 ret = 0;
f7b12b6f 18569 if (ret) {
31bf1dbc 18570 module_put(mod);
f7b12b6f
THJ
18571 bpf_log(log, "%s() is not modifiable\n", tname);
18572 return ret;
1af9270e 18573 }
18644cec 18574 }
f7b12b6f
THJ
18575
18576 break;
18577 }
18578 tgt_info->tgt_addr = addr;
18579 tgt_info->tgt_name = tname;
18580 tgt_info->tgt_type = t;
31bf1dbc 18581 tgt_info->tgt_mod = mod;
f7b12b6f
THJ
18582 return 0;
18583}
18584
35e3815f
JO
18585BTF_SET_START(btf_id_deny)
18586BTF_ID_UNUSED
18587#ifdef CONFIG_SMP
18588BTF_ID(func, migrate_disable)
18589BTF_ID(func, migrate_enable)
18590#endif
18591#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
18592BTF_ID(func, rcu_read_unlock_strict)
18593#endif
18594BTF_SET_END(btf_id_deny)
18595
700e6f85
JO
18596static bool can_be_sleepable(struct bpf_prog *prog)
18597{
18598 if (prog->type == BPF_PROG_TYPE_TRACING) {
18599 switch (prog->expected_attach_type) {
18600 case BPF_TRACE_FENTRY:
18601 case BPF_TRACE_FEXIT:
18602 case BPF_MODIFY_RETURN:
18603 case BPF_TRACE_ITER:
18604 return true;
18605 default:
18606 return false;
18607 }
18608 }
18609 return prog->type == BPF_PROG_TYPE_LSM ||
1e12d3ef
DV
18610 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
18611 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
700e6f85
JO
18612}
18613
f7b12b6f
THJ
18614static int check_attach_btf_id(struct bpf_verifier_env *env)
18615{
18616 struct bpf_prog *prog = env->prog;
3aac1ead 18617 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
18618 struct bpf_attach_target_info tgt_info = {};
18619 u32 btf_id = prog->aux->attach_btf_id;
18620 struct bpf_trampoline *tr;
18621 int ret;
18622 u64 key;
18623
79a7f8bd
AS
18624 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
18625 if (prog->aux->sleepable)
18626 /* attach_btf_id checked to be zero already */
18627 return 0;
18628 verbose(env, "Syscall programs can only be sleepable\n");
18629 return -EINVAL;
18630 }
18631
700e6f85 18632 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
1e12d3ef 18633 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
f7b12b6f
THJ
18634 return -EINVAL;
18635 }
18636
18637 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
18638 return check_struct_ops_btf_id(env);
18639
18640 if (prog->type != BPF_PROG_TYPE_TRACING &&
18641 prog->type != BPF_PROG_TYPE_LSM &&
18642 prog->type != BPF_PROG_TYPE_EXT)
18643 return 0;
18644
18645 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
18646 if (ret)
fec56f58 18647 return ret;
f7b12b6f
THJ
18648
18649 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
18650 /* to make freplace equivalent to their targets, they need to
18651 * inherit env->ops and expected_attach_type for the rest of the
18652 * verification
18653 */
f7b12b6f
THJ
18654 env->ops = bpf_verifier_ops[tgt_prog->type];
18655 prog->expected_attach_type = tgt_prog->expected_attach_type;
18656 }
18657
18658 /* store info about the attachment target that will be used later */
18659 prog->aux->attach_func_proto = tgt_info.tgt_type;
18660 prog->aux->attach_func_name = tgt_info.tgt_name;
31bf1dbc 18661 prog->aux->mod = tgt_info.tgt_mod;
f7b12b6f 18662
4a1e7c0c
THJ
18663 if (tgt_prog) {
18664 prog->aux->saved_dst_prog_type = tgt_prog->type;
18665 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
18666 }
18667
f7b12b6f
THJ
18668 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
18669 prog->aux->attach_btf_trace = true;
18670 return 0;
18671 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
18672 if (!bpf_iter_prog_supported(prog))
18673 return -EINVAL;
18674 return 0;
18675 }
18676
18677 if (prog->type == BPF_PROG_TYPE_LSM) {
18678 ret = bpf_lsm_verify_prog(&env->log, prog);
18679 if (ret < 0)
18680 return ret;
35e3815f
JO
18681 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
18682 btf_id_set_contains(&btf_id_deny, btf_id)) {
18683 return -EINVAL;
38207291 18684 }
f7b12b6f 18685
22dc4a0f 18686 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
18687 tr = bpf_trampoline_get(key, &tgt_info);
18688 if (!tr)
18689 return -ENOMEM;
18690
3aac1ead 18691 prog->aux->dst_trampoline = tr;
f7b12b6f 18692 return 0;
38207291
MKL
18693}
18694
76654e67
AM
18695struct btf *bpf_get_btf_vmlinux(void)
18696{
18697 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
18698 mutex_lock(&bpf_verifier_lock);
18699 if (!btf_vmlinux)
18700 btf_vmlinux = btf_parse_vmlinux();
18701 mutex_unlock(&bpf_verifier_lock);
18702 }
18703 return btf_vmlinux;
18704}
18705
af2ac3e1 18706int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
51580e79 18707{
06ee7115 18708 u64 start_time = ktime_get_ns();
58e2af8b 18709 struct bpf_verifier_env *env;
b9193c1b 18710 struct bpf_verifier_log *log;
9e4c24e7 18711 int i, len, ret = -EINVAL;
e2ae4ca2 18712 bool is_priv;
51580e79 18713
eba0c929
AB
18714 /* no program is valid */
18715 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18716 return -EINVAL;
18717
58e2af8b 18718 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
18719 * allocate/free it every time bpf_check() is called
18720 */
58e2af8b 18721 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
18722 if (!env)
18723 return -ENOMEM;
61bd5218 18724 log = &env->log;
cbd35700 18725
9e4c24e7 18726 len = (*prog)->len;
fad953ce 18727 env->insn_aux_data =
9e4c24e7 18728 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
18729 ret = -ENOMEM;
18730 if (!env->insn_aux_data)
18731 goto err_free_env;
9e4c24e7
JK
18732 for (i = 0; i < len; i++)
18733 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 18734 env->prog = *prog;
00176a34 18735 env->ops = bpf_verifier_ops[env->prog->type];
387544bf 18736 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
2c78ee89 18737 is_priv = bpf_capable();
0246e64d 18738
76654e67 18739 bpf_get_btf_vmlinux();
8580ac94 18740
cbd35700 18741 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
18742 if (!is_priv)
18743 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
18744
18745 if (attr->log_level || attr->log_buf || attr->log_size) {
18746 /* user requested verbose verifier output
18747 * and supplied buffer to store the verification trace
18748 */
e7bf8249
JK
18749 log->level = attr->log_level;
18750 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
18751 log->len_total = attr->log_size;
cbd35700 18752
e7bf8249 18753 /* log attributes have to be sane */
866de407
HT
18754 if (!bpf_verifier_log_attr_valid(log)) {
18755 ret = -EINVAL;
3df126f3 18756 goto err_unlock;
866de407 18757 }
cbd35700 18758 }
1ad2f583 18759
0f55f9ed
CL
18760 mark_verifier_state_clean(env);
18761
8580ac94
AS
18762 if (IS_ERR(btf_vmlinux)) {
18763 /* Either gcc or pahole or kernel are broken. */
18764 verbose(env, "in-kernel BTF is malformed\n");
18765 ret = PTR_ERR(btf_vmlinux);
38207291 18766 goto skip_full_check;
8580ac94
AS
18767 }
18768
1ad2f583
DB
18769 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18770 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 18771 env->strict_alignment = true;
e9ee9efc
DM
18772 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18773 env->strict_alignment = false;
cbd35700 18774
2c78ee89 18775 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 18776 env->allow_uninit_stack = bpf_allow_uninit_stack();
2c78ee89
AS
18777 env->bypass_spec_v1 = bpf_bypass_spec_v1();
18778 env->bypass_spec_v4 = bpf_bypass_spec_v4();
18779 env->bpf_capable = bpf_capable();
e2ae4ca2 18780
10d274e8
AS
18781 if (is_priv)
18782 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18783
dc2a4ebc 18784 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 18785 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
18786 GFP_USER);
18787 ret = -ENOMEM;
18788 if (!env->explored_states)
18789 goto skip_full_check;
18790
e6ac2450
MKL
18791 ret = add_subprog_and_kfunc(env);
18792 if (ret < 0)
18793 goto skip_full_check;
18794
d9762e84 18795 ret = check_subprogs(env);
475fb78f
AS
18796 if (ret < 0)
18797 goto skip_full_check;
18798
c454a46b 18799 ret = check_btf_info(env, attr, uattr);
838e9690
YS
18800 if (ret < 0)
18801 goto skip_full_check;
18802
be8704ff
AS
18803 ret = check_attach_btf_id(env);
18804 if (ret)
18805 goto skip_full_check;
18806
4976b718
HL
18807 ret = resolve_pseudo_ldimm64(env);
18808 if (ret < 0)
18809 goto skip_full_check;
18810
9d03ebc7 18811 if (bpf_prog_is_offloaded(env->prog->aux)) {
ceb11679
YZ
18812 ret = bpf_prog_offload_verifier_prep(env->prog);
18813 if (ret)
18814 goto skip_full_check;
18815 }
18816
d9762e84
MKL
18817 ret = check_cfg(env);
18818 if (ret < 0)
18819 goto skip_full_check;
18820
51c39bb1
AS
18821 ret = do_check_subprogs(env);
18822 ret = ret ?: do_check_main(env);
cbd35700 18823
9d03ebc7 18824 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
c941ce9c
QM
18825 ret = bpf_prog_offload_finalize(env);
18826
0246e64d 18827skip_full_check:
51c39bb1 18828 kvfree(env->explored_states);
0246e64d 18829
c131187d 18830 if (ret == 0)
9b38c405 18831 ret = check_max_stack_depth(env);
c131187d 18832
9b38c405 18833 /* instruction rewrites happen after this point */
1ade2371
EZ
18834 if (ret == 0)
18835 ret = optimize_bpf_loop(env);
18836
e2ae4ca2
JK
18837 if (is_priv) {
18838 if (ret == 0)
18839 opt_hard_wire_dead_code_branches(env);
52875a04
JK
18840 if (ret == 0)
18841 ret = opt_remove_dead_code(env);
a1b14abc
JK
18842 if (ret == 0)
18843 ret = opt_remove_nops(env);
52875a04
JK
18844 } else {
18845 if (ret == 0)
18846 sanitize_dead_code(env);
e2ae4ca2
JK
18847 }
18848
9bac3d6d
AS
18849 if (ret == 0)
18850 /* program is valid, convert *(u32*)(ctx + off) accesses */
18851 ret = convert_ctx_accesses(env);
18852
e245c5c6 18853 if (ret == 0)
e6ac5933 18854 ret = do_misc_fixups(env);
e245c5c6 18855
a4b1d3c1
JW
18856 /* do 32-bit optimization after insn patching has done so those patched
18857 * insns could be handled correctly.
18858 */
9d03ebc7 18859 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
d6c2308c
JW
18860 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18861 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18862 : false;
a4b1d3c1
JW
18863 }
18864
1ea47e01
AS
18865 if (ret == 0)
18866 ret = fixup_call_args(env);
18867
06ee7115
AS
18868 env->verification_time = ktime_get_ns() - start_time;
18869 print_verification_stats(env);
aba64c7d 18870 env->prog->aux->verified_insns = env->insn_processed;
06ee7115 18871
a2a7d570 18872 if (log->level && bpf_verifier_log_full(log))
cbd35700 18873 ret = -ENOSPC;
a2a7d570 18874 if (log->level && !log->ubuf) {
cbd35700 18875 ret = -EFAULT;
a2a7d570 18876 goto err_release_maps;
cbd35700
AS
18877 }
18878
541c3bad
AN
18879 if (ret)
18880 goto err_release_maps;
18881
18882 if (env->used_map_cnt) {
0246e64d 18883 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
18884 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18885 sizeof(env->used_maps[0]),
18886 GFP_KERNEL);
0246e64d 18887
9bac3d6d 18888 if (!env->prog->aux->used_maps) {
0246e64d 18889 ret = -ENOMEM;
a2a7d570 18890 goto err_release_maps;
0246e64d
AS
18891 }
18892
9bac3d6d 18893 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 18894 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 18895 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
18896 }
18897 if (env->used_btf_cnt) {
18898 /* if program passed verifier, update used_btfs in bpf_prog_aux */
18899 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18900 sizeof(env->used_btfs[0]),
18901 GFP_KERNEL);
18902 if (!env->prog->aux->used_btfs) {
18903 ret = -ENOMEM;
18904 goto err_release_maps;
18905 }
0246e64d 18906
541c3bad
AN
18907 memcpy(env->prog->aux->used_btfs, env->used_btfs,
18908 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18909 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18910 }
18911 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
18912 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
18913 * bpf_ld_imm64 instructions
18914 */
18915 convert_pseudo_ld_imm64(env);
18916 }
cbd35700 18917
541c3bad 18918 adjust_btf_func(env);
ba64e7d8 18919
a2a7d570 18920err_release_maps:
9bac3d6d 18921 if (!env->prog->aux->used_maps)
0246e64d 18922 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 18923 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
18924 */
18925 release_maps(env);
541c3bad
AN
18926 if (!env->prog->aux->used_btfs)
18927 release_btfs(env);
03f87c0b
THJ
18928
18929 /* extension progs temporarily inherit the attach_type of their targets
18930 for verification purposes, so set it back to zero before returning
18931 */
18932 if (env->prog->type == BPF_PROG_TYPE_EXT)
18933 env->prog->expected_attach_type = 0;
18934
9bac3d6d 18935 *prog = env->prog;
3df126f3 18936err_unlock:
45a73c17
AS
18937 if (!is_priv)
18938 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
18939 vfree(env->insn_aux_data);
18940err_free_env:
18941 kfree(env);
51580e79
AS
18942 return ret;
18943}