drm/xe: Don't grab runtime PM ref in engine create IOCTL
[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>
f42bcd16 28#include <linux/cpumask.h>
1fda5bb6 29#include <linux/bpf_mem_alloc.h>
680ee045 30#include <net/xdp.h>
51580e79 31
f4ac7e0b
JK
32#include "disasm.h"
33
00176a34 34static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 35#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
36 [_id] = & _name ## _verifier_ops,
37#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 38#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
39#include <linux/bpf_types.h>
40#undef BPF_PROG_TYPE
41#undef BPF_MAP_TYPE
f2e10bff 42#undef BPF_LINK_TYPE
00176a34
JK
43};
44
1fda5bb6
YS
45struct bpf_mem_alloc bpf_global_percpu_ma;
46static bool bpf_global_percpu_ma_set;
47
51580e79
AS
48/* bpf_check() is a static code analyzer that walks eBPF program
49 * instruction by instruction and updates register/stack state.
50 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51 *
52 * The first pass is depth-first-search to check that the program is a DAG.
53 * It rejects the following programs:
54 * - larger than BPF_MAXINSNS insns
55 * - if loop is present (detected via back-edge)
56 * - unreachable insns exist (shouldn't be a forest. program = one function)
57 * - out of bounds or malformed jumps
58 * The second pass is all possible path descent from the 1st insn.
8fb33b60 59 * Since it's analyzing all paths through the program, the length of the
eba38a96 60 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
61 * insn is less then 4K, but there are too many branches that change stack/regs.
62 * Number of 'branches to be analyzed' is limited to 1k
63 *
64 * On entry to each instruction, each register has a type, and the instruction
65 * changes the types of the registers depending on instruction semantics.
66 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67 * copied to R1.
68 *
69 * All registers are 64-bit.
70 * R0 - return register
71 * R1-R5 argument passing registers
72 * R6-R9 callee saved registers
73 * R10 - frame pointer read-only
74 *
75 * At the start of BPF program the register R1 contains a pointer to bpf_context
76 * and has type PTR_TO_CTX.
77 *
78 * Verifier tracks arithmetic operations on pointers in case:
79 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81 * 1st insn copies R10 (which has FRAME_PTR) type into R1
82 * and 2nd arithmetic instruction is pattern matched to recognize
83 * that it wants to construct a pointer to some element within stack.
84 * So after 2nd insn, the register R1 has type PTR_TO_STACK
85 * (and -20 constant is saved for further stack bounds checking).
86 * Meaning that this reg is a pointer to stack plus known immediate constant.
87 *
f1174f77 88 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 89 * means the register has some value, but it's not a valid pointer.
f1174f77 90 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
91 *
92 * When verifier sees load or store instructions the type of base register
c64b7983
JS
93 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94 * four pointer types recognized by check_mem_access() function.
51580e79
AS
95 *
96 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97 * and the range of [ptr, ptr + map's value_size) is accessible.
98 *
99 * registers used to pass values to function calls are checked against
100 * function argument constraints.
101 *
102 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103 * It means that the register type passed to this function must be
104 * PTR_TO_STACK and it will be used inside the function as
105 * 'pointer to map element key'
106 *
107 * For example the argument constraints for bpf_map_lookup_elem():
108 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109 * .arg1_type = ARG_CONST_MAP_PTR,
110 * .arg2_type = ARG_PTR_TO_MAP_KEY,
111 *
112 * ret_type says that this function returns 'pointer to map elem value or null'
113 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114 * 2nd argument should be a pointer to stack, which will be used inside
115 * the helper function as a pointer to map element key.
116 *
117 * On the kernel side the helper function looks like:
118 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119 * {
120 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121 * void *key = (void *) (unsigned long) r2;
122 * void *value;
123 *
124 * here kernel can access 'key' and 'map' pointers safely, knowing that
125 * [key, key + map->key_size) bytes are valid and were initialized on
126 * the stack of eBPF program.
127 * }
128 *
129 * Corresponding eBPF program may look like:
130 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
131 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
133 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134 * here verifier looks at prototype of map_lookup_elem() and sees:
135 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137 *
138 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140 * and were initialized prior to this call.
141 * If it's ok, then verifier allows this BPF_CALL insn and looks at
142 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
8fb33b60 144 * returns either pointer to map value or NULL.
51580e79
AS
145 *
146 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147 * insn, the register holding that pointer in the true branch changes state to
148 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149 * branch. See check_cond_jmp_op().
150 *
151 * After the call R0 is set to return type of the function and registers R1-R5
152 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
153 *
154 * The following reference types represent a potential reference to a kernel
155 * resource which, after first being allocated, must be checked and freed by
156 * the BPF program:
157 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158 *
159 * When the verifier sees a helper call return a reference type, it allocates a
160 * pointer id for the reference and stores it in the current function state.
161 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163 * passes through a NULL-check conditional. For the branch wherein the state is
164 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
165 *
166 * For each helper function that allocates a reference, such as
167 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168 * bpf_sk_release(). When a reference type passes into the release function,
169 * the verifier also releases the reference. If any unchecked or unreleased
170 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
171 */
172
17a52670 173/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 174struct bpf_verifier_stack_elem {
17a52670
AS
175 /* verifer state is 'st'
176 * before processing instruction 'insn_idx'
177 * and after processing instruction 'prev_insn_idx'
178 */
58e2af8b 179 struct bpf_verifier_state st;
17a52670
AS
180 int insn_idx;
181 int prev_insn_idx;
58e2af8b 182 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
183 /* length of verifier log at the time this state was pushed on stack */
184 u32 log_pos;
cbd35700
AS
185};
186
b285fcb7 187#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 188#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 189
d2e4c1e6
DB
190#define BPF_MAP_KEY_POISON (1ULL << 63)
191#define BPF_MAP_KEY_SEEN (1ULL << 62)
192
c93552c4
DB
193#define BPF_MAP_PTR_UNPRIV 1UL
194#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
195 POISON_POINTER_DELTA))
196#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
197
bc34dee6
JK
198static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
199static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
6a3cd331 200static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
5d92ddc3 201static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
6a3cd331
DM
202static int ref_set_non_owning(struct bpf_verifier_env *env,
203 struct bpf_reg_state *reg);
1cf3bfc6
IL
204static void specialize_kfunc(struct bpf_verifier_env *env,
205 u32 func_id, u16 offset, unsigned long *addr);
51302c95 206static bool is_trusted_reg(const struct bpf_reg_state *reg);
bc34dee6 207
c93552c4
DB
208static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
209{
d2e4c1e6 210 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
211}
212
213static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
214{
d2e4c1e6 215 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
216}
217
218static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
219 const struct bpf_map *map, bool unpriv)
220{
221 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
222 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
223 aux->map_ptr_state = (unsigned long)map |
224 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
225}
226
227static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
228{
229 return aux->map_key_state & BPF_MAP_KEY_POISON;
230}
231
232static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
233{
234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
235}
236
237static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
238{
239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
240}
241
242static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
243{
244 bool poisoned = bpf_map_key_poisoned(aux);
245
246 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 248}
fad73a1a 249
fde2a388
AN
250static bool bpf_helper_call(const struct bpf_insn *insn)
251{
252 return insn->code == (BPF_JMP | BPF_CALL) &&
253 insn->src_reg == 0;
254}
255
23a2d70c
YS
256static bool bpf_pseudo_call(const struct bpf_insn *insn)
257{
258 return insn->code == (BPF_JMP | BPF_CALL) &&
259 insn->src_reg == BPF_PSEUDO_CALL;
260}
261
e6ac2450
MKL
262static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
263{
264 return insn->code == (BPF_JMP | BPF_CALL) &&
265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
266}
267
33ff9823
DB
268struct bpf_call_arg_meta {
269 struct bpf_map *map_ptr;
435faee1 270 bool raw_mode;
36bbef52 271 bool pkt_access;
8f14852e 272 u8 release_regno;
435faee1
DB
273 int regno;
274 int access_size;
457f4436 275 int mem_size;
10060503 276 u64 msize_max_value;
1b986589 277 int ref_obj_id;
f8064ab9 278 int dynptr_id;
3e8ce298 279 int map_uid;
d83525ca 280 int func_id;
22dc4a0f 281 struct btf *btf;
eaa6bcb7 282 u32 btf_id;
22dc4a0f 283 struct btf *ret_btf;
eaa6bcb7 284 u32 ret_btf_id;
69c087ba 285 u32 subprogno;
aa3496ac 286 struct btf_field *kptr_field;
33ff9823
DB
287};
288
d0e1ac22
AN
289struct bpf_kfunc_call_arg_meta {
290 /* In parameters */
291 struct btf *btf;
292 u32 func_id;
293 u32 kfunc_flags;
294 const struct btf_type *func_proto;
295 const char *func_name;
296 /* Out parameters */
297 u32 ref_obj_id;
298 u8 release_regno;
299 bool r0_rdonly;
300 u32 ret_btf_id;
301 u64 r0_size;
302 u32 subprogno;
303 struct {
304 u64 value;
305 bool found;
306 } arg_constant;
4d585f48 307
7793fc3b 308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
4d585f48
DM
309 * generally to pass info about user-defined local kptr types to later
310 * verification logic
36d8bdf7 311 * bpf_obj_drop/bpf_percpu_obj_drop
4d585f48
DM
312 * Record the local kptr type to be drop'd
313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
7793fc3b
DM
314 * Record the local kptr type to be refcount_incr'd and use
315 * arg_owning_ref to determine whether refcount_acquire should be
316 * fallible
4d585f48
DM
317 */
318 struct btf *arg_btf;
319 u32 arg_btf_id;
7793fc3b 320 bool arg_owning_ref;
4d585f48 321
d0e1ac22
AN
322 struct {
323 struct btf_field *field;
324 } arg_list_head;
325 struct {
326 struct btf_field *field;
327 } arg_rbtree_root;
328 struct {
329 enum bpf_dynptr_type type;
330 u32 id;
361f129f 331 u32 ref_obj_id;
d0e1ac22 332 } initialized_dynptr;
06accc87
AN
333 struct {
334 u8 spi;
335 u8 frameno;
336 } iter;
d0e1ac22
AN
337 u64 mem_size;
338};
339
8580ac94
AS
340struct btf *btf_vmlinux;
341
cbd35700 342static DEFINE_MUTEX(bpf_verifier_lock);
1fda5bb6 343static DEFINE_MUTEX(bpf_percpu_ma_lock);
cbd35700 344
d9762e84
MKL
345static const struct bpf_line_info *
346find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
347{
348 const struct bpf_line_info *linfo;
349 const struct bpf_prog *prog;
350 u32 i, nr_linfo;
351
352 prog = env->prog;
353 nr_linfo = prog->aux->nr_linfo;
354
355 if (!nr_linfo || insn_off >= prog->len)
356 return NULL;
357
358 linfo = prog->aux->linfo;
359 for (i = 1; i < nr_linfo; i++)
360 if (insn_off < linfo[i].insn_off)
361 break;
362
363 return &linfo[i - 1];
364}
365
abe08840
JO
366__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
367{
77d2e05a 368 struct bpf_verifier_env *env = private_data;
abe08840
JO
369 va_list args;
370
77d2e05a
MKL
371 if (!bpf_verifier_log_needed(&env->log))
372 return;
373
abe08840 374 va_start(args, fmt);
77d2e05a 375 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
376 va_end(args);
377}
cbd35700 378
d9762e84
MKL
379static const char *ltrim(const char *s)
380{
381 while (isspace(*s))
382 s++;
383
384 return s;
385}
386
387__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
388 u32 insn_off,
389 const char *prefix_fmt, ...)
390{
391 const struct bpf_line_info *linfo;
392
393 if (!bpf_verifier_log_needed(&env->log))
394 return;
395
396 linfo = find_linfo(env, insn_off);
397 if (!linfo || linfo == env->prev_linfo)
398 return;
399
400 if (prefix_fmt) {
401 va_list args;
402
403 va_start(args, prefix_fmt);
404 bpf_verifier_vlog(&env->log, prefix_fmt, args);
405 va_end(args);
406 }
407
408 verbose(env, "%s\n",
409 ltrim(btf_name_by_offset(env->prog->aux->btf,
410 linfo->line_off)));
411
412 env->prev_linfo = linfo;
413}
414
bc2591d6
YS
415static void verbose_invalid_scalar(struct bpf_verifier_env *env,
416 struct bpf_reg_state *reg,
417 struct tnum *range, const char *ctx,
418 const char *reg_name)
419{
420 char tn_buf[48];
421
422 verbose(env, "At %s the register %s ", ctx, reg_name);
423 if (!tnum_is_unknown(reg->var_off)) {
424 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
425 verbose(env, "has value %s", tn_buf);
426 } else {
427 verbose(env, "has unknown scalar value");
428 }
429 tnum_strn(tn_buf, sizeof(tn_buf), *range);
430 verbose(env, " should have been in %s\n", tn_buf);
431}
432
de8f3a83
DB
433static bool type_is_pkt_pointer(enum bpf_reg_type type)
434{
0c9a7a7e 435 type = base_type(type);
de8f3a83
DB
436 return type == PTR_TO_PACKET ||
437 type == PTR_TO_PACKET_META;
438}
439
46f8bc92
MKL
440static bool type_is_sk_pointer(enum bpf_reg_type type)
441{
442 return type == PTR_TO_SOCKET ||
655a51e5 443 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
444 type == PTR_TO_TCP_SOCK ||
445 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
446}
447
1057d299
AS
448static bool type_may_be_null(u32 type)
449{
450 return type & PTR_MAYBE_NULL;
451}
452
51302c95 453static bool reg_not_null(const struct bpf_reg_state *reg)
cac616db 454{
51302c95
DV
455 enum bpf_reg_type type;
456
457 type = reg->type;
1057d299
AS
458 if (type_may_be_null(type))
459 return false;
460
461 type = base_type(type);
cac616db
JF
462 return type == PTR_TO_SOCKET ||
463 type == PTR_TO_TCP_SOCK ||
464 type == PTR_TO_MAP_VALUE ||
69c087ba 465 type == PTR_TO_MAP_KEY ||
d5271c5b 466 type == PTR_TO_SOCK_COMMON ||
51302c95 467 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
d5271c5b 468 type == PTR_TO_MEM;
cac616db
JF
469}
470
d8939cb0
DM
471static bool type_is_ptr_alloc_obj(u32 type)
472{
473 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
474}
475
6a3cd331
DM
476static bool type_is_non_owning_ref(u32 type)
477{
478 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
479}
480
4e814da0
KKD
481static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
482{
483 struct btf_record *rec = NULL;
484 struct btf_struct_meta *meta;
485
486 if (reg->type == PTR_TO_MAP_VALUE) {
487 rec = reg->map_ptr->record;
d8939cb0 488 } else if (type_is_ptr_alloc_obj(reg->type)) {
4e814da0
KKD
489 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
490 if (meta)
491 rec = meta->record;
492 }
493 return rec;
494}
495
fde2a388
AN
496static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
497{
498 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
499
500 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
501}
502
d83525ca
AS
503static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
504{
4e814da0 505 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
cba368c1
MKL
506}
507
20b2aff4
HL
508static bool type_is_rdonly_mem(u32 type)
509{
510 return type & MEM_RDONLY;
cba368c1
MKL
511}
512
64d85290
JS
513static bool is_acquire_function(enum bpf_func_id func_id,
514 const struct bpf_map *map)
515{
516 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
517
518 if (func_id == BPF_FUNC_sk_lookup_tcp ||
519 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436 520 func_id == BPF_FUNC_skc_lookup_tcp ||
c0a5a21c
KKD
521 func_id == BPF_FUNC_ringbuf_reserve ||
522 func_id == BPF_FUNC_kptr_xchg)
64d85290
JS
523 return true;
524
525 if (func_id == BPF_FUNC_map_lookup_elem &&
526 (map_type == BPF_MAP_TYPE_SOCKMAP ||
527 map_type == BPF_MAP_TYPE_SOCKHASH))
528 return true;
529
530 return false;
46f8bc92
MKL
531}
532
1b986589
MKL
533static bool is_ptr_cast_function(enum bpf_func_id func_id)
534{
535 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
536 func_id == BPF_FUNC_sk_fullsock ||
537 func_id == BPF_FUNC_skc_to_tcp_sock ||
538 func_id == BPF_FUNC_skc_to_tcp6_sock ||
539 func_id == BPF_FUNC_skc_to_udp6_sock ||
3bc253c2 540 func_id == BPF_FUNC_skc_to_mptcp_sock ||
1df8f55a
MKL
541 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
542 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
543}
544
88374342 545static bool is_dynptr_ref_function(enum bpf_func_id func_id)
b2d8ef19
DM
546{
547 return func_id == BPF_FUNC_dynptr_data;
548}
549
ab5cfac1 550static bool is_sync_callback_calling_kfunc(u32 btf_id);
f18b03fa 551static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
fde2a388 552
ab5cfac1 553static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
be2ef816
AN
554{
555 return func_id == BPF_FUNC_for_each_map_elem ||
be2ef816
AN
556 func_id == BPF_FUNC_find_vma ||
557 func_id == BPF_FUNC_loop ||
558 func_id == BPF_FUNC_user_ringbuf_drain;
559}
560
fde2a388
AN
561static bool is_async_callback_calling_function(enum bpf_func_id func_id)
562{
563 return func_id == BPF_FUNC_timer_set_callback;
564}
565
ab5cfac1
EZ
566static bool is_callback_calling_function(enum bpf_func_id func_id)
567{
568 return is_sync_callback_calling_function(func_id) ||
569 is_async_callback_calling_function(func_id);
570}
571
572static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
573{
574 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
575 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
576}
577
9bb00b28
YS
578static bool is_storage_get_function(enum bpf_func_id func_id)
579{
580 return func_id == BPF_FUNC_sk_storage_get ||
581 func_id == BPF_FUNC_inode_storage_get ||
582 func_id == BPF_FUNC_task_storage_get ||
583 func_id == BPF_FUNC_cgrp_storage_get;
584}
585
b2d8ef19
DM
586static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
587 const struct bpf_map *map)
588{
589 int ref_obj_uses = 0;
590
591 if (is_ptr_cast_function(func_id))
592 ref_obj_uses++;
593 if (is_acquire_function(func_id, map))
594 ref_obj_uses++;
88374342 595 if (is_dynptr_ref_function(func_id))
b2d8ef19
DM
596 ref_obj_uses++;
597
598 return ref_obj_uses > 1;
599}
600
39491867
BJ
601static bool is_cmpxchg_insn(const struct bpf_insn *insn)
602{
603 return BPF_CLASS(insn->code) == BPF_STX &&
604 BPF_MODE(insn->code) == BPF_ATOMIC &&
605 insn->imm == BPF_CMPXCHG;
606}
607
c25b2ae1
HL
608/* string representation of 'enum bpf_reg_type'
609 *
610 * Note that reg_type_str() can not appear more than once in a single verbose()
611 * statement.
612 */
613static const char *reg_type_str(struct bpf_verifier_env *env,
614 enum bpf_reg_type type)
615{
ef66c547 616 char postfix[16] = {0}, prefix[64] = {0};
c25b2ae1
HL
617 static const char * const str[] = {
618 [NOT_INIT] = "?",
7df5072c 619 [SCALAR_VALUE] = "scalar",
c25b2ae1
HL
620 [PTR_TO_CTX] = "ctx",
621 [CONST_PTR_TO_MAP] = "map_ptr",
622 [PTR_TO_MAP_VALUE] = "map_value",
623 [PTR_TO_STACK] = "fp",
624 [PTR_TO_PACKET] = "pkt",
625 [PTR_TO_PACKET_META] = "pkt_meta",
626 [PTR_TO_PACKET_END] = "pkt_end",
627 [PTR_TO_FLOW_KEYS] = "flow_keys",
628 [PTR_TO_SOCKET] = "sock",
629 [PTR_TO_SOCK_COMMON] = "sock_common",
630 [PTR_TO_TCP_SOCK] = "tcp_sock",
631 [PTR_TO_TP_BUFFER] = "tp_buffer",
632 [PTR_TO_XDP_SOCK] = "xdp_sock",
633 [PTR_TO_BTF_ID] = "ptr_",
c25b2ae1 634 [PTR_TO_MEM] = "mem",
20b2aff4 635 [PTR_TO_BUF] = "buf",
c25b2ae1
HL
636 [PTR_TO_FUNC] = "func",
637 [PTR_TO_MAP_KEY] = "map_key",
27060531 638 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
c25b2ae1
HL
639 };
640
641 if (type & PTR_MAYBE_NULL) {
5844101a 642 if (base_type(type) == PTR_TO_BTF_ID)
c25b2ae1
HL
643 strncpy(postfix, "or_null_", 16);
644 else
645 strncpy(postfix, "_or_null", 16);
646 }
647
9bb00b28 648 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
ef66c547
DV
649 type & MEM_RDONLY ? "rdonly_" : "",
650 type & MEM_RINGBUF ? "ringbuf_" : "",
651 type & MEM_USER ? "user_" : "",
652 type & MEM_PERCPU ? "percpu_" : "",
9bb00b28 653 type & MEM_RCU ? "rcu_" : "",
3f00c523
DV
654 type & PTR_UNTRUSTED ? "untrusted_" : "",
655 type & PTR_TRUSTED ? "trusted_" : ""
ef66c547 656 );
20b2aff4 657
d9439c21 658 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
20b2aff4 659 prefix, str[base_type(type)], postfix);
d9439c21 660 return env->tmp_str_buf;
c25b2ae1 661}
17a52670 662
8efea21d
EC
663static char slot_type_char[] = {
664 [STACK_INVALID] = '?',
665 [STACK_SPILL] = 'r',
666 [STACK_MISC] = 'm',
667 [STACK_ZERO] = '0',
97e03f52 668 [STACK_DYNPTR] = 'd',
06accc87 669 [STACK_ITER] = 'i',
8efea21d
EC
670};
671
4e92024a
AS
672static void print_liveness(struct bpf_verifier_env *env,
673 enum bpf_reg_liveness live)
674{
9242b5f5 675 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
676 verbose(env, "_");
677 if (live & REG_LIVE_READ)
678 verbose(env, "r");
679 if (live & REG_LIVE_WRITTEN)
680 verbose(env, "w");
9242b5f5
AS
681 if (live & REG_LIVE_DONE)
682 verbose(env, "D");
4e92024a
AS
683}
684
79168a66 685static int __get_spi(s32 off)
97e03f52
JK
686{
687 return (-off - 1) / BPF_REG_SIZE;
688}
689
f5b625e5
KKD
690static struct bpf_func_state *func(struct bpf_verifier_env *env,
691 const struct bpf_reg_state *reg)
692{
693 struct bpf_verifier_state *cur = env->cur_state;
694
695 return cur->frame[reg->frameno];
696}
697
97e03f52
JK
698static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
699{
f5b625e5 700 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
97e03f52 701
f5b625e5
KKD
702 /* We need to check that slots between [spi - nr_slots + 1, spi] are
703 * within [0, allocated_stack).
704 *
705 * Please note that the spi grows downwards. For example, a dynptr
706 * takes the size of two stack slots; the first slot will be at
707 * spi and the second slot will be at spi - 1.
708 */
709 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
97e03f52
JK
710}
711
a461f5ad
AN
712static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
713 const char *obj_kind, int nr_slots)
f4d7e40a 714{
79168a66 715 int off, spi;
f4d7e40a 716
79168a66 717 if (!tnum_is_const(reg->var_off)) {
a461f5ad 718 verbose(env, "%s has to be at a constant offset\n", obj_kind);
79168a66
KKD
719 return -EINVAL;
720 }
721
722 off = reg->off + reg->var_off.value;
723 if (off % BPF_REG_SIZE) {
a461f5ad 724 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
79168a66
KKD
725 return -EINVAL;
726 }
727
728 spi = __get_spi(off);
a461f5ad
AN
729 if (spi + 1 < nr_slots) {
730 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
79168a66
KKD
731 return -EINVAL;
732 }
97e03f52 733
a461f5ad 734 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
f5b625e5
KKD
735 return -ERANGE;
736 return spi;
f4d7e40a
AS
737}
738
a461f5ad
AN
739static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
740{
741 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
742}
743
06accc87
AN
744static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
745{
746 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
747}
748
b32a5dae 749static const char *btf_type_name(const struct btf *btf, u32 id)
9e15db66 750{
22dc4a0f 751 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
752}
753
d54e0f6c
AN
754static const char *dynptr_type_str(enum bpf_dynptr_type type)
755{
756 switch (type) {
757 case BPF_DYNPTR_TYPE_LOCAL:
758 return "local";
759 case BPF_DYNPTR_TYPE_RINGBUF:
760 return "ringbuf";
761 case BPF_DYNPTR_TYPE_SKB:
762 return "skb";
763 case BPF_DYNPTR_TYPE_XDP:
764 return "xdp";
765 case BPF_DYNPTR_TYPE_INVALID:
766 return "<invalid>";
767 default:
768 WARN_ONCE(1, "unknown dynptr type %d\n", type);
769 return "<unknown>";
770 }
771}
772
06accc87
AN
773static const char *iter_type_str(const struct btf *btf, u32 btf_id)
774{
775 if (!btf || btf_id == 0)
776 return "<invalid>";
777
778 /* we already validated that type is valid and has conforming name */
b32a5dae 779 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
06accc87
AN
780}
781
782static const char *iter_state_str(enum bpf_iter_state state)
783{
784 switch (state) {
785 case BPF_ITER_STATE_ACTIVE:
786 return "active";
787 case BPF_ITER_STATE_DRAINED:
788 return "drained";
789 case BPF_ITER_STATE_INVALID:
790 return "<invalid>";
791 default:
792 WARN_ONCE(1, "unknown iter state %d\n", state);
793 return "<unknown>";
794 }
795}
796
0f55f9ed
CL
797static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
798{
799 env->scratched_regs |= 1U << regno;
800}
801
802static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
803{
343e5375 804 env->scratched_stack_slots |= 1ULL << spi;
0f55f9ed
CL
805}
806
807static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
808{
809 return (env->scratched_regs >> regno) & 1;
810}
811
812static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
813{
814 return (env->scratched_stack_slots >> regno) & 1;
815}
816
817static bool verifier_state_scratched(const struct bpf_verifier_env *env)
818{
819 return env->scratched_regs || env->scratched_stack_slots;
820}
821
822static void mark_verifier_state_clean(struct bpf_verifier_env *env)
823{
824 env->scratched_regs = 0U;
343e5375 825 env->scratched_stack_slots = 0ULL;
0f55f9ed
CL
826}
827
828/* Used for printing the entire verifier state. */
829static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
830{
831 env->scratched_regs = ~0U;
343e5375 832 env->scratched_stack_slots = ~0ULL;
0f55f9ed
CL
833}
834
97e03f52
JK
835static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
836{
837 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
838 case DYNPTR_TYPE_LOCAL:
839 return BPF_DYNPTR_TYPE_LOCAL;
bc34dee6
JK
840 case DYNPTR_TYPE_RINGBUF:
841 return BPF_DYNPTR_TYPE_RINGBUF;
b5964b96
JK
842 case DYNPTR_TYPE_SKB:
843 return BPF_DYNPTR_TYPE_SKB;
05421aec
JK
844 case DYNPTR_TYPE_XDP:
845 return BPF_DYNPTR_TYPE_XDP;
97e03f52
JK
846 default:
847 return BPF_DYNPTR_TYPE_INVALID;
848 }
849}
850
66e3a13e
JK
851static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
852{
853 switch (type) {
854 case BPF_DYNPTR_TYPE_LOCAL:
855 return DYNPTR_TYPE_LOCAL;
856 case BPF_DYNPTR_TYPE_RINGBUF:
857 return DYNPTR_TYPE_RINGBUF;
858 case BPF_DYNPTR_TYPE_SKB:
859 return DYNPTR_TYPE_SKB;
860 case BPF_DYNPTR_TYPE_XDP:
861 return DYNPTR_TYPE_XDP;
862 default:
863 return 0;
864 }
865}
866
bc34dee6
JK
867static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
868{
869 return type == BPF_DYNPTR_TYPE_RINGBUF;
870}
871
27060531
KKD
872static void __mark_dynptr_reg(struct bpf_reg_state *reg,
873 enum bpf_dynptr_type type,
f8064ab9 874 bool first_slot, int dynptr_id);
27060531
KKD
875
876static void __mark_reg_not_init(const struct bpf_verifier_env *env,
877 struct bpf_reg_state *reg);
878
f8064ab9
KKD
879static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
880 struct bpf_reg_state *sreg1,
27060531
KKD
881 struct bpf_reg_state *sreg2,
882 enum bpf_dynptr_type type)
883{
f8064ab9
KKD
884 int id = ++env->id_gen;
885
886 __mark_dynptr_reg(sreg1, type, true, id);
887 __mark_dynptr_reg(sreg2, type, false, id);
27060531
KKD
888}
889
f8064ab9
KKD
890static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
891 struct bpf_reg_state *reg,
27060531
KKD
892 enum bpf_dynptr_type type)
893{
f8064ab9 894 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
27060531
KKD
895}
896
ef8fc7a0
KKD
897static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
898 struct bpf_func_state *state, int spi);
27060531 899
97e03f52 900static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
361f129f 901 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
97e03f52
JK
902{
903 struct bpf_func_state *state = func(env, reg);
904 enum bpf_dynptr_type type;
361f129f 905 int spi, i, err;
97e03f52 906
79168a66
KKD
907 spi = dynptr_get_spi(env, reg);
908 if (spi < 0)
909 return spi;
97e03f52 910
379d4ba8
KKD
911 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
912 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
913 * to ensure that for the following example:
914 * [d1][d1][d2][d2]
915 * spi 3 2 1 0
916 * So marking spi = 2 should lead to destruction of both d1 and d2. In
917 * case they do belong to same dynptr, second call won't see slot_type
918 * as STACK_DYNPTR and will simply skip destruction.
919 */
920 err = destroy_if_dynptr_stack_slot(env, state, spi);
921 if (err)
922 return err;
923 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
924 if (err)
925 return err;
97e03f52
JK
926
927 for (i = 0; i < BPF_REG_SIZE; i++) {
928 state->stack[spi].slot_type[i] = STACK_DYNPTR;
929 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
930 }
931
932 type = arg_to_dynptr_type(arg_type);
933 if (type == BPF_DYNPTR_TYPE_INVALID)
934 return -EINVAL;
935
f8064ab9 936 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
27060531 937 &state->stack[spi - 1].spilled_ptr, type);
97e03f52 938
bc34dee6
JK
939 if (dynptr_type_refcounted(type)) {
940 /* The id is used to track proper releasing */
361f129f
JK
941 int id;
942
943 if (clone_ref_obj_id)
944 id = clone_ref_obj_id;
945 else
946 id = acquire_reference_state(env, insn_idx);
947
bc34dee6
JK
948 if (id < 0)
949 return id;
950
27060531
KKD
951 state->stack[spi].spilled_ptr.ref_obj_id = id;
952 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
bc34dee6
JK
953 }
954
d6fefa11
KKD
955 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
956 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
957
97e03f52
JK
958 return 0;
959}
960
361f129f 961static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
97e03f52 962{
361f129f 963 int i;
97e03f52
JK
964
965 for (i = 0; i < BPF_REG_SIZE; i++) {
966 state->stack[spi].slot_type[i] = STACK_INVALID;
967 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
968 }
969
27060531
KKD
970 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
971 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
d6fefa11
KKD
972
973 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
974 *
975 * While we don't allow reading STACK_INVALID, it is still possible to
976 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
977 * helpers or insns can do partial read of that part without failing,
978 * but check_stack_range_initialized, check_stack_read_var_off, and
979 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
980 * the slot conservatively. Hence we need to prevent those liveness
981 * marking walks.
982 *
983 * This was not a problem before because STACK_INVALID is only set by
984 * default (where the default reg state has its reg->parent as NULL), or
985 * in clean_live_states after REG_LIVE_DONE (at which point
986 * mark_reg_read won't walk reg->parent chain), but not randomly during
987 * verifier state exploration (like we did above). Hence, for our case
988 * parentage chain will still be live (i.e. reg->parent may be
989 * non-NULL), while earlier reg->parent was NULL, so we need
990 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
991 * done later on reads or by mark_dynptr_read as well to unnecessary
992 * mark registers in verifier state.
993 */
994 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
995 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
361f129f
JK
996}
997
998static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
999{
1000 struct bpf_func_state *state = func(env, reg);
1001 int spi, ref_obj_id, i;
1002
1003 spi = dynptr_get_spi(env, reg);
1004 if (spi < 0)
1005 return spi;
1006
1007 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1008 invalidate_dynptr(env, state, spi);
1009 return 0;
1010 }
1011
1012 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1013
1014 /* If the dynptr has a ref_obj_id, then we need to invalidate
1015 * two things:
1016 *
1017 * 1) Any dynptrs with a matching ref_obj_id (clones)
1018 * 2) Any slices derived from this dynptr.
1019 */
1020
1021 /* Invalidate any slices associated with this dynptr */
1022 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1023
1024 /* Invalidate any dynptr clones */
1025 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1026 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1027 continue;
1028
1029 /* it should always be the case that if the ref obj id
1030 * matches then the stack slot also belongs to a
1031 * dynptr
1032 */
1033 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1034 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1035 return -EFAULT;
1036 }
1037 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1038 invalidate_dynptr(env, state, i);
1039 }
d6fefa11 1040
97e03f52
JK
1041 return 0;
1042}
1043
ef8fc7a0
KKD
1044static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1045 struct bpf_reg_state *reg);
1046
dbd8d228
KKD
1047static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1048{
1049 if (!env->allow_ptr_leaks)
1050 __mark_reg_not_init(env, reg);
1051 else
1052 __mark_reg_unknown(env, reg);
1053}
1054
ef8fc7a0
KKD
1055static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1056 struct bpf_func_state *state, int spi)
97e03f52 1057{
f8064ab9
KKD
1058 struct bpf_func_state *fstate;
1059 struct bpf_reg_state *dreg;
1060 int i, dynptr_id;
27060531 1061
ef8fc7a0
KKD
1062 /* We always ensure that STACK_DYNPTR is never set partially,
1063 * hence just checking for slot_type[0] is enough. This is
1064 * different for STACK_SPILL, where it may be only set for
1065 * 1 byte, so code has to use is_spilled_reg.
1066 */
1067 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1068 return 0;
97e03f52 1069
ef8fc7a0
KKD
1070 /* Reposition spi to first slot */
1071 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1072 spi = spi + 1;
1073
1074 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1075 verbose(env, "cannot overwrite referenced dynptr\n");
1076 return -EINVAL;
1077 }
1078
1079 mark_stack_slot_scratched(env, spi);
1080 mark_stack_slot_scratched(env, spi - 1);
97e03f52 1081
ef8fc7a0 1082 /* Writing partially to one dynptr stack slot destroys both. */
97e03f52 1083 for (i = 0; i < BPF_REG_SIZE; i++) {
ef8fc7a0
KKD
1084 state->stack[spi].slot_type[i] = STACK_INVALID;
1085 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
97e03f52
JK
1086 }
1087
f8064ab9
KKD
1088 dynptr_id = state->stack[spi].spilled_ptr.id;
1089 /* Invalidate any slices associated with this dynptr */
1090 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1091 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1092 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1093 continue;
dbd8d228
KKD
1094 if (dreg->dynptr_id == dynptr_id)
1095 mark_reg_invalid(env, dreg);
f8064ab9 1096 }));
ef8fc7a0
KKD
1097
1098 /* Do not release reference state, we are destroying dynptr on stack,
1099 * not using some helper to release it. Just reset register.
1100 */
1101 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1102 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1103
1104 /* Same reason as unmark_stack_slots_dynptr above */
1105 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1106 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1107
1108 return 0;
1109}
1110
7e0dac28 1111static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
97e03f52 1112{
7e0dac28
JK
1113 int spi;
1114
27060531
KKD
1115 if (reg->type == CONST_PTR_TO_DYNPTR)
1116 return false;
97e03f52 1117
7e0dac28
JK
1118 spi = dynptr_get_spi(env, reg);
1119
1120 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1121 * error because this just means the stack state hasn't been updated yet.
1122 * We will do check_mem_access to check and update stack bounds later.
f5b625e5 1123 */
7e0dac28
JK
1124 if (spi < 0 && spi != -ERANGE)
1125 return false;
1126
1127 /* We don't need to check if the stack slots are marked by previous
1128 * dynptr initializations because we allow overwriting existing unreferenced
1129 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1130 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1131 * touching are completely destructed before we reinitialize them for a new
1132 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1133 * instead of delaying it until the end where the user will get "Unreleased
379d4ba8
KKD
1134 * reference" error.
1135 */
97e03f52
JK
1136 return true;
1137}
1138
7e0dac28 1139static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
97e03f52
JK
1140{
1141 struct bpf_func_state *state = func(env, reg);
7e0dac28 1142 int i, spi;
97e03f52 1143
7e0dac28
JK
1144 /* This already represents first slot of initialized bpf_dynptr.
1145 *
1146 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1147 * check_func_arg_reg_off's logic, so we don't need to check its
1148 * offset and alignment.
1149 */
27060531
KKD
1150 if (reg->type == CONST_PTR_TO_DYNPTR)
1151 return true;
1152
7e0dac28 1153 spi = dynptr_get_spi(env, reg);
79168a66
KKD
1154 if (spi < 0)
1155 return false;
f5b625e5 1156 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
97e03f52
JK
1157 return false;
1158
1159 for (i = 0; i < BPF_REG_SIZE; i++) {
1160 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1161 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1162 return false;
1163 }
1164
e9e315b4
RS
1165 return true;
1166}
1167
6b75bd3d
KKD
1168static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1169 enum bpf_arg_type arg_type)
e9e315b4
RS
1170{
1171 struct bpf_func_state *state = func(env, reg);
1172 enum bpf_dynptr_type dynptr_type;
27060531 1173 int spi;
e9e315b4 1174
97e03f52
JK
1175 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1176 if (arg_type == ARG_PTR_TO_DYNPTR)
1177 return true;
1178
e9e315b4 1179 dynptr_type = arg_to_dynptr_type(arg_type);
27060531
KKD
1180 if (reg->type == CONST_PTR_TO_DYNPTR) {
1181 return reg->dynptr.type == dynptr_type;
1182 } else {
79168a66
KKD
1183 spi = dynptr_get_spi(env, reg);
1184 if (spi < 0)
1185 return false;
27060531
KKD
1186 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1187 }
97e03f52
JK
1188}
1189
06accc87
AN
1190static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1191
dfab99df
CZ
1192static bool in_rcu_cs(struct bpf_verifier_env *env);
1193
1194static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1195
06accc87 1196static int mark_stack_slots_iter(struct bpf_verifier_env *env,
dfab99df 1197 struct bpf_kfunc_call_arg_meta *meta,
06accc87
AN
1198 struct bpf_reg_state *reg, int insn_idx,
1199 struct btf *btf, u32 btf_id, int nr_slots)
1200{
1201 struct bpf_func_state *state = func(env, reg);
1202 int spi, i, j, id;
1203
1204 spi = iter_get_spi(env, reg, nr_slots);
1205 if (spi < 0)
1206 return spi;
1207
1208 id = acquire_reference_state(env, insn_idx);
1209 if (id < 0)
1210 return id;
1211
1212 for (i = 0; i < nr_slots; i++) {
1213 struct bpf_stack_state *slot = &state->stack[spi - i];
1214 struct bpf_reg_state *st = &slot->spilled_ptr;
1215
1216 __mark_reg_known_zero(st);
1217 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
dfab99df
CZ
1218 if (is_kfunc_rcu_protected(meta)) {
1219 if (in_rcu_cs(env))
1220 st->type |= MEM_RCU;
1221 else
1222 st->type |= PTR_UNTRUSTED;
1223 }
06accc87
AN
1224 st->live |= REG_LIVE_WRITTEN;
1225 st->ref_obj_id = i == 0 ? id : 0;
1226 st->iter.btf = btf;
1227 st->iter.btf_id = btf_id;
1228 st->iter.state = BPF_ITER_STATE_ACTIVE;
1229 st->iter.depth = 0;
1230
1231 for (j = 0; j < BPF_REG_SIZE; j++)
1232 slot->slot_type[j] = STACK_ITER;
1233
1234 mark_stack_slot_scratched(env, spi - i);
1235 }
1236
1237 return 0;
1238}
1239
1240static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1241 struct bpf_reg_state *reg, int nr_slots)
1242{
1243 struct bpf_func_state *state = func(env, reg);
1244 int spi, i, j;
1245
1246 spi = iter_get_spi(env, reg, nr_slots);
1247 if (spi < 0)
1248 return spi;
1249
1250 for (i = 0; i < nr_slots; i++) {
1251 struct bpf_stack_state *slot = &state->stack[spi - i];
1252 struct bpf_reg_state *st = &slot->spilled_ptr;
1253
1254 if (i == 0)
1255 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1256
1257 __mark_reg_not_init(env, st);
1258
1259 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1260 st->live |= REG_LIVE_WRITTEN;
1261
1262 for (j = 0; j < BPF_REG_SIZE; j++)
1263 slot->slot_type[j] = STACK_INVALID;
1264
1265 mark_stack_slot_scratched(env, spi - i);
1266 }
1267
1268 return 0;
1269}
1270
1271static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1272 struct bpf_reg_state *reg, int nr_slots)
1273{
1274 struct bpf_func_state *state = func(env, reg);
1275 int spi, i, j;
1276
1277 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1278 * will do check_mem_access to check and update stack bounds later, so
1279 * return true for that case.
1280 */
1281 spi = iter_get_spi(env, reg, nr_slots);
1282 if (spi == -ERANGE)
1283 return true;
1284 if (spi < 0)
1285 return false;
1286
1287 for (i = 0; i < nr_slots; i++) {
1288 struct bpf_stack_state *slot = &state->stack[spi - i];
1289
1290 for (j = 0; j < BPF_REG_SIZE; j++)
1291 if (slot->slot_type[j] == STACK_ITER)
1292 return false;
1293 }
1294
1295 return true;
1296}
1297
dfab99df 1298static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
06accc87
AN
1299 struct btf *btf, u32 btf_id, int nr_slots)
1300{
1301 struct bpf_func_state *state = func(env, reg);
1302 int spi, i, j;
1303
1304 spi = iter_get_spi(env, reg, nr_slots);
1305 if (spi < 0)
dfab99df 1306 return -EINVAL;
06accc87
AN
1307
1308 for (i = 0; i < nr_slots; i++) {
1309 struct bpf_stack_state *slot = &state->stack[spi - i];
1310 struct bpf_reg_state *st = &slot->spilled_ptr;
1311
dfab99df
CZ
1312 if (st->type & PTR_UNTRUSTED)
1313 return -EPROTO;
06accc87
AN
1314 /* only main (first) slot has ref_obj_id set */
1315 if (i == 0 && !st->ref_obj_id)
dfab99df 1316 return -EINVAL;
06accc87 1317 if (i != 0 && st->ref_obj_id)
dfab99df 1318 return -EINVAL;
06accc87 1319 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
dfab99df 1320 return -EINVAL;
06accc87
AN
1321
1322 for (j = 0; j < BPF_REG_SIZE; j++)
1323 if (slot->slot_type[j] != STACK_ITER)
dfab99df 1324 return -EINVAL;
06accc87
AN
1325 }
1326
dfab99df 1327 return 0;
06accc87
AN
1328}
1329
1330/* Check if given stack slot is "special":
1331 * - spilled register state (STACK_SPILL);
1332 * - dynptr state (STACK_DYNPTR);
1333 * - iter state (STACK_ITER).
1334 */
1335static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1336{
1337 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1338
1339 switch (type) {
1340 case STACK_SPILL:
1341 case STACK_DYNPTR:
1342 case STACK_ITER:
1343 return true;
1344 case STACK_INVALID:
1345 case STACK_MISC:
1346 case STACK_ZERO:
1347 return false;
1348 default:
1349 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1350 return true;
1351 }
1352}
1353
27113c59
MKL
1354/* The reg state of a pointer or a bounded scalar was saved when
1355 * it was spilled to the stack.
1356 */
1357static bool is_spilled_reg(const struct bpf_stack_state *stack)
1358{
1359 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1360}
1361
407958a0
AN
1362static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1363{
1364 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1365 stack->spilled_ptr.type == SCALAR_VALUE;
1366}
1367
354e8f19
MKL
1368static void scrub_spilled_slot(u8 *stype)
1369{
1370 if (*stype != STACK_INVALID)
1371 *stype = STACK_MISC;
1372}
1373
72f8a1de
AN
1374static void print_scalar_ranges(struct bpf_verifier_env *env,
1375 const struct bpf_reg_state *reg,
1376 const char **sep)
1377{
1378 struct {
1379 const char *name;
1380 u64 val;
1381 bool omit;
1382 } minmaxs[] = {
1383 {"smin", reg->smin_value, reg->smin_value == S64_MIN},
1384 {"smax", reg->smax_value, reg->smax_value == S64_MAX},
1385 {"umin", reg->umin_value, reg->umin_value == 0},
1386 {"umax", reg->umax_value, reg->umax_value == U64_MAX},
1387 {"smin32", (s64)reg->s32_min_value, reg->s32_min_value == S32_MIN},
1388 {"smax32", (s64)reg->s32_max_value, reg->s32_max_value == S32_MAX},
1389 {"umin32", reg->u32_min_value, reg->u32_min_value == 0},
1390 {"umax32", reg->u32_max_value, reg->u32_max_value == U32_MAX},
1391 }, *m1, *m2, *mend = &minmaxs[ARRAY_SIZE(minmaxs)];
1392 bool neg1, neg2;
1393
1394 for (m1 = &minmaxs[0]; m1 < mend; m1++) {
1395 if (m1->omit)
1396 continue;
1397
1398 neg1 = m1->name[0] == 's' && (s64)m1->val < 0;
1399
1400 verbose(env, "%s%s=", *sep, m1->name);
1401 *sep = ",";
1402
1403 for (m2 = m1 + 2; m2 < mend; m2 += 2) {
1404 if (m2->omit || m2->val != m1->val)
1405 continue;
1406 /* don't mix negatives with positives */
1407 neg2 = m2->name[0] == 's' && (s64)m2->val < 0;
1408 if (neg2 != neg1)
1409 continue;
1410 m2->omit = true;
1411 verbose(env, "%s=", m2->name);
1412 }
1413
1414 verbose(env, m1->name[0] == 's' ? "%lld" : "%llu", m1->val);
1415 }
1416}
1417
61bd5218 1418static void print_verifier_state(struct bpf_verifier_env *env,
0f55f9ed
CL
1419 const struct bpf_func_state *state,
1420 bool print_all)
17a52670 1421{
f4d7e40a 1422 const struct bpf_reg_state *reg;
17a52670
AS
1423 enum bpf_reg_type t;
1424 int i;
1425
f4d7e40a
AS
1426 if (state->frameno)
1427 verbose(env, " frame%d:", state->frameno);
17a52670 1428 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
1429 reg = &state->regs[i];
1430 t = reg->type;
17a52670
AS
1431 if (t == NOT_INIT)
1432 continue;
0f55f9ed
CL
1433 if (!print_all && !reg_scratched(env, i))
1434 continue;
4e92024a
AS
1435 verbose(env, " R%d", i);
1436 print_liveness(env, reg->live);
7df5072c 1437 verbose(env, "=");
b5dc0163
AS
1438 if (t == SCALAR_VALUE && reg->precise)
1439 verbose(env, "P");
f1174f77
EC
1440 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1441 tnum_is_const(reg->var_off)) {
1442 /* reg->off should be 0 for SCALAR_VALUE */
7df5072c 1443 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
61bd5218 1444 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 1445 } else {
7df5072c
ML
1446 const char *sep = "";
1447
1448 verbose(env, "%s", reg_type_str(env, t));
5844101a 1449 if (base_type(t) == PTR_TO_BTF_ID)
b32a5dae 1450 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
7df5072c
ML
1451 verbose(env, "(");
1452/*
1453 * _a stands for append, was shortened to avoid multiline statements below.
1454 * This macro is used to output a comma separated list of attributes.
1455 */
1456#define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1457
1458 if (reg->id)
1459 verbose_a("id=%d", reg->id);
a28ace78 1460 if (reg->ref_obj_id)
7df5072c 1461 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
6a3cd331
DM
1462 if (type_is_non_owning_ref(reg->type))
1463 verbose_a("%s", "non_own_ref");
f1174f77 1464 if (t != SCALAR_VALUE)
7df5072c 1465 verbose_a("off=%d", reg->off);
de8f3a83 1466 if (type_is_pkt_pointer(t))
7df5072c 1467 verbose_a("r=%d", reg->range);
c25b2ae1
HL
1468 else if (base_type(t) == CONST_PTR_TO_MAP ||
1469 base_type(t) == PTR_TO_MAP_KEY ||
1470 base_type(t) == PTR_TO_MAP_VALUE)
7df5072c
ML
1471 verbose_a("ks=%d,vs=%d",
1472 reg->map_ptr->key_size,
1473 reg->map_ptr->value_size);
7d1238f2
EC
1474 if (tnum_is_const(reg->var_off)) {
1475 /* Typically an immediate SCALAR_VALUE, but
1476 * could be a pointer whose offset is too big
1477 * for reg->off
1478 */
7df5072c 1479 verbose_a("imm=%llx", reg->var_off.value);
7d1238f2 1480 } else {
72f8a1de 1481 print_scalar_ranges(env, reg, &sep);
7d1238f2
EC
1482 if (!tnum_is_unknown(reg->var_off)) {
1483 char tn_buf[48];
f1174f77 1484
7d1238f2 1485 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7df5072c 1486 verbose_a("var_off=%s", tn_buf);
7d1238f2 1487 }
f1174f77 1488 }
7df5072c
ML
1489#undef verbose_a
1490
61bd5218 1491 verbose(env, ")");
f1174f77 1492 }
17a52670 1493 }
638f5b90 1494 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
1495 char types_buf[BPF_REG_SIZE + 1];
1496 bool valid = false;
1497 int j;
1498
1499 for (j = 0; j < BPF_REG_SIZE; j++) {
1500 if (state->stack[i].slot_type[j] != STACK_INVALID)
1501 valid = true;
d54e0f6c 1502 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
8efea21d
EC
1503 }
1504 types_buf[BPF_REG_SIZE] = 0;
1505 if (!valid)
1506 continue;
0f55f9ed
CL
1507 if (!print_all && !stack_slot_scratched(env, i))
1508 continue;
d54e0f6c
AN
1509 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1510 case STACK_SPILL:
b5dc0163
AS
1511 reg = &state->stack[i].spilled_ptr;
1512 t = reg->type;
d54e0f6c
AN
1513
1514 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1515 print_liveness(env, reg->live);
7df5072c 1516 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
b5dc0163
AS
1517 if (t == SCALAR_VALUE && reg->precise)
1518 verbose(env, "P");
1519 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1520 verbose(env, "%lld", reg->var_off.value + reg->off);
d54e0f6c
AN
1521 break;
1522 case STACK_DYNPTR:
1523 i += BPF_DYNPTR_NR_SLOTS - 1;
1524 reg = &state->stack[i].spilled_ptr;
1525
1526 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1527 print_liveness(env, reg->live);
1528 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1529 if (reg->ref_obj_id)
1530 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1531 break;
06accc87
AN
1532 case STACK_ITER:
1533 /* only main slot has ref_obj_id set; skip others */
1534 reg = &state->stack[i].spilled_ptr;
1535 if (!reg->ref_obj_id)
1536 continue;
1537
1538 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1539 print_liveness(env, reg->live);
1540 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1541 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1542 reg->ref_obj_id, iter_state_str(reg->iter.state),
1543 reg->iter.depth);
1544 break;
d54e0f6c
AN
1545 case STACK_MISC:
1546 case STACK_ZERO:
1547 default:
1548 reg = &state->stack[i].spilled_ptr;
1549
1550 for (j = 0; j < BPF_REG_SIZE; j++)
1551 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1552 types_buf[BPF_REG_SIZE] = 0;
1553
1554 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1555 print_liveness(env, reg->live);
8efea21d 1556 verbose(env, "=%s", types_buf);
d54e0f6c 1557 break;
b5dc0163 1558 }
17a52670 1559 }
fd978bf7
JS
1560 if (state->acquired_refs && state->refs[0].id) {
1561 verbose(env, " refs=%d", state->refs[0].id);
1562 for (i = 1; i < state->acquired_refs; i++)
1563 if (state->refs[i].id)
1564 verbose(env, ",%d", state->refs[i].id);
1565 }
bfc6bb74
AS
1566 if (state->in_callback_fn)
1567 verbose(env, " cb");
1568 if (state->in_async_callback_fn)
1569 verbose(env, " async_cb");
61bd5218 1570 verbose(env, "\n");
1a8a315f
AN
1571 if (!print_all)
1572 mark_verifier_state_clean(env);
17a52670
AS
1573}
1574
2e576648
CL
1575static inline u32 vlog_alignment(u32 pos)
1576{
1577 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1578 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1579}
1580
1581static void print_insn_state(struct bpf_verifier_env *env,
1582 const struct bpf_func_state *state)
1583{
12166409 1584 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
2e576648 1585 /* remove new line character */
12166409
AN
1586 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1587 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
2e576648
CL
1588 } else {
1589 verbose(env, "%d:", env->insn_idx);
1590 }
1591 print_verifier_state(env, state, false);
17a52670
AS
1592}
1593
c69431aa
LB
1594/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1595 * small to hold src. This is different from krealloc since we don't want to preserve
1596 * the contents of dst.
1597 *
1598 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1599 * not be allocated.
638f5b90 1600 */
c69431aa 1601static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 1602{
45435d8d
KC
1603 size_t alloc_bytes;
1604 void *orig = dst;
c69431aa
LB
1605 size_t bytes;
1606
1607 if (ZERO_OR_NULL_PTR(src))
1608 goto out;
1609
1610 if (unlikely(check_mul_overflow(n, size, &bytes)))
1611 return NULL;
1612
45435d8d
KC
1613 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1614 dst = krealloc(orig, alloc_bytes, flags);
1615 if (!dst) {
1616 kfree(orig);
1617 return NULL;
c69431aa
LB
1618 }
1619
1620 memcpy(dst, src, bytes);
1621out:
1622 return dst ? dst : ZERO_SIZE_PTR;
1623}
1624
1625/* resize an array from old_n items to new_n items. the array is reallocated if it's too
1626 * small to hold new_n items. new items are zeroed out if the array grows.
1627 *
1628 * Contrary to krealloc_array, does not free arr if new_n is zero.
1629 */
1630static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1631{
ceb35b66 1632 size_t alloc_size;
42378a9c
KC
1633 void *new_arr;
1634
c69431aa
LB
1635 if (!new_n || old_n == new_n)
1636 goto out;
1637
ceb35b66
KC
1638 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1639 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
42378a9c
KC
1640 if (!new_arr) {
1641 kfree(arr);
c69431aa 1642 return NULL;
42378a9c
KC
1643 }
1644 arr = new_arr;
c69431aa
LB
1645
1646 if (new_n > old_n)
1647 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1648
1649out:
1650 return arr ? arr : ZERO_SIZE_PTR;
1651}
1652
1653static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1654{
1655 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1656 sizeof(struct bpf_reference_state), GFP_KERNEL);
1657 if (!dst->refs)
1658 return -ENOMEM;
1659
1660 dst->acquired_refs = src->acquired_refs;
1661 return 0;
1662}
1663
1664static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1665{
1666 size_t n = src->allocated_stack / BPF_REG_SIZE;
1667
1668 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1669 GFP_KERNEL);
1670 if (!dst->stack)
1671 return -ENOMEM;
1672
1673 dst->allocated_stack = src->allocated_stack;
1674 return 0;
1675}
1676
1677static int resize_reference_state(struct bpf_func_state *state, size_t n)
1678{
1679 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1680 sizeof(struct bpf_reference_state));
1681 if (!state->refs)
1682 return -ENOMEM;
1683
1684 state->acquired_refs = n;
1685 return 0;
1686}
1687
1688static int grow_stack_state(struct bpf_func_state *state, int size)
1689{
1690 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1691
1692 if (old_n >= n)
1693 return 0;
1694
1695 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1696 if (!state->stack)
1697 return -ENOMEM;
1698
1699 state->allocated_stack = size;
1700 return 0;
fd978bf7
JS
1701}
1702
1703/* Acquire a pointer id from the env and update the state->refs to include
1704 * this new pointer reference.
1705 * On success, returns a valid pointer id to associate with the register
1706 * On failure, returns a negative errno.
638f5b90 1707 */
fd978bf7 1708static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 1709{
fd978bf7
JS
1710 struct bpf_func_state *state = cur_func(env);
1711 int new_ofs = state->acquired_refs;
1712 int id, err;
1713
c69431aa 1714 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
1715 if (err)
1716 return err;
1717 id = ++env->id_gen;
1718 state->refs[new_ofs].id = id;
1719 state->refs[new_ofs].insn_idx = insn_idx;
9d9d00ac 1720 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
638f5b90 1721
fd978bf7
JS
1722 return id;
1723}
1724
1725/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 1726static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
1727{
1728 int i, last_idx;
1729
fd978bf7
JS
1730 last_idx = state->acquired_refs - 1;
1731 for (i = 0; i < state->acquired_refs; i++) {
1732 if (state->refs[i].id == ptr_id) {
9d9d00ac
KKD
1733 /* Cannot release caller references in callbacks */
1734 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1735 return -EINVAL;
fd978bf7
JS
1736 if (last_idx && i != last_idx)
1737 memcpy(&state->refs[i], &state->refs[last_idx],
1738 sizeof(*state->refs));
1739 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1740 state->acquired_refs--;
638f5b90 1741 return 0;
638f5b90 1742 }
638f5b90 1743 }
46f8bc92 1744 return -EINVAL;
fd978bf7
JS
1745}
1746
f4d7e40a
AS
1747static void free_func_state(struct bpf_func_state *state)
1748{
5896351e
AS
1749 if (!state)
1750 return;
fd978bf7 1751 kfree(state->refs);
f4d7e40a
AS
1752 kfree(state->stack);
1753 kfree(state);
1754}
1755
b5dc0163
AS
1756static void clear_jmp_history(struct bpf_verifier_state *state)
1757{
1758 kfree(state->jmp_history);
1759 state->jmp_history = NULL;
1760 state->jmp_history_cnt = 0;
1761}
1762
1969db47
AS
1763static void free_verifier_state(struct bpf_verifier_state *state,
1764 bool free_self)
638f5b90 1765{
f4d7e40a
AS
1766 int i;
1767
1768 for (i = 0; i <= state->curframe; i++) {
1769 free_func_state(state->frame[i]);
1770 state->frame[i] = NULL;
1771 }
b5dc0163 1772 clear_jmp_history(state);
1969db47
AS
1773 if (free_self)
1774 kfree(state);
638f5b90
AS
1775}
1776
1777/* copy verifier state from src to dst growing dst stack space
1778 * when necessary to accommodate larger src stack
1779 */
f4d7e40a
AS
1780static int copy_func_state(struct bpf_func_state *dst,
1781 const struct bpf_func_state *src)
638f5b90
AS
1782{
1783 int err;
1784
fd978bf7
JS
1785 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1786 err = copy_reference_state(dst, src);
638f5b90
AS
1787 if (err)
1788 return err;
638f5b90
AS
1789 return copy_stack_state(dst, src);
1790}
1791
f4d7e40a
AS
1792static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1793 const struct bpf_verifier_state *src)
1794{
1795 struct bpf_func_state *dst;
1796 int i, err;
1797
06ab6a50
LB
1798 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1799 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1800 GFP_USER);
1801 if (!dst_state->jmp_history)
1802 return -ENOMEM;
b5dc0163
AS
1803 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1804
f18b03fa
KKD
1805 /* if dst has more stack frames then src frame, free them, this is also
1806 * necessary in case of exceptional exits using bpf_throw.
1807 */
f4d7e40a
AS
1808 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1809 free_func_state(dst_state->frame[i]);
1810 dst_state->frame[i] = NULL;
1811 }
979d63d5 1812 dst_state->speculative = src->speculative;
9bb00b28 1813 dst_state->active_rcu_lock = src->active_rcu_lock;
f4d7e40a 1814 dst_state->curframe = src->curframe;
d0d78c1d
KKD
1815 dst_state->active_lock.ptr = src->active_lock.ptr;
1816 dst_state->active_lock.id = src->active_lock.id;
2589726d
AS
1817 dst_state->branches = src->branches;
1818 dst_state->parent = src->parent;
b5dc0163
AS
1819 dst_state->first_insn_idx = src->first_insn_idx;
1820 dst_state->last_insn_idx = src->last_insn_idx;
2793a8b0 1821 dst_state->dfs_depth = src->dfs_depth;
ab5cfac1 1822 dst_state->callback_unroll_depth = src->callback_unroll_depth;
2a099282 1823 dst_state->used_as_loop_entry = src->used_as_loop_entry;
f4d7e40a
AS
1824 for (i = 0; i <= src->curframe; i++) {
1825 dst = dst_state->frame[i];
1826 if (!dst) {
1827 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1828 if (!dst)
1829 return -ENOMEM;
1830 dst_state->frame[i] = dst;
1831 }
1832 err = copy_func_state(dst, src->frame[i]);
1833 if (err)
1834 return err;
1835 }
1836 return 0;
1837}
1838
3c4e420c
EZ
1839static u32 state_htab_size(struct bpf_verifier_env *env)
1840{
1841 return env->prog->len;
1842}
1843
1844static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1845{
1846 struct bpf_verifier_state *cur = env->cur_state;
1847 struct bpf_func_state *state = cur->frame[cur->curframe];
1848
1849 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1850}
1851
4c97259a
EZ
1852static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1853{
1854 int fr;
1855
1856 if (a->curframe != b->curframe)
1857 return false;
1858
1859 for (fr = a->curframe; fr >= 0; fr--)
1860 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1861 return false;
1862
1863 return true;
1864}
1865
2a099282
EZ
1866/* Open coded iterators allow back-edges in the state graph in order to
1867 * check unbounded loops that iterators.
1868 *
1869 * In is_state_visited() it is necessary to know if explored states are
1870 * part of some loops in order to decide whether non-exact states
1871 * comparison could be used:
1872 * - non-exact states comparison establishes sub-state relation and uses
1873 * read and precision marks to do so, these marks are propagated from
1874 * children states and thus are not guaranteed to be final in a loop;
1875 * - exact states comparison just checks if current and explored states
1876 * are identical (and thus form a back-edge).
1877 *
1878 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1879 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1880 * algorithm for loop structure detection and gives an overview of
1881 * relevant terminology. It also has helpful illustrations.
1882 *
1883 * [1] https://api.semanticscholar.org/CorpusID:15784067
1884 *
1885 * We use a similar algorithm but because loop nested structure is
1886 * irrelevant for verifier ours is significantly simpler and resembles
1887 * strongly connected components algorithm from Sedgewick's textbook.
1888 *
1889 * Define topmost loop entry as a first node of the loop traversed in a
1890 * depth first search starting from initial state. The goal of the loop
1891 * tracking algorithm is to associate topmost loop entries with states
1892 * derived from these entries.
1893 *
1894 * For each step in the DFS states traversal algorithm needs to identify
1895 * the following situations:
1896 *
1897 * initial initial initial
1898 * | | |
1899 * V V V
1900 * ... ... .---------> hdr
1901 * | | | |
1902 * V V | V
1903 * cur .-> succ | .------...
1904 * | | | | | |
1905 * V | V | V V
1906 * succ '-- cur | ... ...
1907 * | | |
1908 * | V V
1909 * | succ <- cur
1910 * | |
1911 * | V
1912 * | ...
1913 * | |
1914 * '----'
1915 *
1916 * (A) successor state of cur (B) successor state of cur or it's entry
1917 * not yet traversed are in current DFS path, thus cur and succ
1918 * are members of the same outermost loop
1919 *
1920 * initial initial
1921 * | |
1922 * V V
1923 * ... ...
1924 * | |
1925 * V V
1926 * .------... .------...
1927 * | | | |
1928 * V V V V
1929 * .-> hdr ... ... ...
1930 * | | | | |
1931 * | V V V V
1932 * | succ <- cur succ <- cur
1933 * | | |
1934 * | V V
1935 * | ... ...
1936 * | | |
1937 * '----' exit
1938 *
1939 * (C) successor state of cur is a part of some loop but this loop
1940 * does not include cur or successor state is not in a loop at all.
1941 *
1942 * Algorithm could be described as the following python code:
1943 *
1944 * traversed = set() # Set of traversed nodes
1945 * entries = {} # Mapping from node to loop entry
1946 * depths = {} # Depth level assigned to graph node
1947 * path = set() # Current DFS path
1948 *
1949 * # Find outermost loop entry known for n
1950 * def get_loop_entry(n):
1951 * h = entries.get(n, None)
1952 * while h in entries and entries[h] != h:
1953 * h = entries[h]
1954 * return h
1955 *
1956 * # Update n's loop entry if h's outermost entry comes
1957 * # before n's outermost entry in current DFS path.
1958 * def update_loop_entry(n, h):
1959 * n1 = get_loop_entry(n) or n
1960 * h1 = get_loop_entry(h) or h
1961 * if h1 in path and depths[h1] <= depths[n1]:
1962 * entries[n] = h1
1963 *
1964 * def dfs(n, depth):
1965 * traversed.add(n)
1966 * path.add(n)
1967 * depths[n] = depth
1968 * for succ in G.successors(n):
1969 * if succ not in traversed:
1970 * # Case A: explore succ and update cur's loop entry
1971 * # only if succ's entry is in current DFS path.
1972 * dfs(succ, depth + 1)
1973 * h = get_loop_entry(succ)
1974 * update_loop_entry(n, h)
1975 * else:
1976 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1977 * update_loop_entry(n, succ)
1978 * path.remove(n)
1979 *
1980 * To adapt this algorithm for use with verifier:
1981 * - use st->branch == 0 as a signal that DFS of succ had been finished
1982 * and cur's loop entry has to be updated (case A), handle this in
1983 * update_branch_counts();
1984 * - use st->branch > 0 as a signal that st is in the current DFS path;
1985 * - handle cases B and C in is_state_visited();
1986 * - update topmost loop entry for intermediate states in get_loop_entry().
1987 */
1988static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1989{
1990 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1991
1992 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1993 topmost = topmost->loop_entry;
1994 /* Update loop entries for intermediate states to avoid this
1995 * traversal in future get_loop_entry() calls.
1996 */
1997 while (st && st->loop_entry != topmost) {
1998 old = st->loop_entry;
1999 st->loop_entry = topmost;
2000 st = old;
2001 }
2002 return topmost;
2003}
2004
2005static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
2006{
2007 struct bpf_verifier_state *cur1, *hdr1;
2008
2009 cur1 = get_loop_entry(cur) ?: cur;
2010 hdr1 = get_loop_entry(hdr) ?: hdr;
2011 /* The head1->branches check decides between cases B and C in
2012 * comment for get_loop_entry(). If hdr1->branches == 0 then
2013 * head's topmost loop entry is not in current DFS path,
2014 * hence 'cur' and 'hdr' are not in the same loop and there is
2015 * no need to update cur->loop_entry.
2016 */
2017 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
2018 cur->loop_entry = hdr;
2019 hdr->used_as_loop_entry = true;
2020 }
2021}
2022
2589726d
AS
2023static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2024{
2025 while (st) {
2026 u32 br = --st->branches;
2027
2a099282
EZ
2028 /* br == 0 signals that DFS exploration for 'st' is finished,
2029 * thus it is necessary to update parent's loop entry if it
2030 * turned out that st is a part of some loop.
2031 * This is a part of 'case A' in get_loop_entry() comment.
2032 */
2033 if (br == 0 && st->parent && st->loop_entry)
2034 update_loop_entry(st->parent, st->loop_entry);
2035
2589726d
AS
2036 /* WARN_ON(br > 1) technically makes sense here,
2037 * but see comment in push_stack(), hence:
2038 */
2039 WARN_ONCE((int)br < 0,
2040 "BUG update_branch_counts:branches_to_explore=%d\n",
2041 br);
2042 if (br)
2043 break;
2044 st = st->parent;
2045 }
2046}
2047
638f5b90 2048static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 2049 int *insn_idx, bool pop_log)
638f5b90
AS
2050{
2051 struct bpf_verifier_state *cur = env->cur_state;
2052 struct bpf_verifier_stack_elem *elem, *head = env->head;
2053 int err;
17a52670
AS
2054
2055 if (env->head == NULL)
638f5b90 2056 return -ENOENT;
17a52670 2057
638f5b90
AS
2058 if (cur) {
2059 err = copy_verifier_state(cur, &head->st);
2060 if (err)
2061 return err;
2062 }
6f8a57cc
AN
2063 if (pop_log)
2064 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
2065 if (insn_idx)
2066 *insn_idx = head->insn_idx;
17a52670 2067 if (prev_insn_idx)
638f5b90
AS
2068 *prev_insn_idx = head->prev_insn_idx;
2069 elem = head->next;
1969db47 2070 free_verifier_state(&head->st, false);
638f5b90 2071 kfree(head);
17a52670
AS
2072 env->head = elem;
2073 env->stack_size--;
638f5b90 2074 return 0;
17a52670
AS
2075}
2076
58e2af8b 2077static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
2078 int insn_idx, int prev_insn_idx,
2079 bool speculative)
17a52670 2080{
638f5b90 2081 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 2082 struct bpf_verifier_stack_elem *elem;
638f5b90 2083 int err;
17a52670 2084
638f5b90 2085 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
2086 if (!elem)
2087 goto err;
2088
17a52670
AS
2089 elem->insn_idx = insn_idx;
2090 elem->prev_insn_idx = prev_insn_idx;
2091 elem->next = env->head;
12166409 2092 elem->log_pos = env->log.end_pos;
17a52670
AS
2093 env->head = elem;
2094 env->stack_size++;
1969db47
AS
2095 err = copy_verifier_state(&elem->st, cur);
2096 if (err)
2097 goto err;
979d63d5 2098 elem->st.speculative |= speculative;
b285fcb7
AS
2099 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2100 verbose(env, "The sequence of %d jumps is too complex.\n",
2101 env->stack_size);
17a52670
AS
2102 goto err;
2103 }
2589726d
AS
2104 if (elem->st.parent) {
2105 ++elem->st.parent->branches;
2106 /* WARN_ON(branches > 2) technically makes sense here,
2107 * but
2108 * 1. speculative states will bump 'branches' for non-branch
2109 * instructions
2110 * 2. is_state_visited() heuristics may decide not to create
2111 * a new state for a sequence of branches and all such current
2112 * and cloned states will be pointing to a single parent state
2113 * which might have large 'branches' count.
2114 */
2115 }
17a52670
AS
2116 return &elem->st;
2117err:
5896351e
AS
2118 free_verifier_state(env->cur_state, true);
2119 env->cur_state = NULL;
17a52670 2120 /* pop all elements and return */
6f8a57cc 2121 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
2122 return NULL;
2123}
2124
2125#define CALLER_SAVED_REGS 6
2126static const int caller_saved[CALLER_SAVED_REGS] = {
2127 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2128};
2129
e688c3db
AS
2130/* This helper doesn't clear reg->id */
2131static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 2132{
b03c9f9f
EC
2133 reg->var_off = tnum_const(imm);
2134 reg->smin_value = (s64)imm;
2135 reg->smax_value = (s64)imm;
2136 reg->umin_value = imm;
2137 reg->umax_value = imm;
3f50f132
JF
2138
2139 reg->s32_min_value = (s32)imm;
2140 reg->s32_max_value = (s32)imm;
2141 reg->u32_min_value = (u32)imm;
2142 reg->u32_max_value = (u32)imm;
2143}
2144
e688c3db
AS
2145/* Mark the unknown part of a register (variable offset or scalar value) as
2146 * known to have the value @imm.
2147 */
2148static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2149{
a73bf9f2 2150 /* Clear off and union(map_ptr, range) */
e688c3db
AS
2151 memset(((u8 *)reg) + sizeof(reg->type), 0,
2152 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
a73bf9f2
AN
2153 reg->id = 0;
2154 reg->ref_obj_id = 0;
e688c3db
AS
2155 ___mark_reg_known(reg, imm);
2156}
2157
3f50f132
JF
2158static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2159{
2160 reg->var_off = tnum_const_subreg(reg->var_off, imm);
2161 reg->s32_min_value = (s32)imm;
2162 reg->s32_max_value = (s32)imm;
2163 reg->u32_min_value = (u32)imm;
2164 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
2165}
2166
f1174f77
EC
2167/* Mark the 'variable offset' part of a register as zero. This should be
2168 * used only on registers holding a pointer type.
2169 */
2170static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 2171{
b03c9f9f 2172 __mark_reg_known(reg, 0);
f1174f77 2173}
a9789ef9 2174
cc2b14d5
AS
2175static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2176{
2177 __mark_reg_known(reg, 0);
cc2b14d5
AS
2178 reg->type = SCALAR_VALUE;
2179}
2180
61bd5218
JK
2181static void mark_reg_known_zero(struct bpf_verifier_env *env,
2182 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2183{
2184 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2185 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
2186 /* Something bad happened, let's kill all regs */
2187 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 2188 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2189 return;
2190 }
2191 __mark_reg_known_zero(regs + regno);
2192}
2193
27060531 2194static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
f8064ab9 2195 bool first_slot, int dynptr_id)
27060531
KKD
2196{
2197 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2198 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2199 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2200 */
2201 __mark_reg_known_zero(reg);
2202 reg->type = CONST_PTR_TO_DYNPTR;
f8064ab9
KKD
2203 /* Give each dynptr a unique id to uniquely associate slices to it. */
2204 reg->id = dynptr_id;
27060531
KKD
2205 reg->dynptr.type = type;
2206 reg->dynptr.first_slot = first_slot;
2207}
2208
4ddb7416
DB
2209static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2210{
c25b2ae1 2211 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
4ddb7416
DB
2212 const struct bpf_map *map = reg->map_ptr;
2213
2214 if (map->inner_map_meta) {
2215 reg->type = CONST_PTR_TO_MAP;
2216 reg->map_ptr = map->inner_map_meta;
3e8ce298
AS
2217 /* transfer reg's id which is unique for every map_lookup_elem
2218 * as UID of the inner map.
2219 */
db559117 2220 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
34d11a44 2221 reg->map_uid = reg->id;
4ddb7416
DB
2222 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2223 reg->type = PTR_TO_XDP_SOCK;
2224 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2225 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2226 reg->type = PTR_TO_SOCKET;
2227 } else {
2228 reg->type = PTR_TO_MAP_VALUE;
2229 }
c25b2ae1 2230 return;
4ddb7416 2231 }
c25b2ae1
HL
2232
2233 reg->type &= ~PTR_MAYBE_NULL;
4ddb7416
DB
2234}
2235
5d92ddc3
DM
2236static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2237 struct btf_field_graph_root *ds_head)
2238{
2239 __mark_reg_known_zero(&regs[regno]);
2240 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2241 regs[regno].btf = ds_head->btf;
2242 regs[regno].btf_id = ds_head->value_btf_id;
2243 regs[regno].off = ds_head->node_offset;
2244}
2245
de8f3a83
DB
2246static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2247{
2248 return type_is_pkt_pointer(reg->type);
2249}
2250
2251static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2252{
2253 return reg_is_pkt_pointer(reg) ||
2254 reg->type == PTR_TO_PACKET_END;
2255}
2256
66e3a13e
JK
2257static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2258{
2259 return base_type(reg->type) == PTR_TO_MEM &&
2260 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2261}
2262
de8f3a83
DB
2263/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2264static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2265 enum bpf_reg_type which)
2266{
2267 /* The register can already have a range from prior markings.
2268 * This is fine as long as it hasn't been advanced from its
2269 * origin.
2270 */
2271 return reg->type == which &&
2272 reg->id == 0 &&
2273 reg->off == 0 &&
2274 tnum_equals_const(reg->var_off, 0);
2275}
2276
3f50f132
JF
2277/* Reset the min/max bounds of a register */
2278static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2279{
2280 reg->smin_value = S64_MIN;
2281 reg->smax_value = S64_MAX;
2282 reg->umin_value = 0;
2283 reg->umax_value = U64_MAX;
2284
2285 reg->s32_min_value = S32_MIN;
2286 reg->s32_max_value = S32_MAX;
2287 reg->u32_min_value = 0;
2288 reg->u32_max_value = U32_MAX;
2289}
2290
2291static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2292{
2293 reg->smin_value = S64_MIN;
2294 reg->smax_value = S64_MAX;
2295 reg->umin_value = 0;
2296 reg->umax_value = U64_MAX;
2297}
2298
2299static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2300{
2301 reg->s32_min_value = S32_MIN;
2302 reg->s32_max_value = S32_MAX;
2303 reg->u32_min_value = 0;
2304 reg->u32_max_value = U32_MAX;
2305}
2306
2307static void __update_reg32_bounds(struct bpf_reg_state *reg)
2308{
2309 struct tnum var32_off = tnum_subreg(reg->var_off);
2310
2311 /* min signed is max(sign bit) | min(other bits) */
2312 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2313 var32_off.value | (var32_off.mask & S32_MIN));
2314 /* max signed is min(sign bit) | max(other bits) */
2315 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2316 var32_off.value | (var32_off.mask & S32_MAX));
2317 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2318 reg->u32_max_value = min(reg->u32_max_value,
2319 (u32)(var32_off.value | var32_off.mask));
2320}
2321
2322static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
2323{
2324 /* min signed is max(sign bit) | min(other bits) */
2325 reg->smin_value = max_t(s64, reg->smin_value,
2326 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2327 /* max signed is min(sign bit) | max(other bits) */
2328 reg->smax_value = min_t(s64, reg->smax_value,
2329 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2330 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2331 reg->umax_value = min(reg->umax_value,
2332 reg->var_off.value | reg->var_off.mask);
2333}
2334
3f50f132
JF
2335static void __update_reg_bounds(struct bpf_reg_state *reg)
2336{
2337 __update_reg32_bounds(reg);
2338 __update_reg64_bounds(reg);
2339}
2340
b03c9f9f 2341/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
2342static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2343{
2344 /* Learn sign from signed bounds.
2345 * If we cannot cross the sign boundary, then signed and unsigned bounds
2346 * are the same, so combine. This works even in the negative case, e.g.
2347 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2348 */
2349 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2350 reg->s32_min_value = reg->u32_min_value =
2351 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2352 reg->s32_max_value = reg->u32_max_value =
2353 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2354 return;
2355 }
2356 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2357 * boundary, so we must be careful.
2358 */
2359 if ((s32)reg->u32_max_value >= 0) {
2360 /* Positive. We can't learn anything from the smin, but smax
2361 * is positive, hence safe.
2362 */
2363 reg->s32_min_value = reg->u32_min_value;
2364 reg->s32_max_value = reg->u32_max_value =
2365 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2366 } else if ((s32)reg->u32_min_value < 0) {
2367 /* Negative. We can't learn anything from the smax, but smin
2368 * is negative, hence safe.
2369 */
2370 reg->s32_min_value = reg->u32_min_value =
2371 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2372 reg->s32_max_value = reg->u32_max_value;
2373 }
2374}
2375
2376static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
2377{
2378 /* Learn sign from signed bounds.
2379 * If we cannot cross the sign boundary, then signed and unsigned bounds
2380 * are the same, so combine. This works even in the negative case, e.g.
2381 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2382 */
2383 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2384 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2385 reg->umin_value);
2386 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2387 reg->umax_value);
2388 return;
2389 }
2390 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2391 * boundary, so we must be careful.
2392 */
2393 if ((s64)reg->umax_value >= 0) {
2394 /* Positive. We can't learn anything from the smin, but smax
2395 * is positive, hence safe.
2396 */
2397 reg->smin_value = reg->umin_value;
2398 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2399 reg->umax_value);
2400 } else if ((s64)reg->umin_value < 0) {
2401 /* Negative. We can't learn anything from the smax, but smin
2402 * is negative, hence safe.
2403 */
2404 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2405 reg->umin_value);
2406 reg->smax_value = reg->umax_value;
2407 }
2408}
2409
3f50f132
JF
2410static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2411{
2412 __reg32_deduce_bounds(reg);
2413 __reg64_deduce_bounds(reg);
2414}
2415
b03c9f9f
EC
2416/* Attempts to improve var_off based on unsigned min/max information */
2417static void __reg_bound_offset(struct bpf_reg_state *reg)
2418{
3f50f132
JF
2419 struct tnum var64_off = tnum_intersect(reg->var_off,
2420 tnum_range(reg->umin_value,
2421 reg->umax_value));
7be14c1c
DB
2422 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2423 tnum_range(reg->u32_min_value,
2424 reg->u32_max_value));
3f50f132
JF
2425
2426 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
2427}
2428
3844d153
DB
2429static void reg_bounds_sync(struct bpf_reg_state *reg)
2430{
2431 /* We might have learned new bounds from the var_off. */
2432 __update_reg_bounds(reg);
2433 /* We might have learned something about the sign bit. */
2434 __reg_deduce_bounds(reg);
2435 /* We might have learned some bits from the bounds. */
2436 __reg_bound_offset(reg);
2437 /* Intersecting with the old var_off might have improved our bounds
2438 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2439 * then new var_off is (0; 0x7f...fc) which improves our umax.
2440 */
2441 __update_reg_bounds(reg);
2442}
2443
e572ff80
DB
2444static bool __reg32_bound_s64(s32 a)
2445{
2446 return a >= 0 && a <= S32_MAX;
2447}
2448
3f50f132 2449static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 2450{
3f50f132
JF
2451 reg->umin_value = reg->u32_min_value;
2452 reg->umax_value = reg->u32_max_value;
e572ff80
DB
2453
2454 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2455 * be positive otherwise set to worse case bounds and refine later
2456 * from tnum.
3f50f132 2457 */
e572ff80
DB
2458 if (__reg32_bound_s64(reg->s32_min_value) &&
2459 __reg32_bound_s64(reg->s32_max_value)) {
3a71dc36 2460 reg->smin_value = reg->s32_min_value;
e572ff80
DB
2461 reg->smax_value = reg->s32_max_value;
2462 } else {
3a71dc36 2463 reg->smin_value = 0;
e572ff80
DB
2464 reg->smax_value = U32_MAX;
2465 }
3f50f132
JF
2466}
2467
2468static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2469{
2470 /* special case when 64-bit register has upper 32-bit register
2471 * zeroed. Typically happens after zext or <<32, >>32 sequence
2472 * allowing us to use 32-bit bounds directly,
2473 */
2474 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2475 __reg_assign_32_into_64(reg);
2476 } else {
2477 /* Otherwise the best we can do is push lower 32bit known and
2478 * unknown bits into register (var_off set from jmp logic)
2479 * then learn as much as possible from the 64-bit tnum
2480 * known and unknown bits. The previous smin/smax bounds are
2481 * invalid here because of jmp32 compare so mark them unknown
2482 * so they do not impact tnum bounds calculation.
2483 */
2484 __mark_reg64_unbounded(reg);
3f50f132 2485 }
3844d153 2486 reg_bounds_sync(reg);
3f50f132
JF
2487}
2488
2489static bool __reg64_bound_s32(s64 a)
2490{
388e2c0b 2491 return a >= S32_MIN && a <= S32_MAX;
3f50f132
JF
2492}
2493
2494static bool __reg64_bound_u32(u64 a)
2495{
b9979db8 2496 return a >= U32_MIN && a <= U32_MAX;
3f50f132
JF
2497}
2498
2499static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2500{
2501 __mark_reg32_unbounded(reg);
b0270958 2502 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 2503 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 2504 reg->s32_max_value = (s32)reg->smax_value;
b0270958 2505 }
10bf4e83 2506 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 2507 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 2508 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 2509 }
3844d153 2510 reg_bounds_sync(reg);
b03c9f9f
EC
2511}
2512
f1174f77 2513/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
2514static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2515 struct bpf_reg_state *reg)
f1174f77 2516{
a9c676bc 2517 /*
a73bf9f2 2518 * Clear type, off, and union(map_ptr, range) and
a9c676bc
AS
2519 * padding between 'type' and union
2520 */
2521 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 2522 reg->type = SCALAR_VALUE;
a73bf9f2
AN
2523 reg->id = 0;
2524 reg->ref_obj_id = 0;
f1174f77 2525 reg->var_off = tnum_unknown;
f4d7e40a 2526 reg->frameno = 0;
be2ef816 2527 reg->precise = !env->bpf_capable;
b03c9f9f 2528 __mark_reg_unbounded(reg);
f1174f77
EC
2529}
2530
61bd5218
JK
2531static void mark_reg_unknown(struct bpf_verifier_env *env,
2532 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2533{
2534 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2535 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
2536 /* Something bad happened, let's kill all regs except FP */
2537 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 2538 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2539 return;
2540 }
f54c7898 2541 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
2542}
2543
f54c7898
DB
2544static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2545 struct bpf_reg_state *reg)
f1174f77 2546{
f54c7898 2547 __mark_reg_unknown(env, reg);
f1174f77
EC
2548 reg->type = NOT_INIT;
2549}
2550
61bd5218
JK
2551static void mark_reg_not_init(struct bpf_verifier_env *env,
2552 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2553{
2554 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2555 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
2556 /* Something bad happened, let's kill all regs except FP */
2557 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 2558 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2559 return;
2560 }
f54c7898 2561 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
2562}
2563
41c48f3a
AI
2564static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2565 struct bpf_reg_state *regs, u32 regno,
22dc4a0f 2566 enum bpf_reg_type reg_type,
c6f1bfe8
YS
2567 struct btf *btf, u32 btf_id,
2568 enum bpf_type_flag flag)
41c48f3a
AI
2569{
2570 if (reg_type == SCALAR_VALUE) {
2571 mark_reg_unknown(env, regs, regno);
2572 return;
2573 }
2574 mark_reg_known_zero(env, regs, regno);
c6f1bfe8 2575 regs[regno].type = PTR_TO_BTF_ID | flag;
22dc4a0f 2576 regs[regno].btf = btf;
41c48f3a
AI
2577 regs[regno].btf_id = btf_id;
2578}
2579
5327ed3d 2580#define DEF_NOT_SUBREG (0)
61bd5218 2581static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 2582 struct bpf_func_state *state)
17a52670 2583{
f4d7e40a 2584 struct bpf_reg_state *regs = state->regs;
17a52670
AS
2585 int i;
2586
dc503a8a 2587 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 2588 mark_reg_not_init(env, regs, i);
dc503a8a 2589 regs[i].live = REG_LIVE_NONE;
679c782d 2590 regs[i].parent = NULL;
5327ed3d 2591 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 2592 }
17a52670
AS
2593
2594 /* frame pointer */
f1174f77 2595 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 2596 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 2597 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
2598}
2599
f4d7e40a
AS
2600#define BPF_MAIN_FUNC (-1)
2601static void init_func_state(struct bpf_verifier_env *env,
2602 struct bpf_func_state *state,
2603 int callsite, int frameno, int subprogno)
2604{
2605 state->callsite = callsite;
2606 state->frameno = frameno;
2607 state->subprogno = subprogno;
1bfe26fb 2608 state->callback_ret_range = tnum_range(0, 0);
f4d7e40a 2609 init_reg_state(env, state);
0f55f9ed 2610 mark_verifier_state_scratched(env);
f4d7e40a
AS
2611}
2612
bfc6bb74
AS
2613/* Similar to push_stack(), but for async callbacks */
2614static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2615 int insn_idx, int prev_insn_idx,
2616 int subprog)
2617{
2618 struct bpf_verifier_stack_elem *elem;
2619 struct bpf_func_state *frame;
2620
2621 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2622 if (!elem)
2623 goto err;
2624
2625 elem->insn_idx = insn_idx;
2626 elem->prev_insn_idx = prev_insn_idx;
2627 elem->next = env->head;
12166409 2628 elem->log_pos = env->log.end_pos;
bfc6bb74
AS
2629 env->head = elem;
2630 env->stack_size++;
2631 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2632 verbose(env,
2633 "The sequence of %d jumps is too complex for async cb.\n",
2634 env->stack_size);
2635 goto err;
2636 }
2637 /* Unlike push_stack() do not copy_verifier_state().
2638 * The caller state doesn't matter.
2639 * This is async callback. It starts in a fresh stack.
2640 * Initialize it similar to do_check_common().
2641 */
2642 elem->st.branches = 1;
2643 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2644 if (!frame)
2645 goto err;
2646 init_func_state(env, frame,
2647 BPF_MAIN_FUNC /* callsite */,
2648 0 /* frameno within this callchain */,
2649 subprog /* subprog number within this prog */);
2650 elem->st.frame[0] = frame;
2651 return &elem->st;
2652err:
2653 free_verifier_state(env->cur_state, true);
2654 env->cur_state = NULL;
2655 /* pop all elements and return */
2656 while (!pop_stack(env, NULL, NULL, false));
2657 return NULL;
2658}
2659
2660
17a52670
AS
2661enum reg_arg_type {
2662 SRC_OP, /* register is used as source operand */
2663 DST_OP, /* register is used as destination operand */
2664 DST_OP_NO_MARK /* same as above, check only, don't mark */
2665};
2666
cc8b0b92
AS
2667static int cmp_subprogs(const void *a, const void *b)
2668{
9c8105bd
JW
2669 return ((struct bpf_subprog_info *)a)->start -
2670 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
2671}
2672
2673static int find_subprog(struct bpf_verifier_env *env, int off)
2674{
9c8105bd 2675 struct bpf_subprog_info *p;
cc8b0b92 2676
9c8105bd
JW
2677 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2678 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
2679 if (!p)
2680 return -ENOENT;
9c8105bd 2681 return p - env->subprog_info;
cc8b0b92
AS
2682
2683}
2684
2685static int add_subprog(struct bpf_verifier_env *env, int off)
2686{
2687 int insn_cnt = env->prog->len;
2688 int ret;
2689
2690 if (off >= insn_cnt || off < 0) {
2691 verbose(env, "call to invalid destination\n");
2692 return -EINVAL;
2693 }
2694 ret = find_subprog(env, off);
2695 if (ret >= 0)
282a0f46 2696 return ret;
4cb3d99c 2697 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
2698 verbose(env, "too many subprograms\n");
2699 return -E2BIG;
2700 }
e6ac2450 2701 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
2702 env->subprog_info[env->subprog_cnt++].start = off;
2703 sort(env->subprog_info, env->subprog_cnt,
2704 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 2705 return env->subprog_cnt - 1;
cc8b0b92
AS
2706}
2707
b9ae0c9d
KKD
2708static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2709{
2710 struct bpf_prog_aux *aux = env->prog->aux;
2711 struct btf *btf = aux->btf;
2712 const struct btf_type *t;
2713 u32 main_btf_id, id;
2714 const char *name;
2715 int ret, i;
2716
2717 /* Non-zero func_info_cnt implies valid btf */
2718 if (!aux->func_info_cnt)
2719 return 0;
2720 main_btf_id = aux->func_info[0].type_id;
2721
2722 t = btf_type_by_id(btf, main_btf_id);
2723 if (!t) {
2724 verbose(env, "invalid btf id for main subprog in func_info\n");
2725 return -EINVAL;
2726 }
2727
2728 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2729 if (IS_ERR(name)) {
2730 ret = PTR_ERR(name);
2731 /* If there is no tag present, there is no exception callback */
2732 if (ret == -ENOENT)
2733 ret = 0;
2734 else if (ret == -EEXIST)
2735 verbose(env, "multiple exception callback tags for main subprog\n");
2736 return ret;
2737 }
2738
2739 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2740 if (ret < 0) {
2741 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2742 return ret;
2743 }
2744 id = ret;
2745 t = btf_type_by_id(btf, id);
2746 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2747 verbose(env, "exception callback '%s' must have global linkage\n", name);
2748 return -EINVAL;
2749 }
2750 ret = 0;
2751 for (i = 0; i < aux->func_info_cnt; i++) {
2752 if (aux->func_info[i].type_id != id)
2753 continue;
2754 ret = aux->func_info[i].insn_off;
2755 /* Further func_info and subprog checks will also happen
2756 * later, so assume this is the right insn_off for now.
2757 */
2758 if (!ret) {
2759 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2760 ret = -EINVAL;
2761 }
2762 }
2763 if (!ret) {
2764 verbose(env, "exception callback type id not found in func_info\n");
2765 ret = -EINVAL;
2766 }
2767 return ret;
2768}
2769
2357672c
KKD
2770#define MAX_KFUNC_DESCS 256
2771#define MAX_KFUNC_BTFS 256
2772
e6ac2450
MKL
2773struct bpf_kfunc_desc {
2774 struct btf_func_model func_model;
2775 u32 func_id;
2776 s32 imm;
2357672c 2777 u16 offset;
1cf3bfc6 2778 unsigned long addr;
2357672c
KKD
2779};
2780
2781struct bpf_kfunc_btf {
2782 struct btf *btf;
2783 struct module *module;
2784 u16 offset;
e6ac2450
MKL
2785};
2786
e6ac2450 2787struct bpf_kfunc_desc_tab {
1cf3bfc6
IL
2788 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2789 * verification. JITs do lookups by bpf_insn, where func_id may not be
2790 * available, therefore at the end of verification do_misc_fixups()
2791 * sorts this by imm and offset.
2792 */
e6ac2450
MKL
2793 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2794 u32 nr_descs;
2795};
2796
2357672c
KKD
2797struct bpf_kfunc_btf_tab {
2798 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2799 u32 nr_descs;
2800};
2801
2802static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
e6ac2450
MKL
2803{
2804 const struct bpf_kfunc_desc *d0 = a;
2805 const struct bpf_kfunc_desc *d1 = b;
2806
2807 /* func_id is not greater than BTF_MAX_TYPE */
2357672c
KKD
2808 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2809}
2810
2811static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2812{
2813 const struct bpf_kfunc_btf *d0 = a;
2814 const struct bpf_kfunc_btf *d1 = b;
2815
2816 return d0->offset - d1->offset;
e6ac2450
MKL
2817}
2818
2819static const struct bpf_kfunc_desc *
2357672c 2820find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
e6ac2450
MKL
2821{
2822 struct bpf_kfunc_desc desc = {
2823 .func_id = func_id,
2357672c 2824 .offset = offset,
e6ac2450
MKL
2825 };
2826 struct bpf_kfunc_desc_tab *tab;
2827
2828 tab = prog->aux->kfunc_tab;
2829 return bsearch(&desc, tab->descs, tab->nr_descs,
2357672c
KKD
2830 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2831}
2832
1cf3bfc6
IL
2833int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2834 u16 btf_fd_idx, u8 **func_addr)
2835{
2836 const struct bpf_kfunc_desc *desc;
2837
2838 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2839 if (!desc)
2840 return -EFAULT;
2841
2842 *func_addr = (u8 *)desc->addr;
2843 return 0;
2844}
2845
2357672c 2846static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
b202d844 2847 s16 offset)
2357672c
KKD
2848{
2849 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2850 struct bpf_kfunc_btf_tab *tab;
2851 struct bpf_kfunc_btf *b;
2852 struct module *mod;
2853 struct btf *btf;
2854 int btf_fd;
2855
2856 tab = env->prog->aux->kfunc_btf_tab;
2857 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2858 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2859 if (!b) {
2860 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2861 verbose(env, "too many different module BTFs\n");
2862 return ERR_PTR(-E2BIG);
2863 }
2864
2865 if (bpfptr_is_null(env->fd_array)) {
2866 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2867 return ERR_PTR(-EPROTO);
2868 }
2869
2870 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2871 offset * sizeof(btf_fd),
2872 sizeof(btf_fd)))
2873 return ERR_PTR(-EFAULT);
2874
2875 btf = btf_get_by_fd(btf_fd);
588cd7ef
KKD
2876 if (IS_ERR(btf)) {
2877 verbose(env, "invalid module BTF fd specified\n");
2357672c 2878 return btf;
588cd7ef 2879 }
2357672c
KKD
2880
2881 if (!btf_is_module(btf)) {
2882 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2883 btf_put(btf);
2884 return ERR_PTR(-EINVAL);
2885 }
2886
2887 mod = btf_try_get_module(btf);
2888 if (!mod) {
2889 btf_put(btf);
2890 return ERR_PTR(-ENXIO);
2891 }
2892
2893 b = &tab->descs[tab->nr_descs++];
2894 b->btf = btf;
2895 b->module = mod;
2896 b->offset = offset;
2897
2898 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2899 kfunc_btf_cmp_by_off, NULL);
2900 }
2357672c 2901 return b->btf;
e6ac2450
MKL
2902}
2903
2357672c
KKD
2904void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2905{
2906 if (!tab)
2907 return;
2908
2909 while (tab->nr_descs--) {
2910 module_put(tab->descs[tab->nr_descs].module);
2911 btf_put(tab->descs[tab->nr_descs].btf);
2912 }
2913 kfree(tab);
2914}
2915
43bf0878 2916static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2357672c 2917{
2357672c
KKD
2918 if (offset) {
2919 if (offset < 0) {
2920 /* In the future, this can be allowed to increase limit
2921 * of fd index into fd_array, interpreted as u16.
2922 */
2923 verbose(env, "negative offset disallowed for kernel module function call\n");
2924 return ERR_PTR(-EINVAL);
2925 }
2926
b202d844 2927 return __find_kfunc_desc_btf(env, offset);
2357672c
KKD
2928 }
2929 return btf_vmlinux ?: ERR_PTR(-ENOENT);
e6ac2450
MKL
2930}
2931
2357672c 2932static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
e6ac2450
MKL
2933{
2934 const struct btf_type *func, *func_proto;
2357672c 2935 struct bpf_kfunc_btf_tab *btf_tab;
e6ac2450
MKL
2936 struct bpf_kfunc_desc_tab *tab;
2937 struct bpf_prog_aux *prog_aux;
2938 struct bpf_kfunc_desc *desc;
2939 const char *func_name;
2357672c 2940 struct btf *desc_btf;
8cbf062a 2941 unsigned long call_imm;
e6ac2450
MKL
2942 unsigned long addr;
2943 int err;
2944
2945 prog_aux = env->prog->aux;
2946 tab = prog_aux->kfunc_tab;
2357672c 2947 btf_tab = prog_aux->kfunc_btf_tab;
e6ac2450
MKL
2948 if (!tab) {
2949 if (!btf_vmlinux) {
2950 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2951 return -ENOTSUPP;
2952 }
2953
2954 if (!env->prog->jit_requested) {
2955 verbose(env, "JIT is required for calling kernel function\n");
2956 return -ENOTSUPP;
2957 }
2958
2959 if (!bpf_jit_supports_kfunc_call()) {
2960 verbose(env, "JIT does not support calling kernel function\n");
2961 return -ENOTSUPP;
2962 }
2963
2964 if (!env->prog->gpl_compatible) {
2965 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2966 return -EINVAL;
2967 }
2968
2969 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2970 if (!tab)
2971 return -ENOMEM;
2972 prog_aux->kfunc_tab = tab;
2973 }
2974
a5d82727
KKD
2975 /* func_id == 0 is always invalid, but instead of returning an error, be
2976 * conservative and wait until the code elimination pass before returning
2977 * error, so that invalid calls that get pruned out can be in BPF programs
2978 * loaded from userspace. It is also required that offset be untouched
2979 * for such calls.
2980 */
2981 if (!func_id && !offset)
2982 return 0;
2983
2357672c
KKD
2984 if (!btf_tab && offset) {
2985 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2986 if (!btf_tab)
2987 return -ENOMEM;
2988 prog_aux->kfunc_btf_tab = btf_tab;
2989 }
2990
43bf0878 2991 desc_btf = find_kfunc_desc_btf(env, offset);
2357672c
KKD
2992 if (IS_ERR(desc_btf)) {
2993 verbose(env, "failed to find BTF for kernel function\n");
2994 return PTR_ERR(desc_btf);
2995 }
2996
2997 if (find_kfunc_desc(env->prog, func_id, offset))
e6ac2450
MKL
2998 return 0;
2999
3000 if (tab->nr_descs == MAX_KFUNC_DESCS) {
3001 verbose(env, "too many different kernel function calls\n");
3002 return -E2BIG;
3003 }
3004
2357672c 3005 func = btf_type_by_id(desc_btf, func_id);
e6ac2450
MKL
3006 if (!func || !btf_type_is_func(func)) {
3007 verbose(env, "kernel btf_id %u is not a function\n",
3008 func_id);
3009 return -EINVAL;
3010 }
2357672c 3011 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450
MKL
3012 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3013 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3014 func_id);
3015 return -EINVAL;
3016 }
3017
2357672c 3018 func_name = btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
3019 addr = kallsyms_lookup_name(func_name);
3020 if (!addr) {
3021 verbose(env, "cannot find address for kernel function %s\n",
3022 func_name);
3023 return -EINVAL;
3024 }
1cf3bfc6 3025 specialize_kfunc(env, func_id, offset, &addr);
e6ac2450 3026
1cf3bfc6
IL
3027 if (bpf_jit_supports_far_kfunc_call()) {
3028 call_imm = func_id;
3029 } else {
3030 call_imm = BPF_CALL_IMM(addr);
3031 /* Check whether the relative offset overflows desc->imm */
3032 if ((unsigned long)(s32)call_imm != call_imm) {
3033 verbose(env, "address of kernel function %s is out of range\n",
3034 func_name);
3035 return -EINVAL;
3036 }
8cbf062a
HT
3037 }
3038
3d76a4d3
SF
3039 if (bpf_dev_bound_kfunc_id(func_id)) {
3040 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3041 if (err)
3042 return err;
3043 }
3044
e6ac2450
MKL
3045 desc = &tab->descs[tab->nr_descs++];
3046 desc->func_id = func_id;
8cbf062a 3047 desc->imm = call_imm;
2357672c 3048 desc->offset = offset;
1cf3bfc6 3049 desc->addr = addr;
2357672c 3050 err = btf_distill_func_proto(&env->log, desc_btf,
e6ac2450
MKL
3051 func_proto, func_name,
3052 &desc->func_model);
3053 if (!err)
3054 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2357672c 3055 kfunc_desc_cmp_by_id_off, NULL);
e6ac2450
MKL
3056 return err;
3057}
3058
1cf3bfc6 3059static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
e6ac2450
MKL
3060{
3061 const struct bpf_kfunc_desc *d0 = a;
3062 const struct bpf_kfunc_desc *d1 = b;
3063
1cf3bfc6
IL
3064 if (d0->imm != d1->imm)
3065 return d0->imm < d1->imm ? -1 : 1;
3066 if (d0->offset != d1->offset)
3067 return d0->offset < d1->offset ? -1 : 1;
e6ac2450
MKL
3068 return 0;
3069}
3070
1cf3bfc6 3071static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
e6ac2450
MKL
3072{
3073 struct bpf_kfunc_desc_tab *tab;
3074
3075 tab = prog->aux->kfunc_tab;
3076 if (!tab)
3077 return;
3078
3079 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1cf3bfc6 3080 kfunc_desc_cmp_by_imm_off, NULL);
e6ac2450
MKL
3081}
3082
3083bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3084{
3085 return !!prog->aux->kfunc_tab;
3086}
3087
3088const struct btf_func_model *
3089bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3090 const struct bpf_insn *insn)
3091{
3092 const struct bpf_kfunc_desc desc = {
3093 .imm = insn->imm,
1cf3bfc6 3094 .offset = insn->off,
e6ac2450
MKL
3095 };
3096 const struct bpf_kfunc_desc *res;
3097 struct bpf_kfunc_desc_tab *tab;
3098
3099 tab = prog->aux->kfunc_tab;
3100 res = bsearch(&desc, tab->descs, tab->nr_descs,
1cf3bfc6 3101 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
e6ac2450
MKL
3102
3103 return res ? &res->func_model : NULL;
3104}
3105
3106static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 3107{
9c8105bd 3108 struct bpf_subprog_info *subprog = env->subprog_info;
b9ae0c9d 3109 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
cc8b0b92 3110 struct bpf_insn *insn = env->prog->insnsi;
cc8b0b92 3111
f910cefa
JW
3112 /* Add entry function. */
3113 ret = add_subprog(env, 0);
e6ac2450 3114 if (ret)
f910cefa
JW
3115 return ret;
3116
e6ac2450
MKL
3117 for (i = 0; i < insn_cnt; i++, insn++) {
3118 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3119 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 3120 continue;
e6ac2450 3121
2c78ee89 3122 if (!env->bpf_capable) {
e6ac2450 3123 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
3124 return -EPERM;
3125 }
e6ac2450 3126
3990ed4c 3127 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
e6ac2450 3128 ret = add_subprog(env, i + insn->imm + 1);
3990ed4c 3129 else
2357672c 3130 ret = add_kfunc_call(env, insn->imm, insn->off);
e6ac2450 3131
cc8b0b92
AS
3132 if (ret < 0)
3133 return ret;
3134 }
3135
b9ae0c9d
KKD
3136 ret = bpf_find_exception_callback_insn_off(env);
3137 if (ret < 0)
3138 return ret;
3139 ex_cb_insn = ret;
3140
3141 /* If ex_cb_insn > 0, this means that the main program has a subprog
3142 * marked using BTF decl tag to serve as the exception callback.
3143 */
3144 if (ex_cb_insn) {
3145 ret = add_subprog(env, ex_cb_insn);
3146 if (ret < 0)
3147 return ret;
3148 for (i = 1; i < env->subprog_cnt; i++) {
3149 if (env->subprog_info[i].start != ex_cb_insn)
3150 continue;
3151 env->exception_callback_subprog = i;
3152 break;
3153 }
3154 }
3155
4cb3d99c
JW
3156 /* Add a fake 'exit' subprog which could simplify subprog iteration
3157 * logic. 'subprog_cnt' should not be increased.
3158 */
3159 subprog[env->subprog_cnt].start = insn_cnt;
3160
06ee7115 3161 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 3162 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 3163 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 3164
e6ac2450
MKL
3165 return 0;
3166}
3167
3168static int check_subprogs(struct bpf_verifier_env *env)
3169{
3170 int i, subprog_start, subprog_end, off, cur_subprog = 0;
3171 struct bpf_subprog_info *subprog = env->subprog_info;
3172 struct bpf_insn *insn = env->prog->insnsi;
3173 int insn_cnt = env->prog->len;
3174
cc8b0b92 3175 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
3176 subprog_start = subprog[cur_subprog].start;
3177 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
3178 for (i = 0; i < insn_cnt; i++) {
3179 u8 code = insn[i].code;
3180
7f6e4312 3181 if (code == (BPF_JMP | BPF_CALL) &&
df2ccc18
IL
3182 insn[i].src_reg == 0 &&
3183 insn[i].imm == BPF_FUNC_tail_call)
7f6e4312 3184 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
3185 if (BPF_CLASS(code) == BPF_LD &&
3186 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3187 subprog[cur_subprog].has_ld_abs = true;
092ed096 3188 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
3189 goto next;
3190 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3191 goto next;
4cd58e9a
YS
3192 if (code == (BPF_JMP32 | BPF_JA))
3193 off = i + insn[i].imm + 1;
3194 else
3195 off = i + insn[i].off + 1;
cc8b0b92
AS
3196 if (off < subprog_start || off >= subprog_end) {
3197 verbose(env, "jump out of range from insn %d to %d\n", i, off);
3198 return -EINVAL;
3199 }
3200next:
3201 if (i == subprog_end - 1) {
3202 /* to avoid fall-through from one subprog into another
3203 * the last insn of the subprog should be either exit
f18b03fa 3204 * or unconditional jump back or bpf_throw call
cc8b0b92
AS
3205 */
3206 if (code != (BPF_JMP | BPF_EXIT) &&
4cd58e9a 3207 code != (BPF_JMP32 | BPF_JA) &&
cc8b0b92
AS
3208 code != (BPF_JMP | BPF_JA)) {
3209 verbose(env, "last insn is not an exit or jmp\n");
3210 return -EINVAL;
3211 }
3212 subprog_start = subprog_end;
4cb3d99c
JW
3213 cur_subprog++;
3214 if (cur_subprog < env->subprog_cnt)
9c8105bd 3215 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
3216 }
3217 }
3218 return 0;
3219}
3220
679c782d
EC
3221/* Parentage chain of this register (or stack slot) should take care of all
3222 * issues like callee-saved registers, stack slot allocation time, etc.
3223 */
f4d7e40a 3224static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 3225 const struct bpf_reg_state *state,
5327ed3d 3226 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
3227{
3228 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 3229 int cnt = 0;
dc503a8a
EC
3230
3231 while (parent) {
3232 /* if read wasn't screened by an earlier write ... */
679c782d 3233 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 3234 break;
9242b5f5
AS
3235 if (parent->live & REG_LIVE_DONE) {
3236 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
c25b2ae1 3237 reg_type_str(env, parent->type),
9242b5f5
AS
3238 parent->var_off.value, parent->off);
3239 return -EFAULT;
3240 }
5327ed3d
JW
3241 /* The first condition is more likely to be true than the
3242 * second, checked it first.
3243 */
3244 if ((parent->live & REG_LIVE_READ) == flag ||
3245 parent->live & REG_LIVE_READ64)
25af32da
AS
3246 /* The parentage chain never changes and
3247 * this parent was already marked as LIVE_READ.
3248 * There is no need to keep walking the chain again and
3249 * keep re-marking all parents as LIVE_READ.
3250 * This case happens when the same register is read
3251 * multiple times without writes into it in-between.
5327ed3d
JW
3252 * Also, if parent has the stronger REG_LIVE_READ64 set,
3253 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
3254 */
3255 break;
dc503a8a 3256 /* ... then we depend on parent's value */
5327ed3d
JW
3257 parent->live |= flag;
3258 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3259 if (flag == REG_LIVE_READ64)
3260 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
3261 state = parent;
3262 parent = state->parent;
f4d7e40a 3263 writes = true;
06ee7115 3264 cnt++;
dc503a8a 3265 }
06ee7115
AS
3266
3267 if (env->longest_mark_read_walk < cnt)
3268 env->longest_mark_read_walk = cnt;
f4d7e40a 3269 return 0;
dc503a8a
EC
3270}
3271
d6fefa11
KKD
3272static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3273{
3274 struct bpf_func_state *state = func(env, reg);
3275 int spi, ret;
3276
3277 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3278 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3279 * check_kfunc_call.
3280 */
3281 if (reg->type == CONST_PTR_TO_DYNPTR)
3282 return 0;
79168a66
KKD
3283 spi = dynptr_get_spi(env, reg);
3284 if (spi < 0)
3285 return spi;
d6fefa11
KKD
3286 /* Caller ensures dynptr is valid and initialized, which means spi is in
3287 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3288 * read.
3289 */
3290 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3291 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3292 if (ret)
3293 return ret;
3294 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3295 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3296}
3297
06accc87
AN
3298static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3299 int spi, int nr_slots)
3300{
3301 struct bpf_func_state *state = func(env, reg);
3302 int err, i;
3303
3304 for (i = 0; i < nr_slots; i++) {
3305 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3306
3307 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3308 if (err)
3309 return err;
3310
3311 mark_stack_slot_scratched(env, spi - i);
3312 }
3313
3314 return 0;
3315}
3316
5327ed3d
JW
3317/* This function is supposed to be used by the following 32-bit optimization
3318 * code only. It returns TRUE if the source or destination register operates
3319 * on 64-bit, otherwise return FALSE.
3320 */
3321static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3322 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3323{
3324 u8 code, class, op;
3325
3326 code = insn->code;
3327 class = BPF_CLASS(code);
3328 op = BPF_OP(code);
3329 if (class == BPF_JMP) {
3330 /* BPF_EXIT for "main" will reach here. Return TRUE
3331 * conservatively.
3332 */
3333 if (op == BPF_EXIT)
3334 return true;
3335 if (op == BPF_CALL) {
3336 /* BPF to BPF call will reach here because of marking
3337 * caller saved clobber with DST_OP_NO_MARK for which we
3338 * don't care the register def because they are anyway
3339 * marked as NOT_INIT already.
3340 */
3341 if (insn->src_reg == BPF_PSEUDO_CALL)
3342 return false;
3343 /* Helper call will reach here because of arg type
3344 * check, conservatively return TRUE.
3345 */
3346 if (t == SRC_OP)
3347 return true;
3348
3349 return false;
3350 }
3351 }
3352
0845c3db
YS
3353 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3354 return false;
3355
5327ed3d 3356 if (class == BPF_ALU64 || class == BPF_JMP ||
5327ed3d
JW
3357 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3358 return true;
3359
3360 if (class == BPF_ALU || class == BPF_JMP32)
3361 return false;
3362
3363 if (class == BPF_LDX) {
3364 if (t != SRC_OP)
577c06af 3365 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
5327ed3d
JW
3366 /* LDX source must be ptr. */
3367 return true;
3368 }
3369
3370 if (class == BPF_STX) {
83a28819
IL
3371 /* BPF_STX (including atomic variants) has multiple source
3372 * operands, one of which is a ptr. Check whether the caller is
3373 * asking about it.
3374 */
3375 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
3376 return true;
3377 return BPF_SIZE(code) == BPF_DW;
3378 }
3379
3380 if (class == BPF_LD) {
3381 u8 mode = BPF_MODE(code);
3382
3383 /* LD_IMM64 */
3384 if (mode == BPF_IMM)
3385 return true;
3386
3387 /* Both LD_IND and LD_ABS return 32-bit data. */
3388 if (t != SRC_OP)
3389 return false;
3390
3391 /* Implicit ctx ptr. */
3392 if (regno == BPF_REG_6)
3393 return true;
3394
3395 /* Explicit source could be any width. */
3396 return true;
3397 }
3398
3399 if (class == BPF_ST)
3400 /* The only source register for BPF_ST is a ptr. */
3401 return true;
3402
3403 /* Conservatively return true at default. */
3404 return true;
3405}
3406
83a28819
IL
3407/* Return the regno defined by the insn, or -1. */
3408static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 3409{
83a28819
IL
3410 switch (BPF_CLASS(insn->code)) {
3411 case BPF_JMP:
3412 case BPF_JMP32:
3413 case BPF_ST:
3414 return -1;
3415 case BPF_STX:
3416 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3417 (insn->imm & BPF_FETCH)) {
3418 if (insn->imm == BPF_CMPXCHG)
3419 return BPF_REG_0;
3420 else
3421 return insn->src_reg;
3422 } else {
3423 return -1;
3424 }
3425 default:
3426 return insn->dst_reg;
3427 }
b325fbca
JW
3428}
3429
3430/* Return TRUE if INSN has defined any 32-bit value explicitly. */
3431static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3432{
83a28819
IL
3433 int dst_reg = insn_def_regno(insn);
3434
3435 if (dst_reg == -1)
b325fbca
JW
3436 return false;
3437
83a28819 3438 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
3439}
3440
5327ed3d
JW
3441static void mark_insn_zext(struct bpf_verifier_env *env,
3442 struct bpf_reg_state *reg)
3443{
3444 s32 def_idx = reg->subreg_def;
3445
3446 if (def_idx == DEF_NOT_SUBREG)
3447 return;
3448
3449 env->insn_aux_data[def_idx - 1].zext_dst = true;
3450 /* The dst will be zero extended, so won't be sub-register anymore. */
3451 reg->subreg_def = DEF_NOT_SUBREG;
3452}
3453
683b96f9
EZ
3454static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3455 enum reg_arg_type t)
17a52670 3456{
5327ed3d 3457 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
683b96f9 3458 struct bpf_reg_state *reg;
5327ed3d 3459 bool rw64;
dc503a8a 3460
17a52670 3461 if (regno >= MAX_BPF_REG) {
61bd5218 3462 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
3463 return -EINVAL;
3464 }
3465
0f55f9ed
CL
3466 mark_reg_scratched(env, regno);
3467
c342dc10 3468 reg = &regs[regno];
5327ed3d 3469 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
3470 if (t == SRC_OP) {
3471 /* check whether register used as source operand can be read */
c342dc10 3472 if (reg->type == NOT_INIT) {
61bd5218 3473 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
3474 return -EACCES;
3475 }
679c782d 3476 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
3477 if (regno == BPF_REG_FP)
3478 return 0;
3479
5327ed3d
JW
3480 if (rw64)
3481 mark_insn_zext(env, reg);
3482
3483 return mark_reg_read(env, reg, reg->parent,
3484 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
3485 } else {
3486 /* check whether register used as dest operand can be written to */
3487 if (regno == BPF_REG_FP) {
61bd5218 3488 verbose(env, "frame pointer is read only\n");
17a52670
AS
3489 return -EACCES;
3490 }
c342dc10 3491 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 3492 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 3493 if (t == DST_OP)
61bd5218 3494 mark_reg_unknown(env, regs, regno);
17a52670
AS
3495 }
3496 return 0;
3497}
3498
683b96f9
EZ
3499static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3500 enum reg_arg_type t)
3501{
3502 struct bpf_verifier_state *vstate = env->cur_state;
3503 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3504
3505 return __check_reg_arg(env, state->regs, regno, t);
3506}
3507
bffdeaa8
AN
3508static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3509{
3510 env->insn_aux_data[idx].jmp_point = true;
3511}
3512
3513static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3514{
3515 return env->insn_aux_data[insn_idx].jmp_point;
3516}
3517
b5dc0163
AS
3518/* for any branch, call, exit record the history of jmps in the given state */
3519static int push_jmp_history(struct bpf_verifier_env *env,
3520 struct bpf_verifier_state *cur)
3521{
3522 u32 cnt = cur->jmp_history_cnt;
3523 struct bpf_idx_pair *p;
ceb35b66 3524 size_t alloc_size;
b5dc0163 3525
bffdeaa8
AN
3526 if (!is_jmp_point(env, env->insn_idx))
3527 return 0;
3528
b5dc0163 3529 cnt++;
ceb35b66
KC
3530 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3531 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
b5dc0163
AS
3532 if (!p)
3533 return -ENOMEM;
3534 p[cnt - 1].idx = env->insn_idx;
3535 p[cnt - 1].prev_idx = env->prev_insn_idx;
3536 cur->jmp_history = p;
3537 cur->jmp_history_cnt = cnt;
3538 return 0;
3539}
3540
3541/* Backtrack one insn at a time. If idx is not at the top of recorded
3542 * history then previous instruction came from straight line execution.
4bb7ea94
AN
3543 * Return -ENOENT if we exhausted all instructions within given state.
3544 *
3545 * It's legal to have a bit of a looping with the same starting and ending
3546 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3547 * instruction index is the same as state's first_idx doesn't mean we are
3548 * done. If there is still some jump history left, we should keep going. We
3549 * need to take into account that we might have a jump history between given
3550 * state's parent and itself, due to checkpointing. In this case, we'll have
3551 * history entry recording a jump from last instruction of parent state and
3552 * first instruction of given state.
b5dc0163
AS
3553 */
3554static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3555 u32 *history)
3556{
3557 u32 cnt = *history;
3558
4bb7ea94
AN
3559 if (i == st->first_insn_idx) {
3560 if (cnt == 0)
3561 return -ENOENT;
3562 if (cnt == 1 && st->jmp_history[0].idx == i)
3563 return -ENOENT;
3564 }
3565
b5dc0163
AS
3566 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3567 i = st->jmp_history[cnt - 1].prev_idx;
3568 (*history)--;
3569 } else {
3570 i--;
3571 }
3572 return i;
3573}
3574
e6ac2450
MKL
3575static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3576{
3577 const struct btf_type *func;
2357672c 3578 struct btf *desc_btf;
e6ac2450
MKL
3579
3580 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3581 return NULL;
3582
43bf0878 3583 desc_btf = find_kfunc_desc_btf(data, insn->off);
2357672c
KKD
3584 if (IS_ERR(desc_btf))
3585 return "<error>";
3586
3587 func = btf_type_by_id(desc_btf, insn->imm);
3588 return btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
3589}
3590
407958a0
AN
3591static inline void bt_init(struct backtrack_state *bt, u32 frame)
3592{
3593 bt->frame = frame;
3594}
3595
3596static inline void bt_reset(struct backtrack_state *bt)
3597{
3598 struct bpf_verifier_env *env = bt->env;
3599
3600 memset(bt, 0, sizeof(*bt));
3601 bt->env = env;
3602}
3603
3604static inline u32 bt_empty(struct backtrack_state *bt)
3605{
3606 u64 mask = 0;
3607 int i;
3608
3609 for (i = 0; i <= bt->frame; i++)
3610 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3611
3612 return mask == 0;
3613}
3614
3615static inline int bt_subprog_enter(struct backtrack_state *bt)
3616{
3617 if (bt->frame == MAX_CALL_FRAMES - 1) {
3618 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3619 WARN_ONCE(1, "verifier backtracking bug");
3620 return -EFAULT;
3621 }
3622 bt->frame++;
3623 return 0;
3624}
3625
3626static inline int bt_subprog_exit(struct backtrack_state *bt)
3627{
3628 if (bt->frame == 0) {
3629 verbose(bt->env, "BUG subprog exit from frame 0\n");
3630 WARN_ONCE(1, "verifier backtracking bug");
3631 return -EFAULT;
3632 }
3633 bt->frame--;
3634 return 0;
3635}
3636
3637static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3638{
3639 bt->reg_masks[frame] |= 1 << reg;
3640}
3641
3642static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3643{
3644 bt->reg_masks[frame] &= ~(1 << reg);
3645}
3646
3647static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3648{
3649 bt_set_frame_reg(bt, bt->frame, reg);
3650}
3651
3652static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3653{
3654 bt_clear_frame_reg(bt, bt->frame, reg);
3655}
3656
3657static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3658{
3659 bt->stack_masks[frame] |= 1ull << slot;
3660}
3661
3662static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3663{
3664 bt->stack_masks[frame] &= ~(1ull << slot);
3665}
3666
3667static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3668{
3669 bt_set_frame_slot(bt, bt->frame, slot);
3670}
3671
3672static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3673{
3674 bt_clear_frame_slot(bt, bt->frame, slot);
3675}
3676
3677static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3678{
3679 return bt->reg_masks[frame];
3680}
3681
3682static inline u32 bt_reg_mask(struct backtrack_state *bt)
3683{
3684 return bt->reg_masks[bt->frame];
3685}
3686
3687static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3688{
3689 return bt->stack_masks[frame];
3690}
3691
3692static inline u64 bt_stack_mask(struct backtrack_state *bt)
3693{
3694 return bt->stack_masks[bt->frame];
3695}
3696
3697static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3698{
3699 return bt->reg_masks[bt->frame] & (1 << reg);
3700}
3701
3702static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3703{
3704 return bt->stack_masks[bt->frame] & (1ull << slot);
3705}
3706
d9439c21
AN
3707/* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3708static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3709{
3710 DECLARE_BITMAP(mask, 64);
3711 bool first = true;
3712 int i, n;
3713
3714 buf[0] = '\0';
3715
3716 bitmap_from_u64(mask, reg_mask);
3717 for_each_set_bit(i, mask, 32) {
3718 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3719 first = false;
3720 buf += n;
3721 buf_sz -= n;
3722 if (buf_sz < 0)
3723 break;
3724 }
3725}
3726/* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3727static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3728{
3729 DECLARE_BITMAP(mask, 64);
3730 bool first = true;
3731 int i, n;
3732
3733 buf[0] = '\0';
3734
3735 bitmap_from_u64(mask, stack_mask);
3736 for_each_set_bit(i, mask, 64) {
3737 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3738 first = false;
3739 buf += n;
3740 buf_sz -= n;
3741 if (buf_sz < 0)
3742 break;
3743 }
3744}
3745
ab5cfac1
EZ
3746static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3747
b5dc0163
AS
3748/* For given verifier state backtrack_insn() is called from the last insn to
3749 * the first insn. Its purpose is to compute a bitmask of registers and
3750 * stack slots that needs precision in the parent verifier state.
fde2a388
AN
3751 *
3752 * @idx is an index of the instruction we are currently processing;
3753 * @subseq_idx is an index of the subsequent instruction that:
3754 * - *would be* executed next, if jump history is viewed in forward order;
3755 * - *was* processed previously during backtracking.
b5dc0163 3756 */
fde2a388 3757static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
407958a0 3758 struct backtrack_state *bt)
b5dc0163
AS
3759{
3760 const struct bpf_insn_cbs cbs = {
e6ac2450 3761 .cb_call = disasm_kfunc_name,
b5dc0163
AS
3762 .cb_print = verbose,
3763 .private_data = env,
3764 };
3765 struct bpf_insn *insn = env->prog->insnsi + idx;
3766 u8 class = BPF_CLASS(insn->code);
3767 u8 opcode = BPF_OP(insn->code);
3768 u8 mode = BPF_MODE(insn->code);
407958a0
AN
3769 u32 dreg = insn->dst_reg;
3770 u32 sreg = insn->src_reg;
fde2a388 3771 u32 spi, i;
b5dc0163
AS
3772
3773 if (insn->code == 0)
3774 return 0;
496f3324 3775 if (env->log.level & BPF_LOG_LEVEL2) {
d9439c21
AN
3776 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3777 verbose(env, "mark_precise: frame%d: regs=%s ",
3778 bt->frame, env->tmp_str_buf);
3779 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3780 verbose(env, "stack=%s before ", env->tmp_str_buf);
b5dc0163
AS
3781 verbose(env, "%d: ", idx);
3782 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3783 }
3784
3785 if (class == BPF_ALU || class == BPF_ALU64) {
407958a0 3786 if (!bt_is_reg_set(bt, dreg))
b5dc0163 3787 return 0;
291d044f
SHY
3788 if (opcode == BPF_END || opcode == BPF_NEG) {
3789 /* sreg is reserved and unused
3790 * dreg still need precision before this insn
3791 */
3792 return 0;
3793 } else if (opcode == BPF_MOV) {
b5dc0163 3794 if (BPF_SRC(insn->code) == BPF_X) {
8100928c 3795 /* dreg = sreg or dreg = (s8, s16, s32)sreg
b5dc0163
AS
3796 * dreg needs precision after this insn
3797 * sreg needs precision before this insn
3798 */
407958a0
AN
3799 bt_clear_reg(bt, dreg);
3800 bt_set_reg(bt, sreg);
b5dc0163
AS
3801 } else {
3802 /* dreg = K
3803 * dreg needs precision after this insn.
3804 * Corresponding register is already marked
3805 * as precise=true in this verifier state.
3806 * No further markings in parent are necessary
3807 */
407958a0 3808 bt_clear_reg(bt, dreg);
b5dc0163
AS
3809 }
3810 } else {
3811 if (BPF_SRC(insn->code) == BPF_X) {
3812 /* dreg += sreg
3813 * both dreg and sreg need precision
3814 * before this insn
3815 */
407958a0 3816 bt_set_reg(bt, sreg);
b5dc0163
AS
3817 } /* else dreg += K
3818 * dreg still needs precision before this insn
3819 */
3820 }
3821 } else if (class == BPF_LDX) {
407958a0 3822 if (!bt_is_reg_set(bt, dreg))
b5dc0163 3823 return 0;
407958a0 3824 bt_clear_reg(bt, dreg);
b5dc0163
AS
3825
3826 /* scalars can only be spilled into stack w/o losing precision.
3827 * Load from any other memory can be zero extended.
3828 * The desire to keep that precision is already indicated
3829 * by 'precise' mark in corresponding register of this state.
3830 * No further tracking necessary.
3831 */
3832 if (insn->src_reg != BPF_REG_FP)
3833 return 0;
b5dc0163
AS
3834
3835 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3836 * that [fp - off] slot contains scalar that needs to be
3837 * tracked with precision
3838 */
3839 spi = (-insn->off - 1) / BPF_REG_SIZE;
3840 if (spi >= 64) {
3841 verbose(env, "BUG spi %d\n", spi);
3842 WARN_ONCE(1, "verifier backtracking bug");
3843 return -EFAULT;
3844 }
407958a0 3845 bt_set_slot(bt, spi);
b3b50f05 3846 } else if (class == BPF_STX || class == BPF_ST) {
407958a0 3847 if (bt_is_reg_set(bt, dreg))
b3b50f05 3848 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
3849 * to access memory. It means backtracking
3850 * encountered a case of pointer subtraction.
3851 */
3852 return -ENOTSUPP;
3853 /* scalars can only be spilled into stack */
3854 if (insn->dst_reg != BPF_REG_FP)
3855 return 0;
b5dc0163
AS
3856 spi = (-insn->off - 1) / BPF_REG_SIZE;
3857 if (spi >= 64) {
3858 verbose(env, "BUG spi %d\n", spi);
3859 WARN_ONCE(1, "verifier backtracking bug");
3860 return -EFAULT;
3861 }
407958a0 3862 if (!bt_is_slot_set(bt, spi))
b5dc0163 3863 return 0;
407958a0 3864 bt_clear_slot(bt, spi);
b3b50f05 3865 if (class == BPF_STX)
407958a0 3866 bt_set_reg(bt, sreg);
b5dc0163 3867 } else if (class == BPF_JMP || class == BPF_JMP32) {
fde2a388
AN
3868 if (bpf_pseudo_call(insn)) {
3869 int subprog_insn_idx, subprog;
3870
3871 subprog_insn_idx = idx + insn->imm + 1;
3872 subprog = find_subprog(env, subprog_insn_idx);
3873 if (subprog < 0)
3874 return -EFAULT;
3875
3876 if (subprog_is_global(env, subprog)) {
3877 /* check that jump history doesn't have any
3878 * extra instructions from subprog; the next
3879 * instruction after call to global subprog
3880 * should be literally next instruction in
3881 * caller program
3882 */
3883 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3884 /* r1-r5 are invalidated after subprog call,
3885 * so for global func call it shouldn't be set
3886 * anymore
3887 */
3888 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3889 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3890 WARN_ONCE(1, "verifier backtracking bug");
3891 return -EFAULT;
3892 }
3893 /* global subprog always sets R0 */
3894 bt_clear_reg(bt, BPF_REG_0);
3895 return 0;
3896 } else {
3897 /* static subprog call instruction, which
3898 * means that we are exiting current subprog,
3899 * so only r1-r5 could be still requested as
3900 * precise, r0 and r6-r10 or any stack slot in
3901 * the current frame should be zero by now
3902 */
3903 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3904 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3905 WARN_ONCE(1, "verifier backtracking bug");
3906 return -EFAULT;
3907 }
3908 /* we don't track register spills perfectly,
3909 * so fallback to force-precise instead of failing */
3910 if (bt_stack_mask(bt) != 0)
3911 return -ENOTSUPP;
3912 /* propagate r1-r5 to the caller */
3913 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3914 if (bt_is_reg_set(bt, i)) {
3915 bt_clear_reg(bt, i);
3916 bt_set_frame_reg(bt, bt->frame - 1, i);
3917 }
3918 }
3919 if (bt_subprog_exit(bt))
3920 return -EFAULT;
3921 return 0;
3922 }
ab5cfac1
EZ
3923 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3924 /* exit from callback subprog to callback-calling helper or
3925 * kfunc call. Use idx/subseq_idx check to discern it from
3926 * straight line code backtracking.
3927 * Unlike the subprog call handling above, we shouldn't
3928 * propagate precision of r1-r5 (if any requested), as they are
3929 * not actually arguments passed directly to callback subprogs
be2ef816 3930 */
fde2a388
AN
3931 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3932 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3933 WARN_ONCE(1, "verifier backtracking bug");
3934 return -EFAULT;
3935 }
3936 if (bt_stack_mask(bt) != 0)
be2ef816 3937 return -ENOTSUPP;
fde2a388
AN
3938 /* clear r1-r5 in callback subprog's mask */
3939 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3940 bt_clear_reg(bt, i);
3941 if (bt_subprog_exit(bt))
3942 return -EFAULT;
3943 return 0;
3944 } else if (opcode == BPF_CALL) {
d3178e8a
HS
3945 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3946 * catch this error later. Make backtracking conservative
3947 * with ENOTSUPP.
3948 */
3949 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3950 return -ENOTSUPP;
b5dc0163 3951 /* regular helper call sets R0 */
407958a0
AN
3952 bt_clear_reg(bt, BPF_REG_0);
3953 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
b5dc0163
AS
3954 /* if backtracing was looking for registers R1-R5
3955 * they should have been found already.
3956 */
407958a0 3957 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
b5dc0163
AS
3958 WARN_ONCE(1, "verifier backtracking bug");
3959 return -EFAULT;
3960 }
3961 } else if (opcode == BPF_EXIT) {
fde2a388
AN
3962 bool r0_precise;
3963
ab5cfac1
EZ
3964 /* Backtracking to a nested function call, 'idx' is a part of
3965 * the inner frame 'subseq_idx' is a part of the outer frame.
3966 * In case of a regular function call, instructions giving
3967 * precision to registers R1-R5 should have been found already.
3968 * In case of a callback, it is ok to have R1-R5 marked for
3969 * backtracking, as these registers are set by the function
3970 * invoking callback.
3971 */
3972 if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3973 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3974 bt_clear_reg(bt, i);
fde2a388 3975 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
fde2a388
AN
3976 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3977 WARN_ONCE(1, "verifier backtracking bug");
3978 return -EFAULT;
3979 }
3980
3981 /* BPF_EXIT in subprog or callback always returns
3982 * right after the call instruction, so by checking
3983 * whether the instruction at subseq_idx-1 is subprog
3984 * call or not we can distinguish actual exit from
3985 * *subprog* from exit from *callback*. In the former
3986 * case, we need to propagate r0 precision, if
3987 * necessary. In the former we never do that.
3988 */
3989 r0_precise = subseq_idx - 1 >= 0 &&
3990 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3991 bt_is_reg_set(bt, BPF_REG_0);
3992
3993 bt_clear_reg(bt, BPF_REG_0);
3994 if (bt_subprog_enter(bt))
3995 return -EFAULT;
3996
3997 if (r0_precise)
3998 bt_set_reg(bt, BPF_REG_0);
3999 /* r6-r9 and stack slots will stay set in caller frame
4000 * bitmasks until we return back from callee(s)
4001 */
4002 return 0;
71b547f5 4003 } else if (BPF_SRC(insn->code) == BPF_X) {
407958a0 4004 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
71b547f5
DB
4005 return 0;
4006 /* dreg <cond> sreg
4007 * Both dreg and sreg need precision before
4008 * this insn. If only sreg was marked precise
4009 * before it would be equally necessary to
4010 * propagate it to dreg.
4011 */
407958a0
AN
4012 bt_set_reg(bt, dreg);
4013 bt_set_reg(bt, sreg);
71b547f5
DB
4014 /* else dreg <cond> K
4015 * Only dreg still needs precision before
4016 * this insn, so for the K-based conditional
4017 * there is nothing new to be marked.
4018 */
b5dc0163
AS
4019 }
4020 } else if (class == BPF_LD) {
407958a0 4021 if (!bt_is_reg_set(bt, dreg))
b5dc0163 4022 return 0;
407958a0 4023 bt_clear_reg(bt, dreg);
b5dc0163
AS
4024 /* It's ld_imm64 or ld_abs or ld_ind.
4025 * For ld_imm64 no further tracking of precision
4026 * into parent is necessary
4027 */
4028 if (mode == BPF_IND || mode == BPF_ABS)
4029 /* to be analyzed */
4030 return -ENOTSUPP;
b5dc0163
AS
4031 }
4032 return 0;
4033}
4034
4035/* the scalar precision tracking algorithm:
4036 * . at the start all registers have precise=false.
4037 * . scalar ranges are tracked as normal through alu and jmp insns.
4038 * . once precise value of the scalar register is used in:
4039 * . ptr + scalar alu
4040 * . if (scalar cond K|scalar)
4041 * . helper_call(.., scalar, ...) where ARG_CONST is expected
4042 * backtrack through the verifier states and mark all registers and
4043 * stack slots with spilled constants that these scalar regisers
4044 * should be precise.
4045 * . during state pruning two registers (or spilled stack slots)
4046 * are equivalent if both are not precise.
4047 *
4048 * Note the verifier cannot simply walk register parentage chain,
4049 * since many different registers and stack slots could have been
4050 * used to compute single precise scalar.
4051 *
4052 * The approach of starting with precise=true for all registers and then
4053 * backtrack to mark a register as not precise when the verifier detects
4054 * that program doesn't care about specific value (e.g., when helper
4055 * takes register as ARG_ANYTHING parameter) is not safe.
4056 *
4057 * It's ok to walk single parentage chain of the verifier states.
4058 * It's possible that this backtracking will go all the way till 1st insn.
4059 * All other branches will be explored for needing precision later.
4060 *
4061 * The backtracking needs to deal with cases like:
4062 * 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)
4063 * r9 -= r8
4064 * r5 = r9
4065 * if r5 > 0x79f goto pc+7
4066 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4067 * r5 += 1
4068 * ...
4069 * call bpf_perf_event_output#25
4070 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4071 *
4072 * and this case:
4073 * r6 = 1
4074 * call foo // uses callee's r6 inside to compute r0
4075 * r0 += r6
4076 * if r0 == 0 goto
4077 *
4078 * to track above reg_mask/stack_mask needs to be independent for each frame.
4079 *
4080 * Also if parent's curframe > frame where backtracking started,
4081 * the verifier need to mark registers in both frames, otherwise callees
4082 * may incorrectly prune callers. This is similar to
4083 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4084 *
4085 * For now backtracking falls back into conservative marking.
4086 */
4087static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4088 struct bpf_verifier_state *st)
4089{
4090 struct bpf_func_state *func;
4091 struct bpf_reg_state *reg;
4092 int i, j;
4093
d9439c21
AN
4094 if (env->log.level & BPF_LOG_LEVEL2) {
4095 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4096 st->curframe);
4097 }
4098
b5dc0163
AS
4099 /* big hammer: mark all scalars precise in this path.
4100 * pop_stack may still get !precise scalars.
f63181b6
AN
4101 * We also skip current state and go straight to first parent state,
4102 * because precision markings in current non-checkpointed state are
4103 * not needed. See why in the comment in __mark_chain_precision below.
b5dc0163 4104 */
f63181b6 4105 for (st = st->parent; st; st = st->parent) {
b5dc0163
AS
4106 for (i = 0; i <= st->curframe; i++) {
4107 func = st->frame[i];
4108 for (j = 0; j < BPF_REG_FP; j++) {
4109 reg = &func->regs[j];
d9439c21 4110 if (reg->type != SCALAR_VALUE || reg->precise)
b5dc0163
AS
4111 continue;
4112 reg->precise = true;
d9439c21
AN
4113 if (env->log.level & BPF_LOG_LEVEL2) {
4114 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4115 i, j);
4116 }
b5dc0163
AS
4117 }
4118 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
27113c59 4119 if (!is_spilled_reg(&func->stack[j]))
b5dc0163
AS
4120 continue;
4121 reg = &func->stack[j].spilled_ptr;
d9439c21 4122 if (reg->type != SCALAR_VALUE || reg->precise)
b5dc0163
AS
4123 continue;
4124 reg->precise = true;
d9439c21
AN
4125 if (env->log.level & BPF_LOG_LEVEL2) {
4126 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4127 i, -(j + 1) * 8);
4128 }
b5dc0163
AS
4129 }
4130 }
f63181b6 4131 }
b5dc0163
AS
4132}
4133
7a830b53
AN
4134static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4135{
4136 struct bpf_func_state *func;
4137 struct bpf_reg_state *reg;
4138 int i, j;
4139
4140 for (i = 0; i <= st->curframe; i++) {
4141 func = st->frame[i];
4142 for (j = 0; j < BPF_REG_FP; j++) {
4143 reg = &func->regs[j];
4144 if (reg->type != SCALAR_VALUE)
4145 continue;
4146 reg->precise = false;
4147 }
4148 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4149 if (!is_spilled_reg(&func->stack[j]))
4150 continue;
4151 reg = &func->stack[j].spilled_ptr;
4152 if (reg->type != SCALAR_VALUE)
4153 continue;
4154 reg->precise = false;
4155 }
4156 }
4157}
4158
904e6ddf
EZ
4159static bool idset_contains(struct bpf_idset *s, u32 id)
4160{
4161 u32 i;
4162
4163 for (i = 0; i < s->count; ++i)
4164 if (s->ids[i] == id)
4165 return true;
4166
4167 return false;
4168}
4169
4170static int idset_push(struct bpf_idset *s, u32 id)
4171{
4172 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4173 return -EFAULT;
4174 s->ids[s->count++] = id;
4175 return 0;
4176}
4177
4178static void idset_reset(struct bpf_idset *s)
4179{
4180 s->count = 0;
4181}
4182
4183/* Collect a set of IDs for all registers currently marked as precise in env->bt.
4184 * Mark all registers with these IDs as precise.
4185 */
4186static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4187{
4188 struct bpf_idset *precise_ids = &env->idset_scratch;
4189 struct backtrack_state *bt = &env->bt;
4190 struct bpf_func_state *func;
4191 struct bpf_reg_state *reg;
4192 DECLARE_BITMAP(mask, 64);
4193 int i, fr;
4194
4195 idset_reset(precise_ids);
4196
4197 for (fr = bt->frame; fr >= 0; fr--) {
4198 func = st->frame[fr];
4199
4200 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4201 for_each_set_bit(i, mask, 32) {
4202 reg = &func->regs[i];
4203 if (!reg->id || reg->type != SCALAR_VALUE)
4204 continue;
4205 if (idset_push(precise_ids, reg->id))
4206 return -EFAULT;
4207 }
4208
4209 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4210 for_each_set_bit(i, mask, 64) {
4211 if (i >= func->allocated_stack / BPF_REG_SIZE)
4212 break;
4213 if (!is_spilled_scalar_reg(&func->stack[i]))
4214 continue;
4215 reg = &func->stack[i].spilled_ptr;
4216 if (!reg->id)
4217 continue;
4218 if (idset_push(precise_ids, reg->id))
4219 return -EFAULT;
4220 }
4221 }
4222
4223 for (fr = 0; fr <= st->curframe; ++fr) {
4224 func = st->frame[fr];
4225
4226 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4227 reg = &func->regs[i];
4228 if (!reg->id)
4229 continue;
4230 if (!idset_contains(precise_ids, reg->id))
4231 continue;
4232 bt_set_frame_reg(bt, fr, i);
4233 }
4234 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4235 if (!is_spilled_scalar_reg(&func->stack[i]))
4236 continue;
4237 reg = &func->stack[i].spilled_ptr;
4238 if (!reg->id)
4239 continue;
4240 if (!idset_contains(precise_ids, reg->id))
4241 continue;
4242 bt_set_frame_slot(bt, fr, i);
4243 }
4244 }
4245
4246 return 0;
4247}
4248
f63181b6
AN
4249/*
4250 * __mark_chain_precision() backtracks BPF program instruction sequence and
4251 * chain of verifier states making sure that register *regno* (if regno >= 0)
4252 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4253 * SCALARS, as well as any other registers and slots that contribute to
4254 * a tracked state of given registers/stack slots, depending on specific BPF
4255 * assembly instructions (see backtrack_insns() for exact instruction handling
4256 * logic). This backtracking relies on recorded jmp_history and is able to
4257 * traverse entire chain of parent states. This process ends only when all the
4258 * necessary registers/slots and their transitive dependencies are marked as
4259 * precise.
4260 *
4261 * One important and subtle aspect is that precise marks *do not matter* in
4262 * the currently verified state (current state). It is important to understand
4263 * why this is the case.
4264 *
4265 * First, note that current state is the state that is not yet "checkpointed",
4266 * i.e., it is not yet put into env->explored_states, and it has no children
4267 * states as well. It's ephemeral, and can end up either a) being discarded if
4268 * compatible explored state is found at some point or BPF_EXIT instruction is
4269 * reached or b) checkpointed and put into env->explored_states, branching out
4270 * into one or more children states.
4271 *
4272 * In the former case, precise markings in current state are completely
4273 * ignored by state comparison code (see regsafe() for details). Only
4274 * checkpointed ("old") state precise markings are important, and if old
4275 * state's register/slot is precise, regsafe() assumes current state's
4276 * register/slot as precise and checks value ranges exactly and precisely. If
4277 * states turn out to be compatible, current state's necessary precise
4278 * markings and any required parent states' precise markings are enforced
4279 * after the fact with propagate_precision() logic, after the fact. But it's
4280 * important to realize that in this case, even after marking current state
4281 * registers/slots as precise, we immediately discard current state. So what
4282 * actually matters is any of the precise markings propagated into current
4283 * state's parent states, which are always checkpointed (due to b) case above).
4284 * As such, for scenario a) it doesn't matter if current state has precise
4285 * markings set or not.
4286 *
4287 * Now, for the scenario b), checkpointing and forking into child(ren)
4288 * state(s). Note that before current state gets to checkpointing step, any
4289 * processed instruction always assumes precise SCALAR register/slot
4290 * knowledge: if precise value or range is useful to prune jump branch, BPF
4291 * verifier takes this opportunity enthusiastically. Similarly, when
4292 * register's value is used to calculate offset or memory address, exact
4293 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4294 * what we mentioned above about state comparison ignoring precise markings
4295 * during state comparison, BPF verifier ignores and also assumes precise
4296 * markings *at will* during instruction verification process. But as verifier
4297 * assumes precision, it also propagates any precision dependencies across
4298 * parent states, which are not yet finalized, so can be further restricted
4299 * based on new knowledge gained from restrictions enforced by their children
4300 * states. This is so that once those parent states are finalized, i.e., when
4301 * they have no more active children state, state comparison logic in
4302 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4303 * required for correctness.
4304 *
4305 * To build a bit more intuition, note also that once a state is checkpointed,
4306 * the path we took to get to that state is not important. This is crucial
4307 * property for state pruning. When state is checkpointed and finalized at
4308 * some instruction index, it can be correctly and safely used to "short
4309 * circuit" any *compatible* state that reaches exactly the same instruction
4310 * index. I.e., if we jumped to that instruction from a completely different
4311 * code path than original finalized state was derived from, it doesn't
4312 * matter, current state can be discarded because from that instruction
4313 * forward having a compatible state will ensure we will safely reach the
4314 * exit. States describe preconditions for further exploration, but completely
4315 * forget the history of how we got here.
4316 *
4317 * This also means that even if we needed precise SCALAR range to get to
4318 * finalized state, but from that point forward *that same* SCALAR register is
4319 * never used in a precise context (i.e., it's precise value is not needed for
4320 * correctness), it's correct and safe to mark such register as "imprecise"
4321 * (i.e., precise marking set to false). This is what we rely on when we do
4322 * not set precise marking in current state. If no child state requires
4323 * precision for any given SCALAR register, it's safe to dictate that it can
4324 * be imprecise. If any child state does require this register to be precise,
4325 * we'll mark it precise later retroactively during precise markings
4326 * propagation from child state to parent states.
7a830b53
AN
4327 *
4328 * Skipping precise marking setting in current state is a mild version of
4329 * relying on the above observation. But we can utilize this property even
4330 * more aggressively by proactively forgetting any precise marking in the
4331 * current state (which we inherited from the parent state), right before we
4332 * checkpoint it and branch off into new child state. This is done by
4333 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4334 * finalized states which help in short circuiting more future states.
f63181b6 4335 */
f655badf 4336static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
b5dc0163 4337{
407958a0 4338 struct backtrack_state *bt = &env->bt;
b5dc0163
AS
4339 struct bpf_verifier_state *st = env->cur_state;
4340 int first_idx = st->first_insn_idx;
4341 int last_idx = env->insn_idx;
d84b1a67 4342 int subseq_idx = -1;
b5dc0163
AS
4343 struct bpf_func_state *func;
4344 struct bpf_reg_state *reg;
b5dc0163 4345 bool skip_first = true;
d84b1a67 4346 int i, fr, err;
b5dc0163 4347
2c78ee89 4348 if (!env->bpf_capable)
b5dc0163
AS
4349 return 0;
4350
407958a0 4351 /* set frame number from which we are starting to backtrack */
f655badf 4352 bt_init(bt, env->cur_state->curframe);
407958a0 4353
f63181b6
AN
4354 /* Do sanity checks against current state of register and/or stack
4355 * slot, but don't set precise flag in current state, as precision
4356 * tracking in the current state is unnecessary.
4357 */
f655badf 4358 func = st->frame[bt->frame];
a3ce685d
AS
4359 if (regno >= 0) {
4360 reg = &func->regs[regno];
4361 if (reg->type != SCALAR_VALUE) {
4362 WARN_ONCE(1, "backtracing misuse");
4363 return -EFAULT;
4364 }
407958a0 4365 bt_set_reg(bt, regno);
b5dc0163 4366 }
b5dc0163 4367
407958a0 4368 if (bt_empty(bt))
a3ce685d 4369 return 0;
be2ef816 4370
b5dc0163
AS
4371 for (;;) {
4372 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
4373 u32 history = st->jmp_history_cnt;
4374
d9439c21 4375 if (env->log.level & BPF_LOG_LEVEL2) {
d84b1a67
AN
4376 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4377 bt->frame, last_idx, first_idx, subseq_idx);
d9439c21 4378 }
be2ef816 4379
904e6ddf
EZ
4380 /* If some register with scalar ID is marked as precise,
4381 * make sure that all registers sharing this ID are also precise.
4382 * This is needed to estimate effect of find_equal_scalars().
4383 * Do this at the last instruction of each state,
4384 * bpf_reg_state::id fields are valid for these instructions.
4385 *
4386 * Allows to track precision in situation like below:
4387 *
4388 * r2 = unknown value
4389 * ...
4390 * --- state #0 ---
4391 * ...
4392 * r1 = r2 // r1 and r2 now share the same ID
4393 * ...
4394 * --- state #1 {r1.id = A, r2.id = A} ---
4395 * ...
4396 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4397 * ...
4398 * --- state #2 {r1.id = A, r2.id = A} ---
4399 * r3 = r10
4400 * r3 += r1 // need to mark both r1 and r2
4401 */
4402 if (mark_precise_scalar_ids(env, st))
4403 return -EFAULT;
4404
be2ef816
AN
4405 if (last_idx < 0) {
4406 /* we are at the entry into subprog, which
4407 * is expected for global funcs, but only if
4408 * requested precise registers are R1-R5
4409 * (which are global func's input arguments)
4410 */
4411 if (st->curframe == 0 &&
4412 st->frame[0]->subprogno > 0 &&
4413 st->frame[0]->callsite == BPF_MAIN_FUNC &&
407958a0
AN
4414 bt_stack_mask(bt) == 0 &&
4415 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4416 bitmap_from_u64(mask, bt_reg_mask(bt));
be2ef816
AN
4417 for_each_set_bit(i, mask, 32) {
4418 reg = &st->frame[0]->regs[i];
81335f90
AN
4419 bt_clear_reg(bt, i);
4420 if (reg->type == SCALAR_VALUE)
4421 reg->precise = true;
be2ef816
AN
4422 }
4423 return 0;
4424 }
4425
407958a0
AN
4426 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4427 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
be2ef816
AN
4428 WARN_ONCE(1, "verifier backtracking bug");
4429 return -EFAULT;
4430 }
4431
d84b1a67 4432 for (i = last_idx;;) {
b5dc0163
AS
4433 if (skip_first) {
4434 err = 0;
4435 skip_first = false;
4436 } else {
d84b1a67 4437 err = backtrack_insn(env, i, subseq_idx, bt);
b5dc0163
AS
4438 }
4439 if (err == -ENOTSUPP) {
c50c0b57 4440 mark_all_scalars_precise(env, env->cur_state);
407958a0 4441 bt_reset(bt);
b5dc0163
AS
4442 return 0;
4443 } else if (err) {
4444 return err;
4445 }
407958a0 4446 if (bt_empty(bt))
b5dc0163
AS
4447 /* Found assignment(s) into tracked register in this state.
4448 * Since this state is already marked, just return.
4449 * Nothing to be tracked further in the parent state.
4450 */
4451 return 0;
d84b1a67 4452 subseq_idx = i;
b5dc0163 4453 i = get_prev_insn_idx(st, i, &history);
4bb7ea94
AN
4454 if (i == -ENOENT)
4455 break;
b5dc0163
AS
4456 if (i >= env->prog->len) {
4457 /* This can happen if backtracking reached insn 0
4458 * and there are still reg_mask or stack_mask
4459 * to backtrack.
4460 * It means the backtracking missed the spot where
4461 * particular register was initialized with a constant.
4462 */
4463 verbose(env, "BUG backtracking idx %d\n", i);
4464 WARN_ONCE(1, "verifier backtracking bug");
4465 return -EFAULT;
4466 }
4467 }
4468 st = st->parent;
4469 if (!st)
4470 break;
4471
1ef22b68
AN
4472 for (fr = bt->frame; fr >= 0; fr--) {
4473 func = st->frame[fr];
4474 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4475 for_each_set_bit(i, mask, 32) {
4476 reg = &func->regs[i];
4477 if (reg->type != SCALAR_VALUE) {
4478 bt_clear_frame_reg(bt, fr, i);
4479 continue;
4480 }
4481 if (reg->precise)
4482 bt_clear_frame_reg(bt, fr, i);
4483 else
4484 reg->precise = true;
a3ce685d 4485 }
b5dc0163 4486
1ef22b68
AN
4487 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4488 for_each_set_bit(i, mask, 64) {
4489 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4490 /* the sequence of instructions:
4491 * 2: (bf) r3 = r10
4492 * 3: (7b) *(u64 *)(r3 -8) = r0
4493 * 4: (79) r4 = *(u64 *)(r10 -8)
4494 * doesn't contain jmps. It's backtracked
4495 * as a single block.
4496 * During backtracking insn 3 is not recognized as
4497 * stack access, so at the end of backtracking
4498 * stack slot fp-8 is still marked in stack_mask.
4499 * However the parent state may not have accessed
4500 * fp-8 and it's "unallocated" stack space.
4501 * In such case fallback to conservative.
4502 */
c50c0b57 4503 mark_all_scalars_precise(env, env->cur_state);
1ef22b68
AN
4504 bt_reset(bt);
4505 return 0;
4506 }
b5dc0163 4507
1ef22b68
AN
4508 if (!is_spilled_scalar_reg(&func->stack[i])) {
4509 bt_clear_frame_slot(bt, fr, i);
4510 continue;
4511 }
4512 reg = &func->stack[i].spilled_ptr;
4513 if (reg->precise)
4514 bt_clear_frame_slot(bt, fr, i);
4515 else
4516 reg->precise = true;
4517 }
4518 if (env->log.level & BPF_LOG_LEVEL2) {
4519 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4520 bt_frame_reg_mask(bt, fr));
4521 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4522 fr, env->tmp_str_buf);
4523 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4524 bt_frame_stack_mask(bt, fr));
4525 verbose(env, "stack=%s: ", env->tmp_str_buf);
4526 print_verifier_state(env, func, true);
a3ce685d 4527 }
b5dc0163
AS
4528 }
4529
407958a0 4530 if (bt_empty(bt))
c50c0b57 4531 return 0;
b5dc0163 4532
d84b1a67 4533 subseq_idx = first_idx;
b5dc0163
AS
4534 last_idx = st->last_insn_idx;
4535 first_idx = st->first_insn_idx;
4536 }
c50c0b57
AN
4537
4538 /* if we still have requested precise regs or slots, we missed
4539 * something (e.g., stack access through non-r10 register), so
4540 * fallback to marking all precise
4541 */
4542 if (!bt_empty(bt)) {
4543 mark_all_scalars_precise(env, env->cur_state);
4544 bt_reset(bt);
4545 }
4546
b5dc0163
AS
4547 return 0;
4548}
4549
eb1f7f71 4550int mark_chain_precision(struct bpf_verifier_env *env, int regno)
a3ce685d 4551{
f655badf 4552 return __mark_chain_precision(env, regno);
a3ce685d
AS
4553}
4554
f655badf
AN
4555/* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4556 * desired reg and stack masks across all relevant frames
4557 */
4558static int mark_chain_precision_batch(struct bpf_verifier_env *env)
a3ce685d 4559{
f655badf 4560 return __mark_chain_precision(env, -1);
a3ce685d 4561}
b5dc0163 4562
1be7f75d
AS
4563static bool is_spillable_regtype(enum bpf_reg_type type)
4564{
c25b2ae1 4565 switch (base_type(type)) {
1be7f75d 4566 case PTR_TO_MAP_VALUE:
1be7f75d
AS
4567 case PTR_TO_STACK:
4568 case PTR_TO_CTX:
969bf05e 4569 case PTR_TO_PACKET:
de8f3a83 4570 case PTR_TO_PACKET_META:
969bf05e 4571 case PTR_TO_PACKET_END:
d58e468b 4572 case PTR_TO_FLOW_KEYS:
1be7f75d 4573 case CONST_PTR_TO_MAP:
c64b7983 4574 case PTR_TO_SOCKET:
46f8bc92 4575 case PTR_TO_SOCK_COMMON:
655a51e5 4576 case PTR_TO_TCP_SOCK:
fada7fdc 4577 case PTR_TO_XDP_SOCK:
65726b5b 4578 case PTR_TO_BTF_ID:
20b2aff4 4579 case PTR_TO_BUF:
744ea4e3 4580 case PTR_TO_MEM:
69c087ba
YS
4581 case PTR_TO_FUNC:
4582 case PTR_TO_MAP_KEY:
1be7f75d
AS
4583 return true;
4584 default:
4585 return false;
4586 }
4587}
4588
cc2b14d5
AS
4589/* Does this register contain a constant zero? */
4590static bool register_is_null(struct bpf_reg_state *reg)
4591{
4592 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4593}
4594
f7cf25b2
AS
4595static bool register_is_const(struct bpf_reg_state *reg)
4596{
4597 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4598}
4599
5689d49b
YS
4600static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4601{
4602 return tnum_is_unknown(reg->var_off) &&
4603 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4604 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4605 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4606 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4607}
4608
4609static bool register_is_bounded(struct bpf_reg_state *reg)
4610{
4611 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4612}
4613
6e7e63cb
JH
4614static bool __is_pointer_value(bool allow_ptr_leaks,
4615 const struct bpf_reg_state *reg)
4616{
4617 if (allow_ptr_leaks)
4618 return false;
4619
4620 return reg->type != SCALAR_VALUE;
4621}
4622
71f656a5
EZ
4623/* Copy src state preserving dst->parent and dst->live fields */
4624static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4625{
4626 struct bpf_reg_state *parent = dst->parent;
4627 enum bpf_reg_liveness live = dst->live;
4628
4629 *dst = *src;
4630 dst->parent = parent;
4631 dst->live = live;
4632}
4633
f7cf25b2 4634static void save_register_state(struct bpf_func_state *state,
354e8f19
MKL
4635 int spi, struct bpf_reg_state *reg,
4636 int size)
f7cf25b2
AS
4637{
4638 int i;
4639
71f656a5 4640 copy_register_state(&state->stack[spi].spilled_ptr, reg);
354e8f19
MKL
4641 if (size == BPF_REG_SIZE)
4642 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
f7cf25b2 4643
354e8f19
MKL
4644 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4645 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
f7cf25b2 4646
354e8f19
MKL
4647 /* size < 8 bytes spill */
4648 for (; i; i--)
4649 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
f7cf25b2
AS
4650}
4651
ecdf985d
EZ
4652static bool is_bpf_st_mem(struct bpf_insn *insn)
4653{
4654 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4655}
4656
01f810ac 4657/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
4658 * stack boundary and alignment are checked in check_mem_access()
4659 */
01f810ac
AM
4660static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4661 /* stack frame we're writing to */
4662 struct bpf_func_state *state,
4663 int off, int size, int value_regno,
4664 int insn_idx)
17a52670 4665{
f4d7e40a 4666 struct bpf_func_state *cur; /* state of the current function */
638f5b90 4667 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
ecdf985d 4668 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
f7cf25b2 4669 struct bpf_reg_state *reg = NULL;
ecdf985d 4670 u32 dst_reg = insn->dst_reg;
638f5b90 4671
c69431aa 4672 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
4673 if (err)
4674 return err;
9c399760
AS
4675 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4676 * so it's aligned access and [off, off + size) are within stack limits
4677 */
638f5b90
AS
4678 if (!env->allow_ptr_leaks &&
4679 state->stack[spi].slot_type[0] == STACK_SPILL &&
4680 size != BPF_REG_SIZE) {
4681 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4682 return -EACCES;
4683 }
17a52670 4684
f4d7e40a 4685 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
4686 if (value_regno >= 0)
4687 reg = &cur->regs[value_regno];
2039f26f
DB
4688 if (!env->bypass_spec_v4) {
4689 bool sanitize = reg && is_spillable_regtype(reg->type);
4690
4691 for (i = 0; i < size; i++) {
e4f4db47
LG
4692 u8 type = state->stack[spi].slot_type[i];
4693
4694 if (type != STACK_MISC && type != STACK_ZERO) {
2039f26f
DB
4695 sanitize = true;
4696 break;
4697 }
4698 }
4699
4700 if (sanitize)
4701 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4702 }
17a52670 4703
ef8fc7a0
KKD
4704 err = destroy_if_dynptr_stack_slot(env, state, spi);
4705 if (err)
4706 return err;
4707
0f55f9ed 4708 mark_stack_slot_scratched(env, spi);
354e8f19 4709 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2c78ee89 4710 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
4711 if (dst_reg != BPF_REG_FP) {
4712 /* The backtracking logic can only recognize explicit
4713 * stack slot address like [fp - 8]. Other spill of
8fb33b60 4714 * scalar via different register has to be conservative.
b5dc0163
AS
4715 * Backtrack from here and mark all registers as precise
4716 * that contributed into 'reg' being a constant.
4717 */
4718 err = mark_chain_precision(env, value_regno);
4719 if (err)
4720 return err;
4721 }
354e8f19 4722 save_register_state(state, spi, reg, size);
713274f1
MM
4723 /* Break the relation on a narrowing spill. */
4724 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4725 state->stack[spi].spilled_ptr.id = 0;
ecdf985d
EZ
4726 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4727 insn->imm != 0 && env->bpf_capable) {
4728 struct bpf_reg_state fake_reg = {};
4729
811c3636 4730 __mark_reg_known(&fake_reg, insn->imm);
ecdf985d
EZ
4731 fake_reg.type = SCALAR_VALUE;
4732 save_register_state(state, spi, &fake_reg, size);
f7cf25b2 4733 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 4734 /* register containing pointer is being spilled into stack */
9c399760 4735 if (size != BPF_REG_SIZE) {
f7cf25b2 4736 verbose_linfo(env, insn_idx, "; ");
61bd5218 4737 verbose(env, "invalid size of register spill\n");
17a52670
AS
4738 return -EACCES;
4739 }
f7cf25b2 4740 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
4741 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4742 return -EINVAL;
4743 }
354e8f19 4744 save_register_state(state, spi, reg, size);
9c399760 4745 } else {
cc2b14d5
AS
4746 u8 type = STACK_MISC;
4747
679c782d
EC
4748 /* regular write of data into stack destroys any spilled ptr */
4749 state->stack[spi].spilled_ptr.type = NOT_INIT;
06accc87
AN
4750 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4751 if (is_stack_slot_special(&state->stack[spi]))
0bae2d4d 4752 for (i = 0; i < BPF_REG_SIZE; i++)
354e8f19 4753 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
9c399760 4754
cc2b14d5
AS
4755 /* only mark the slot as written if all 8 bytes were written
4756 * otherwise read propagation may incorrectly stop too soon
4757 * when stack slots are partially written.
4758 * This heuristic means that read propagation will be
4759 * conservative, since it will add reg_live_read marks
4760 * to stack slots all the way to first state when programs
4761 * writes+reads less than 8 bytes
4762 */
4763 if (size == BPF_REG_SIZE)
4764 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4765
4766 /* when we zero initialize stack slots mark them as such */
ecdf985d
EZ
4767 if ((reg && register_is_null(reg)) ||
4768 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
b5dc0163
AS
4769 /* backtracking doesn't work for STACK_ZERO yet. */
4770 err = mark_chain_precision(env, value_regno);
4771 if (err)
4772 return err;
cc2b14d5 4773 type = STACK_ZERO;
b5dc0163 4774 }
cc2b14d5 4775
0bae2d4d 4776 /* Mark slots affected by this stack write. */
9c399760 4777 for (i = 0; i < size; i++)
638f5b90 4778 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 4779 type;
17a52670
AS
4780 }
4781 return 0;
4782}
4783
01f810ac
AM
4784/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4785 * known to contain a variable offset.
4786 * This function checks whether the write is permitted and conservatively
4787 * tracks the effects of the write, considering that each stack slot in the
4788 * dynamic range is potentially written to.
4789 *
4790 * 'off' includes 'regno->off'.
4791 * 'value_regno' can be -1, meaning that an unknown value is being written to
4792 * the stack.
4793 *
4794 * Spilled pointers in range are not marked as written because we don't know
4795 * what's going to be actually written. This means that read propagation for
4796 * future reads cannot be terminated by this write.
4797 *
4798 * For privileged programs, uninitialized stack slots are considered
4799 * initialized by this write (even though we don't know exactly what offsets
4800 * are going to be written to). The idea is that we don't want the verifier to
4801 * reject future reads that access slots written to through variable offsets.
4802 */
4803static int check_stack_write_var_off(struct bpf_verifier_env *env,
4804 /* func where register points to */
4805 struct bpf_func_state *state,
4806 int ptr_regno, int off, int size,
4807 int value_regno, int insn_idx)
4808{
4809 struct bpf_func_state *cur; /* state of the current function */
4810 int min_off, max_off;
4811 int i, err;
4812 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
31ff2135 4813 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
01f810ac
AM
4814 bool writing_zero = false;
4815 /* set if the fact that we're writing a zero is used to let any
4816 * stack slots remain STACK_ZERO
4817 */
4818 bool zero_used = false;
4819
4820 cur = env->cur_state->frame[env->cur_state->curframe];
4821 ptr_reg = &cur->regs[ptr_regno];
4822 min_off = ptr_reg->smin_value + off;
4823 max_off = ptr_reg->smax_value + off + size;
4824 if (value_regno >= 0)
4825 value_reg = &cur->regs[value_regno];
31ff2135
EZ
4826 if ((value_reg && register_is_null(value_reg)) ||
4827 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
01f810ac
AM
4828 writing_zero = true;
4829
c69431aa 4830 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
4831 if (err)
4832 return err;
4833
ef8fc7a0
KKD
4834 for (i = min_off; i < max_off; i++) {
4835 int spi;
4836
4837 spi = __get_spi(i);
4838 err = destroy_if_dynptr_stack_slot(env, state, spi);
4839 if (err)
4840 return err;
4841 }
01f810ac
AM
4842
4843 /* Variable offset writes destroy any spilled pointers in range. */
4844 for (i = min_off; i < max_off; i++) {
4845 u8 new_type, *stype;
4846 int slot, spi;
4847
4848 slot = -i - 1;
4849 spi = slot / BPF_REG_SIZE;
4850 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
0f55f9ed 4851 mark_stack_slot_scratched(env, spi);
01f810ac 4852
f5e477a8
KKD
4853 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4854 /* Reject the write if range we may write to has not
4855 * been initialized beforehand. If we didn't reject
4856 * here, the ptr status would be erased below (even
4857 * though not all slots are actually overwritten),
4858 * possibly opening the door to leaks.
4859 *
4860 * We do however catch STACK_INVALID case below, and
4861 * only allow reading possibly uninitialized memory
4862 * later for CAP_PERFMON, as the write may not happen to
4863 * that slot.
01f810ac
AM
4864 */
4865 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4866 insn_idx, i);
4867 return -EINVAL;
4868 }
4869
4870 /* Erase all spilled pointers. */
4871 state->stack[spi].spilled_ptr.type = NOT_INIT;
4872
4873 /* Update the slot type. */
4874 new_type = STACK_MISC;
4875 if (writing_zero && *stype == STACK_ZERO) {
4876 new_type = STACK_ZERO;
4877 zero_used = true;
4878 }
4879 /* If the slot is STACK_INVALID, we check whether it's OK to
4880 * pretend that it will be initialized by this write. The slot
4881 * might not actually be written to, and so if we mark it as
4882 * initialized future reads might leak uninitialized memory.
4883 * For privileged programs, we will accept such reads to slots
4884 * that may or may not be written because, if we're reject
4885 * them, the error would be too confusing.
4886 */
4887 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4888 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4889 insn_idx, i);
4890 return -EINVAL;
4891 }
4892 *stype = new_type;
4893 }
4894 if (zero_used) {
4895 /* backtracking doesn't work for STACK_ZERO yet. */
4896 err = mark_chain_precision(env, value_regno);
4897 if (err)
4898 return err;
4899 }
4900 return 0;
4901}
4902
4903/* When register 'dst_regno' is assigned some values from stack[min_off,
4904 * max_off), we set the register's type according to the types of the
4905 * respective stack slots. If all the stack values are known to be zeros, then
4906 * so is the destination reg. Otherwise, the register is considered to be
4907 * SCALAR. This function does not deal with register filling; the caller must
4908 * ensure that all spilled registers in the stack range have been marked as
4909 * read.
4910 */
4911static void mark_reg_stack_read(struct bpf_verifier_env *env,
4912 /* func where src register points to */
4913 struct bpf_func_state *ptr_state,
4914 int min_off, int max_off, int dst_regno)
4915{
4916 struct bpf_verifier_state *vstate = env->cur_state;
4917 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4918 int i, slot, spi;
4919 u8 *stype;
4920 int zeros = 0;
4921
4922 for (i = min_off; i < max_off; i++) {
4923 slot = -i - 1;
4924 spi = slot / BPF_REG_SIZE;
e0bf4622 4925 mark_stack_slot_scratched(env, spi);
01f810ac
AM
4926 stype = ptr_state->stack[spi].slot_type;
4927 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4928 break;
4929 zeros++;
4930 }
4931 if (zeros == max_off - min_off) {
4932 /* any access_size read into register is zero extended,
4933 * so the whole register == const_zero
4934 */
4935 __mark_reg_const_zero(&state->regs[dst_regno]);
4936 /* backtracking doesn't support STACK_ZERO yet,
4937 * so mark it precise here, so that later
4938 * backtracking can stop here.
4939 * Backtracking may not need this if this register
4940 * doesn't participate in pointer adjustment.
4941 * Forward propagation of precise flag is not
4942 * necessary either. This mark is only to stop
4943 * backtracking. Any register that contributed
4944 * to const 0 was marked precise before spill.
4945 */
4946 state->regs[dst_regno].precise = true;
4947 } else {
4948 /* have read misc data from the stack */
4949 mark_reg_unknown(env, state->regs, dst_regno);
4950 }
4951 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4952}
4953
4954/* Read the stack at 'off' and put the results into the register indicated by
4955 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4956 * spilled reg.
4957 *
4958 * 'dst_regno' can be -1, meaning that the read value is not going to a
4959 * register.
4960 *
4961 * The access is assumed to be within the current stack bounds.
4962 */
4963static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4964 /* func where src register points to */
4965 struct bpf_func_state *reg_state,
4966 int off, int size, int dst_regno)
17a52670 4967{
f4d7e40a
AS
4968 struct bpf_verifier_state *vstate = env->cur_state;
4969 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 4970 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 4971 struct bpf_reg_state *reg;
354e8f19 4972 u8 *stype, type;
17a52670 4973
f4d7e40a 4974 stype = reg_state->stack[spi].slot_type;
f7cf25b2 4975 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 4976
e0bf4622
AN
4977 mark_stack_slot_scratched(env, spi);
4978
27113c59 4979 if (is_spilled_reg(&reg_state->stack[spi])) {
f30d4968
MKL
4980 u8 spill_size = 1;
4981
4982 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4983 spill_size++;
354e8f19 4984
f30d4968 4985 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
f7cf25b2
AS
4986 if (reg->type != SCALAR_VALUE) {
4987 verbose_linfo(env, env->insn_idx, "; ");
4988 verbose(env, "invalid size of register fill\n");
4989 return -EACCES;
4990 }
354e8f19
MKL
4991
4992 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4993 if (dst_regno < 0)
4994 return 0;
4995
f30d4968 4996 if (!(off % BPF_REG_SIZE) && size == spill_size) {
354e8f19
MKL
4997 /* The earlier check_reg_arg() has decided the
4998 * subreg_def for this insn. Save it first.
4999 */
5000 s32 subreg_def = state->regs[dst_regno].subreg_def;
5001
71f656a5 5002 copy_register_state(&state->regs[dst_regno], reg);
354e8f19
MKL
5003 state->regs[dst_regno].subreg_def = subreg_def;
5004 } else {
5005 for (i = 0; i < size; i++) {
5006 type = stype[(slot - i) % BPF_REG_SIZE];
5007 if (type == STACK_SPILL)
5008 continue;
5009 if (type == STACK_MISC)
5010 continue;
6715df8d
EZ
5011 if (type == STACK_INVALID && env->allow_uninit_stack)
5012 continue;
354e8f19
MKL
5013 verbose(env, "invalid read from stack off %d+%d size %d\n",
5014 off, i, size);
5015 return -EACCES;
5016 }
01f810ac 5017 mark_reg_unknown(env, state->regs, dst_regno);
f7cf25b2 5018 }
354e8f19 5019 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2 5020 return 0;
17a52670 5021 }
17a52670 5022
01f810ac 5023 if (dst_regno >= 0) {
17a52670 5024 /* restore register state from stack */
71f656a5 5025 copy_register_state(&state->regs[dst_regno], reg);
2f18f62e
AS
5026 /* mark reg as written since spilled pointer state likely
5027 * has its liveness marks cleared by is_state_visited()
5028 * which resets stack/reg liveness for state transitions
5029 */
01f810ac 5030 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 5031 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 5032 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
5033 * it is acceptable to use this value as a SCALAR_VALUE
5034 * (e.g. for XADD).
5035 * We must not allow unprivileged callers to do that
5036 * with spilled pointers.
5037 */
5038 verbose(env, "leaking pointer from stack off %d\n",
5039 off);
5040 return -EACCES;
dc503a8a 5041 }
f7cf25b2 5042 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670
AS
5043 } else {
5044 for (i = 0; i < size; i++) {
01f810ac
AM
5045 type = stype[(slot - i) % BPF_REG_SIZE];
5046 if (type == STACK_MISC)
cc2b14d5 5047 continue;
01f810ac 5048 if (type == STACK_ZERO)
cc2b14d5 5049 continue;
6715df8d
EZ
5050 if (type == STACK_INVALID && env->allow_uninit_stack)
5051 continue;
cc2b14d5
AS
5052 verbose(env, "invalid read from stack off %d+%d size %d\n",
5053 off, i, size);
5054 return -EACCES;
5055 }
f7cf25b2 5056 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
5057 if (dst_regno >= 0)
5058 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 5059 }
f7cf25b2 5060 return 0;
17a52670
AS
5061}
5062
61df10c7 5063enum bpf_access_src {
01f810ac
AM
5064 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
5065 ACCESS_HELPER = 2, /* the access is performed by a helper */
5066};
5067
5068static int check_stack_range_initialized(struct bpf_verifier_env *env,
5069 int regno, int off, int access_size,
5070 bool zero_size_allowed,
61df10c7 5071 enum bpf_access_src type,
01f810ac
AM
5072 struct bpf_call_arg_meta *meta);
5073
5074static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5075{
5076 return cur_regs(env) + regno;
5077}
5078
5079/* Read the stack at 'ptr_regno + off' and put the result into the register
5080 * 'dst_regno'.
5081 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5082 * but not its variable offset.
5083 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5084 *
5085 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5086 * filling registers (i.e. reads of spilled register cannot be detected when
5087 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5088 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5089 * offset; for a fixed offset check_stack_read_fixed_off should be used
5090 * instead.
5091 */
5092static int check_stack_read_var_off(struct bpf_verifier_env *env,
5093 int ptr_regno, int off, int size, int dst_regno)
e4298d25 5094{
01f810ac
AM
5095 /* The state of the source register. */
5096 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5097 struct bpf_func_state *ptr_state = func(env, reg);
5098 int err;
5099 int min_off, max_off;
5100
5101 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 5102 */
01f810ac
AM
5103 err = check_stack_range_initialized(env, ptr_regno, off, size,
5104 false, ACCESS_DIRECT, NULL);
5105 if (err)
5106 return err;
5107
5108 min_off = reg->smin_value + off;
5109 max_off = reg->smax_value + off;
5110 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5111 return 0;
5112}
5113
5114/* check_stack_read dispatches to check_stack_read_fixed_off or
5115 * check_stack_read_var_off.
5116 *
5117 * The caller must ensure that the offset falls within the allocated stack
5118 * bounds.
5119 *
5120 * 'dst_regno' is a register which will receive the value from the stack. It
5121 * can be -1, meaning that the read value is not going to a register.
5122 */
5123static int check_stack_read(struct bpf_verifier_env *env,
5124 int ptr_regno, int off, int size,
5125 int dst_regno)
5126{
5127 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5128 struct bpf_func_state *state = func(env, reg);
5129 int err;
5130 /* Some accesses are only permitted with a static offset. */
5131 bool var_off = !tnum_is_const(reg->var_off);
5132
5133 /* The offset is required to be static when reads don't go to a
5134 * register, in order to not leak pointers (see
5135 * check_stack_read_fixed_off).
5136 */
5137 if (dst_regno < 0 && var_off) {
e4298d25
DB
5138 char tn_buf[48];
5139
5140 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 5141 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
5142 tn_buf, off, size);
5143 return -EACCES;
5144 }
01f810ac
AM
5145 /* Variable offset is prohibited for unprivileged mode for simplicity
5146 * since it requires corresponding support in Spectre masking for stack
082cdc69
LG
5147 * ALU. See also retrieve_ptr_limit(). The check in
5148 * check_stack_access_for_ptr_arithmetic() called by
5149 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5150 * with variable offsets, therefore no check is required here. Further,
5151 * just checking it here would be insufficient as speculative stack
5152 * writes could still lead to unsafe speculative behaviour.
01f810ac 5153 */
01f810ac
AM
5154 if (!var_off) {
5155 off += reg->var_off.value;
5156 err = check_stack_read_fixed_off(env, state, off, size,
5157 dst_regno);
5158 } else {
5159 /* Variable offset stack reads need more conservative handling
5160 * than fixed offset ones. Note that dst_regno >= 0 on this
5161 * branch.
5162 */
5163 err = check_stack_read_var_off(env, ptr_regno, off, size,
5164 dst_regno);
5165 }
5166 return err;
5167}
5168
5169
5170/* check_stack_write dispatches to check_stack_write_fixed_off or
5171 * check_stack_write_var_off.
5172 *
5173 * 'ptr_regno' is the register used as a pointer into the stack.
5174 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5175 * 'value_regno' is the register whose value we're writing to the stack. It can
5176 * be -1, meaning that we're not writing from a register.
5177 *
5178 * The caller must ensure that the offset falls within the maximum stack size.
5179 */
5180static int check_stack_write(struct bpf_verifier_env *env,
5181 int ptr_regno, int off, int size,
5182 int value_regno, int insn_idx)
5183{
5184 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5185 struct bpf_func_state *state = func(env, reg);
5186 int err;
5187
5188 if (tnum_is_const(reg->var_off)) {
5189 off += reg->var_off.value;
5190 err = check_stack_write_fixed_off(env, state, off, size,
5191 value_regno, insn_idx);
5192 } else {
5193 /* Variable offset stack reads need more conservative handling
5194 * than fixed offset ones.
5195 */
5196 err = check_stack_write_var_off(env, state,
5197 ptr_regno, off, size,
5198 value_regno, insn_idx);
5199 }
5200 return err;
e4298d25
DB
5201}
5202
591fe988
DB
5203static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5204 int off, int size, enum bpf_access_type type)
5205{
5206 struct bpf_reg_state *regs = cur_regs(env);
5207 struct bpf_map *map = regs[regno].map_ptr;
5208 u32 cap = bpf_map_flags_to_cap(map);
5209
5210 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5211 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5212 map->value_size, off, size);
5213 return -EACCES;
5214 }
5215
5216 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5217 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5218 map->value_size, off, size);
5219 return -EACCES;
5220 }
5221
5222 return 0;
5223}
5224
457f4436
AN
5225/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5226static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5227 int off, int size, u32 mem_size,
5228 bool zero_size_allowed)
17a52670 5229{
457f4436
AN
5230 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5231 struct bpf_reg_state *reg;
5232
5233 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5234 return 0;
17a52670 5235
457f4436
AN
5236 reg = &cur_regs(env)[regno];
5237 switch (reg->type) {
69c087ba
YS
5238 case PTR_TO_MAP_KEY:
5239 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5240 mem_size, off, size);
5241 break;
457f4436 5242 case PTR_TO_MAP_VALUE:
61bd5218 5243 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
5244 mem_size, off, size);
5245 break;
5246 case PTR_TO_PACKET:
5247 case PTR_TO_PACKET_META:
5248 case PTR_TO_PACKET_END:
5249 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5250 off, size, regno, reg->id, off, mem_size);
5251 break;
5252 case PTR_TO_MEM:
5253 default:
5254 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5255 mem_size, off, size);
17a52670 5256 }
457f4436
AN
5257
5258 return -EACCES;
17a52670
AS
5259}
5260
457f4436
AN
5261/* check read/write into a memory region with possible variable offset */
5262static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5263 int off, int size, u32 mem_size,
5264 bool zero_size_allowed)
dbcfe5f7 5265{
f4d7e40a
AS
5266 struct bpf_verifier_state *vstate = env->cur_state;
5267 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
5268 struct bpf_reg_state *reg = &state->regs[regno];
5269 int err;
5270
457f4436 5271 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
5272 * need to try adding each of min_value and max_value to off
5273 * to make sure our theoretical access will be safe.
2e576648
CL
5274 *
5275 * The minimum value is only important with signed
dbcfe5f7
GB
5276 * comparisons where we can't assume the floor of a
5277 * value is 0. If we are using signed variables for our
5278 * index'es we need to make sure that whatever we use
5279 * will have a set floor within our range.
5280 */
b7137c4e
DB
5281 if (reg->smin_value < 0 &&
5282 (reg->smin_value == S64_MIN ||
5283 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5284 reg->smin_value + off < 0)) {
61bd5218 5285 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
5286 regno);
5287 return -EACCES;
5288 }
457f4436
AN
5289 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5290 mem_size, zero_size_allowed);
dbcfe5f7 5291 if (err) {
457f4436 5292 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 5293 regno);
dbcfe5f7
GB
5294 return err;
5295 }
5296
b03c9f9f
EC
5297 /* If we haven't set a max value then we need to bail since we can't be
5298 * sure we won't do bad things.
5299 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 5300 */
b03c9f9f 5301 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 5302 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
5303 regno);
5304 return -EACCES;
5305 }
457f4436
AN
5306 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5307 mem_size, zero_size_allowed);
5308 if (err) {
5309 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 5310 regno);
457f4436
AN
5311 return err;
5312 }
5313
5314 return 0;
5315}
d83525ca 5316
e9147b44
KKD
5317static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5318 const struct bpf_reg_state *reg, int regno,
5319 bool fixed_off_ok)
5320{
5321 /* Access to this pointer-typed register or passing it to a helper
5322 * is only allowed in its original, unmodified form.
5323 */
5324
5325 if (reg->off < 0) {
5326 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5327 reg_type_str(env, reg->type), regno, reg->off);
5328 return -EACCES;
5329 }
5330
5331 if (!fixed_off_ok && reg->off) {
5332 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5333 reg_type_str(env, reg->type), regno, reg->off);
5334 return -EACCES;
5335 }
5336
5337 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5338 char tn_buf[48];
5339
5340 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5341 verbose(env, "variable %s access var_off=%s disallowed\n",
5342 reg_type_str(env, reg->type), tn_buf);
5343 return -EACCES;
5344 }
5345
5346 return 0;
5347}
5348
5349int check_ptr_off_reg(struct bpf_verifier_env *env,
5350 const struct bpf_reg_state *reg, int regno)
5351{
5352 return __check_ptr_off_reg(env, reg, regno, false);
5353}
5354
61df10c7 5355static int map_kptr_match_type(struct bpf_verifier_env *env,
aa3496ac 5356 struct btf_field *kptr_field,
61df10c7
KKD
5357 struct bpf_reg_state *reg, u32 regno)
5358{
b32a5dae 5359 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
ab6c637a 5360 int perm_flags;
61df10c7
KKD
5361 const char *reg_name = "";
5362
ab6c637a
YS
5363 if (btf_is_kernel(reg->btf)) {
5364 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5365
5366 /* Only unreferenced case accepts untrusted pointers */
5367 if (kptr_field->type == BPF_KPTR_UNREF)
5368 perm_flags |= PTR_UNTRUSTED;
5369 } else {
5370 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
36d8bdf7
YS
5371 if (kptr_field->type == BPF_KPTR_PERCPU)
5372 perm_flags |= MEM_PERCPU;
ab6c637a 5373 }
6efe152d
KKD
5374
5375 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
61df10c7
KKD
5376 goto bad_type;
5377
61df10c7 5378 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
b32a5dae 5379 reg_name = btf_type_name(reg->btf, reg->btf_id);
61df10c7 5380
c0a5a21c
KKD
5381 /* For ref_ptr case, release function check should ensure we get one
5382 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5383 * normal store of unreferenced kptr, we must ensure var_off is zero.
5384 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5385 * reg->off and reg->ref_obj_id are not needed here.
5386 */
61df10c7
KKD
5387 if (__check_ptr_off_reg(env, reg, regno, true))
5388 return -EACCES;
5389
ab6c637a 5390 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
61df10c7
KKD
5391 * we also need to take into account the reg->off.
5392 *
5393 * We want to support cases like:
5394 *
5395 * struct foo {
5396 * struct bar br;
5397 * struct baz bz;
5398 * };
5399 *
5400 * struct foo *v;
5401 * v = func(); // PTR_TO_BTF_ID
5402 * val->foo = v; // reg->off is zero, btf and btf_id match type
5403 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5404 * // first member type of struct after comparison fails
5405 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5406 * // to match type
5407 *
5408 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
2ab3b380
KKD
5409 * is zero. We must also ensure that btf_struct_ids_match does not walk
5410 * the struct to match type against first member of struct, i.e. reject
5411 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5412 * strict mode to true for type match.
61df10c7
KKD
5413 */
5414 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
aa3496ac 5415 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
36d8bdf7 5416 kptr_field->type != BPF_KPTR_UNREF))
61df10c7
KKD
5417 goto bad_type;
5418 return 0;
5419bad_type:
5420 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5421 reg_type_str(env, reg->type), reg_name);
6efe152d 5422 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
aa3496ac 5423 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
5424 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5425 targ_name);
5426 else
5427 verbose(env, "\n");
61df10c7
KKD
5428 return -EINVAL;
5429}
5430
20c09d92
AS
5431/* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5432 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5433 */
5434static bool in_rcu_cs(struct bpf_verifier_env *env)
5435{
5861d1e8
DM
5436 return env->cur_state->active_rcu_lock ||
5437 env->cur_state->active_lock.ptr ||
5438 !env->prog->aux->sleepable;
20c09d92
AS
5439}
5440
5441/* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5442BTF_SET_START(rcu_protected_types)
5443BTF_ID(struct, prog_test_ref_kfunc)
05670f81 5444#ifdef CONFIG_CGROUPS
20c09d92 5445BTF_ID(struct, cgroup)
05670f81 5446#endif
63d2d83d 5447BTF_ID(struct, bpf_cpumask)
d02c48fa 5448BTF_ID(struct, task_struct)
20c09d92
AS
5449BTF_SET_END(rcu_protected_types)
5450
5451static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5452{
5453 if (!btf_is_kernel(btf))
5454 return false;
5455 return btf_id_set_contains(&rcu_protected_types, btf_id);
5456}
5457
5458static bool rcu_safe_kptr(const struct btf_field *field)
5459{
5460 const struct btf_field_kptr *kptr = &field->kptr;
5461
36d8bdf7
YS
5462 return field->type == BPF_KPTR_PERCPU ||
5463 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5464}
5465
5466static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5467{
5468 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5469 if (kptr_field->type != BPF_KPTR_PERCPU)
5470 return PTR_MAYBE_NULL | MEM_RCU;
5471 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU;
5472 }
5473 return PTR_MAYBE_NULL | PTR_UNTRUSTED;
20c09d92
AS
5474}
5475
61df10c7
KKD
5476static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5477 int value_regno, int insn_idx,
aa3496ac 5478 struct btf_field *kptr_field)
61df10c7
KKD
5479{
5480 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5481 int class = BPF_CLASS(insn->code);
5482 struct bpf_reg_state *val_reg;
5483
5484 /* Things we already checked for in check_map_access and caller:
5485 * - Reject cases where variable offset may touch kptr
5486 * - size of access (must be BPF_DW)
5487 * - tnum_is_const(reg->var_off)
aa3496ac 5488 * - kptr_field->offset == off + reg->var_off.value
61df10c7
KKD
5489 */
5490 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5491 if (BPF_MODE(insn->code) != BPF_MEM) {
5492 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5493 return -EACCES;
5494 }
5495
6efe152d
KKD
5496 /* We only allow loading referenced kptr, since it will be marked as
5497 * untrusted, similar to unreferenced kptr.
5498 */
36d8bdf7
YS
5499 if (class != BPF_LDX &&
5500 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6efe152d 5501 verbose(env, "store to referenced kptr disallowed\n");
c0a5a21c
KKD
5502 return -EACCES;
5503 }
5504
61df10c7
KKD
5505 if (class == BPF_LDX) {
5506 val_reg = reg_state(env, value_regno);
5507 /* We can simply mark the value_regno receiving the pointer
5508 * value from map as PTR_TO_BTF_ID, with the correct type.
5509 */
aa3496ac 5510 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
36d8bdf7 5511 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
61df10c7
KKD
5512 /* For mark_ptr_or_null_reg */
5513 val_reg->id = ++env->id_gen;
5514 } else if (class == BPF_STX) {
5515 val_reg = reg_state(env, value_regno);
5516 if (!register_is_null(val_reg) &&
aa3496ac 5517 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
61df10c7
KKD
5518 return -EACCES;
5519 } else if (class == BPF_ST) {
5520 if (insn->imm) {
5521 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
aa3496ac 5522 kptr_field->offset);
61df10c7
KKD
5523 return -EACCES;
5524 }
5525 } else {
5526 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5527 return -EACCES;
5528 }
5529 return 0;
5530}
5531
457f4436
AN
5532/* check read/write into a map element with possible variable offset */
5533static int check_map_access(struct bpf_verifier_env *env, u32 regno,
61df10c7
KKD
5534 int off, int size, bool zero_size_allowed,
5535 enum bpf_access_src src)
457f4436
AN
5536{
5537 struct bpf_verifier_state *vstate = env->cur_state;
5538 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5539 struct bpf_reg_state *reg = &state->regs[regno];
5540 struct bpf_map *map = reg->map_ptr;
aa3496ac
KKD
5541 struct btf_record *rec;
5542 int err, i;
457f4436
AN
5543
5544 err = check_mem_region_access(env, regno, off, size, map->value_size,
5545 zero_size_allowed);
5546 if (err)
5547 return err;
5548
aa3496ac
KKD
5549 if (IS_ERR_OR_NULL(map->record))
5550 return 0;
5551 rec = map->record;
5552 for (i = 0; i < rec->cnt; i++) {
5553 struct btf_field *field = &rec->fields[i];
5554 u32 p = field->offset;
d83525ca 5555
db559117
KKD
5556 /* If any part of a field can be touched by load/store, reject
5557 * this program. To check that [x1, x2) overlaps with [y1, y2),
d83525ca
AS
5558 * it is sufficient to check x1 < y2 && y1 < x2.
5559 */
aa3496ac
KKD
5560 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5561 p < reg->umax_value + off + size) {
5562 switch (field->type) {
5563 case BPF_KPTR_UNREF:
5564 case BPF_KPTR_REF:
36d8bdf7 5565 case BPF_KPTR_PERCPU:
61df10c7
KKD
5566 if (src != ACCESS_DIRECT) {
5567 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5568 return -EACCES;
5569 }
5570 if (!tnum_is_const(reg->var_off)) {
5571 verbose(env, "kptr access cannot have variable offset\n");
5572 return -EACCES;
5573 }
5574 if (p != off + reg->var_off.value) {
5575 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5576 p, off + reg->var_off.value);
5577 return -EACCES;
5578 }
5579 if (size != bpf_size_to_bytes(BPF_DW)) {
5580 verbose(env, "kptr access size must be BPF_DW\n");
5581 return -EACCES;
5582 }
5583 break;
aa3496ac 5584 default:
db559117
KKD
5585 verbose(env, "%s cannot be accessed directly by load/store\n",
5586 btf_field_type_name(field->type));
aa3496ac 5587 return -EACCES;
61df10c7
KKD
5588 }
5589 }
5590 }
aa3496ac 5591 return 0;
dbcfe5f7
GB
5592}
5593
969bf05e
AS
5594#define MAX_PACKET_OFF 0xffff
5595
58e2af8b 5596static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
5597 const struct bpf_call_arg_meta *meta,
5598 enum bpf_access_type t)
4acf6c0b 5599{
7e40781c
UP
5600 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5601
5602 switch (prog_type) {
5d66fa7d 5603 /* Program types only with direct read access go here! */
3a0af8fd
TG
5604 case BPF_PROG_TYPE_LWT_IN:
5605 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 5606 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 5607 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 5608 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 5609 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
5610 if (t == BPF_WRITE)
5611 return false;
8731745e 5612 fallthrough;
5d66fa7d
DB
5613
5614 /* Program types with direct read + write access go here! */
36bbef52
DB
5615 case BPF_PROG_TYPE_SCHED_CLS:
5616 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 5617 case BPF_PROG_TYPE_XDP:
3a0af8fd 5618 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 5619 case BPF_PROG_TYPE_SK_SKB:
4f738adb 5620 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
5621 if (meta)
5622 return meta->pkt_access;
5623
5624 env->seen_direct_write = true;
4acf6c0b 5625 return true;
0d01da6a
SF
5626
5627 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5628 if (t == BPF_WRITE)
5629 env->seen_direct_write = true;
5630
5631 return true;
5632
4acf6c0b
BB
5633 default:
5634 return false;
5635 }
5636}
5637
f1174f77 5638static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 5639 int size, bool zero_size_allowed)
f1174f77 5640{
638f5b90 5641 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
5642 struct bpf_reg_state *reg = &regs[regno];
5643 int err;
5644
5645 /* We may have added a variable offset to the packet pointer; but any
5646 * reg->range we have comes after that. We are only checking the fixed
5647 * offset.
5648 */
5649
5650 /* We don't allow negative numbers, because we aren't tracking enough
5651 * detail to prove they're safe.
5652 */
b03c9f9f 5653 if (reg->smin_value < 0) {
61bd5218 5654 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
5655 regno);
5656 return -EACCES;
5657 }
6d94e741
AS
5658
5659 err = reg->range < 0 ? -EINVAL :
5660 __check_mem_access(env, regno, off, size, reg->range,
457f4436 5661 zero_size_allowed);
f1174f77 5662 if (err) {
61bd5218 5663 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
5664 return err;
5665 }
e647815a 5666
457f4436 5667 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
5668 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5669 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 5670 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
5671 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5672 */
5673 env->prog->aux->max_pkt_offset =
5674 max_t(u32, env->prog->aux->max_pkt_offset,
5675 off + reg->umax_value + size - 1);
5676
f1174f77
EC
5677 return err;
5678}
5679
5680/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 5681static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 5682 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 5683 struct btf **btf, u32 *btf_id)
17a52670 5684{
f96da094
DB
5685 struct bpf_insn_access_aux info = {
5686 .reg_type = *reg_type,
9e15db66 5687 .log = &env->log,
f96da094 5688 };
31fd8581 5689
4f9218aa 5690 if (env->ops->is_valid_access &&
5e43f899 5691 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
5692 /* A non zero info.ctx_field_size indicates that this field is a
5693 * candidate for later verifier transformation to load the whole
5694 * field and then apply a mask when accessed with a narrower
5695 * access than actual ctx access size. A zero info.ctx_field_size
5696 * will only allow for whole field access and rejects any other
5697 * type of narrower access.
31fd8581 5698 */
23994631 5699 *reg_type = info.reg_type;
31fd8581 5700
c25b2ae1 5701 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 5702 *btf = info.btf;
9e15db66 5703 *btf_id = info.btf_id;
22dc4a0f 5704 } else {
9e15db66 5705 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 5706 }
32bbe007
AS
5707 /* remember the offset of last byte accessed in ctx */
5708 if (env->prog->aux->max_ctx_offset < off + size)
5709 env->prog->aux->max_ctx_offset = off + size;
17a52670 5710 return 0;
32bbe007 5711 }
17a52670 5712
61bd5218 5713 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
5714 return -EACCES;
5715}
5716
d58e468b
PP
5717static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5718 int size)
5719{
5720 if (size < 0 || off < 0 ||
5721 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5722 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5723 off, size);
5724 return -EACCES;
5725 }
5726 return 0;
5727}
5728
5f456649
MKL
5729static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5730 u32 regno, int off, int size,
5731 enum bpf_access_type t)
c64b7983
JS
5732{
5733 struct bpf_reg_state *regs = cur_regs(env);
5734 struct bpf_reg_state *reg = &regs[regno];
5f456649 5735 struct bpf_insn_access_aux info = {};
46f8bc92 5736 bool valid;
c64b7983
JS
5737
5738 if (reg->smin_value < 0) {
5739 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5740 regno);
5741 return -EACCES;
5742 }
5743
46f8bc92
MKL
5744 switch (reg->type) {
5745 case PTR_TO_SOCK_COMMON:
5746 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5747 break;
5748 case PTR_TO_SOCKET:
5749 valid = bpf_sock_is_valid_access(off, size, t, &info);
5750 break;
655a51e5
MKL
5751 case PTR_TO_TCP_SOCK:
5752 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5753 break;
fada7fdc
JL
5754 case PTR_TO_XDP_SOCK:
5755 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5756 break;
46f8bc92
MKL
5757 default:
5758 valid = false;
c64b7983
JS
5759 }
5760
5f456649 5761
46f8bc92
MKL
5762 if (valid) {
5763 env->insn_aux_data[insn_idx].ctx_field_size =
5764 info.ctx_field_size;
5765 return 0;
5766 }
5767
5768 verbose(env, "R%d invalid %s access off=%d size=%d\n",
c25b2ae1 5769 regno, reg_type_str(env, reg->type), off, size);
46f8bc92
MKL
5770
5771 return -EACCES;
c64b7983
JS
5772}
5773
4cabc5b1
DB
5774static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5775{
2a159c6f 5776 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
5777}
5778
f37a8cb8
DB
5779static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5780{
2a159c6f 5781 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 5782
46f8bc92
MKL
5783 return reg->type == PTR_TO_CTX;
5784}
5785
5786static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5787{
5788 const struct bpf_reg_state *reg = reg_state(env, regno);
5789
5790 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
5791}
5792
ca369602
DB
5793static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5794{
2a159c6f 5795 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
5796
5797 return type_is_pkt_pointer(reg->type);
5798}
5799
4b5defde
DB
5800static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5801{
5802 const struct bpf_reg_state *reg = reg_state(env, regno);
5803
5804 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5805 return reg->type == PTR_TO_FLOW_KEYS;
5806}
5807
831deb29
AP
5808static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5809#ifdef CONFIG_NET
5810 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5811 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5812 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5813#endif
5ba190c2 5814 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
831deb29
AP
5815};
5816
9bb00b28
YS
5817static bool is_trusted_reg(const struct bpf_reg_state *reg)
5818{
5819 /* A referenced register is always trusted. */
5820 if (reg->ref_obj_id)
5821 return true;
5822
831deb29
AP
5823 /* Types listed in the reg2btf_ids are always trusted */
5824 if (reg2btf_ids[base_type(reg->type)])
5825 return true;
5826
9bb00b28 5827 /* If a register is not referenced, it is trusted if it has the
fca1aa75 5828 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
9bb00b28
YS
5829 * other type modifiers may be safe, but we elect to take an opt-in
5830 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5831 * not.
5832 *
5833 * Eventually, we should make PTR_TRUSTED the single source of truth
5834 * for whether a register is trusted.
5835 */
5836 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5837 !bpf_type_has_unsafe_modifiers(reg->type);
5838}
5839
fca1aa75
YS
5840static bool is_rcu_reg(const struct bpf_reg_state *reg)
5841{
5842 return reg->type & MEM_RCU;
5843}
5844
afeebf9f
AS
5845static void clear_trusted_flags(enum bpf_type_flag *flag)
5846{
5847 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5848}
5849
61bd5218
JK
5850static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5851 const struct bpf_reg_state *reg,
d1174416 5852 int off, int size, bool strict)
969bf05e 5853{
f1174f77 5854 struct tnum reg_off;
e07b98d9 5855 int ip_align;
d1174416
DM
5856
5857 /* Byte size accesses are always allowed. */
5858 if (!strict || size == 1)
5859 return 0;
5860
e4eda884
DM
5861 /* For platforms that do not have a Kconfig enabling
5862 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5863 * NET_IP_ALIGN is universally set to '2'. And on platforms
5864 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5865 * to this code only in strict mode where we want to emulate
5866 * the NET_IP_ALIGN==2 checking. Therefore use an
5867 * unconditional IP align value of '2'.
e07b98d9 5868 */
e4eda884 5869 ip_align = 2;
f1174f77
EC
5870
5871 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5872 if (!tnum_is_aligned(reg_off, size)) {
5873 char tn_buf[48];
5874
5875 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
5876 verbose(env,
5877 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 5878 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
5879 return -EACCES;
5880 }
79adffcd 5881
969bf05e
AS
5882 return 0;
5883}
5884
61bd5218
JK
5885static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5886 const struct bpf_reg_state *reg,
f1174f77
EC
5887 const char *pointer_desc,
5888 int off, int size, bool strict)
79adffcd 5889{
f1174f77
EC
5890 struct tnum reg_off;
5891
5892 /* Byte size accesses are always allowed. */
5893 if (!strict || size == 1)
5894 return 0;
5895
5896 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5897 if (!tnum_is_aligned(reg_off, size)) {
5898 char tn_buf[48];
5899
5900 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 5901 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 5902 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
5903 return -EACCES;
5904 }
5905
969bf05e
AS
5906 return 0;
5907}
5908
e07b98d9 5909static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
5910 const struct bpf_reg_state *reg, int off,
5911 int size, bool strict_alignment_once)
79adffcd 5912{
ca369602 5913 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 5914 const char *pointer_desc = "";
d1174416 5915
79adffcd
DB
5916 switch (reg->type) {
5917 case PTR_TO_PACKET:
de8f3a83
DB
5918 case PTR_TO_PACKET_META:
5919 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5920 * right in front, treat it the very same way.
5921 */
61bd5218 5922 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
5923 case PTR_TO_FLOW_KEYS:
5924 pointer_desc = "flow keys ";
5925 break;
69c087ba
YS
5926 case PTR_TO_MAP_KEY:
5927 pointer_desc = "key ";
5928 break;
f1174f77
EC
5929 case PTR_TO_MAP_VALUE:
5930 pointer_desc = "value ";
5931 break;
5932 case PTR_TO_CTX:
5933 pointer_desc = "context ";
5934 break;
5935 case PTR_TO_STACK:
5936 pointer_desc = "stack ";
01f810ac
AM
5937 /* The stack spill tracking logic in check_stack_write_fixed_off()
5938 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
5939 * aligned.
5940 */
5941 strict = true;
f1174f77 5942 break;
c64b7983
JS
5943 case PTR_TO_SOCKET:
5944 pointer_desc = "sock ";
5945 break;
46f8bc92
MKL
5946 case PTR_TO_SOCK_COMMON:
5947 pointer_desc = "sock_common ";
5948 break;
655a51e5
MKL
5949 case PTR_TO_TCP_SOCK:
5950 pointer_desc = "tcp_sock ";
5951 break;
fada7fdc
JL
5952 case PTR_TO_XDP_SOCK:
5953 pointer_desc = "xdp_sock ";
5954 break;
79adffcd 5955 default:
f1174f77 5956 break;
79adffcd 5957 }
61bd5218
JK
5958 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5959 strict);
79adffcd
DB
5960}
5961
f4d7e40a
AS
5962static int update_stack_depth(struct bpf_verifier_env *env,
5963 const struct bpf_func_state *func,
5964 int off)
5965{
9c8105bd 5966 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
5967
5968 if (stack >= -off)
5969 return 0;
5970
5971 /* update known max for given subprogram */
9c8105bd 5972 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
5973 return 0;
5974}
f4d7e40a 5975
70a87ffe
AS
5976/* starting from main bpf function walk all instructions of the function
5977 * and recursively walk all callees that given function can call.
5978 * Ignore jump and exit insns.
5979 * Since recursion is prevented by check_cfg() this algorithm
5980 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5981 */
b5e9ad52 5982static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
70a87ffe 5983{
9c8105bd 5984 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 5985 struct bpf_insn *insn = env->prog->insnsi;
b5e9ad52 5986 int depth = 0, frame = 0, i, subprog_end;
ebf7d1f5 5987 bool tail_call_reachable = false;
70a87ffe
AS
5988 int ret_insn[MAX_CALL_FRAMES];
5989 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 5990 int j;
f4d7e40a 5991
b5e9ad52 5992 i = subprog[idx].start;
70a87ffe 5993process_func:
7f6e4312
MF
5994 /* protect against potential stack overflow that might happen when
5995 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5996 * depth for such case down to 256 so that the worst case scenario
5997 * would result in 8k stack size (32 which is tailcall limit * 256 =
5998 * 8k).
5999 *
6000 * To get the idea what might happen, see an example:
6001 * func1 -> sub rsp, 128
6002 * subfunc1 -> sub rsp, 256
6003 * tailcall1 -> add rsp, 256
6004 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6005 * subfunc2 -> sub rsp, 64
6006 * subfunc22 -> sub rsp, 128
6007 * tailcall2 -> add rsp, 128
6008 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6009 *
6010 * tailcall will unwind the current stack frame but it will not get rid
6011 * of caller's stack as shown on the example above.
6012 */
6013 if (idx && subprog[idx].has_tail_call && depth >= 256) {
6014 verbose(env,
6015 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6016 depth);
6017 return -EACCES;
6018 }
70a87ffe
AS
6019 /* round up to 32-bytes, since this is granularity
6020 * of interpreter stack size
6021 */
9c8105bd 6022 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 6023 if (depth > MAX_BPF_STACK) {
f4d7e40a 6024 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 6025 frame + 1, depth);
f4d7e40a
AS
6026 return -EACCES;
6027 }
70a87ffe 6028continue_func:
4cb3d99c 6029 subprog_end = subprog[idx + 1].start;
70a87ffe 6030 for (; i < subprog_end; i++) {
ba7b3e7d 6031 int next_insn, sidx;
7ddc80a4 6032
f18b03fa
KKD
6033 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6034 bool err = false;
6035
6036 if (!is_bpf_throw_kfunc(insn + i))
6037 continue;
6038 if (subprog[idx].is_cb)
6039 err = true;
6040 for (int c = 0; c < frame && !err; c++) {
6041 if (subprog[ret_prog[c]].is_cb) {
6042 err = true;
6043 break;
6044 }
6045 }
6046 if (!err)
6047 continue;
6048 verbose(env,
6049 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6050 i, idx);
6051 return -EINVAL;
6052 }
6053
69c087ba 6054 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
6055 continue;
6056 /* remember insn and function to return to */
6057 ret_insn[frame] = i + 1;
9c8105bd 6058 ret_prog[frame] = idx;
70a87ffe
AS
6059
6060 /* find the callee */
7ddc80a4 6061 next_insn = i + insn[i].imm + 1;
ba7b3e7d
KKD
6062 sidx = find_subprog(env, next_insn);
6063 if (sidx < 0) {
70a87ffe 6064 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7ddc80a4 6065 next_insn);
70a87ffe
AS
6066 return -EFAULT;
6067 }
ba7b3e7d
KKD
6068 if (subprog[sidx].is_async_cb) {
6069 if (subprog[sidx].has_tail_call) {
7ddc80a4
AS
6070 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6071 return -EFAULT;
6072 }
5415ccd5
KKD
6073 /* async callbacks don't increase bpf prog stack size unless called directly */
6074 if (!bpf_pseudo_call(insn + i))
6075 continue;
b9ae0c9d
KKD
6076 if (subprog[sidx].is_exception_cb) {
6077 verbose(env, "insn %d cannot call exception cb directly\n", i);
6078 return -EINVAL;
6079 }
7ddc80a4
AS
6080 }
6081 i = next_insn;
ba7b3e7d 6082 idx = sidx;
ebf7d1f5
MF
6083
6084 if (subprog[idx].has_tail_call)
6085 tail_call_reachable = true;
6086
70a87ffe
AS
6087 frame++;
6088 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
6089 verbose(env, "the call stack of %d frames is too deep !\n",
6090 frame);
6091 return -E2BIG;
70a87ffe
AS
6092 }
6093 goto process_func;
6094 }
ebf7d1f5
MF
6095 /* if tail call got detected across bpf2bpf calls then mark each of the
6096 * currently present subprog frames as tail call reachable subprogs;
6097 * this info will be utilized by JIT so that we will be preserving the
6098 * tail call counter throughout bpf2bpf calls combined with tailcalls
6099 */
6100 if (tail_call_reachable)
b9ae0c9d
KKD
6101 for (j = 0; j < frame; j++) {
6102 if (subprog[ret_prog[j]].is_exception_cb) {
6103 verbose(env, "cannot tail call within exception cb\n");
6104 return -EINVAL;
6105 }
ebf7d1f5 6106 subprog[ret_prog[j]].tail_call_reachable = true;
b9ae0c9d 6107 }
5dd0a6b8
DB
6108 if (subprog[0].tail_call_reachable)
6109 env->prog->aux->tail_call_reachable = true;
ebf7d1f5 6110
70a87ffe
AS
6111 /* end of for() loop means the last insn of the 'subprog'
6112 * was reached. Doesn't matter whether it was JA or EXIT
6113 */
6114 if (frame == 0)
6115 return 0;
9c8105bd 6116 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
6117 frame--;
6118 i = ret_insn[frame];
9c8105bd 6119 idx = ret_prog[frame];
70a87ffe 6120 goto continue_func;
f4d7e40a
AS
6121}
6122
b5e9ad52
KKD
6123static int check_max_stack_depth(struct bpf_verifier_env *env)
6124{
6125 struct bpf_subprog_info *si = env->subprog_info;
6126 int ret;
6127
6128 for (int i = 0; i < env->subprog_cnt; i++) {
6129 if (!i || si[i].is_async_cb) {
6130 ret = check_max_stack_depth_subprog(env, i);
6131 if (ret < 0)
6132 return ret;
6133 }
6134 continue;
6135 }
6136 return 0;
6137}
6138
19d28fbd 6139#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
6140static int get_callee_stack_depth(struct bpf_verifier_env *env,
6141 const struct bpf_insn *insn, int idx)
6142{
6143 int start = idx + insn->imm + 1, subprog;
6144
6145 subprog = find_subprog(env, start);
6146 if (subprog < 0) {
6147 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6148 start);
6149 return -EFAULT;
6150 }
9c8105bd 6151 return env->subprog_info[subprog].stack_depth;
1ea47e01 6152}
19d28fbd 6153#endif
1ea47e01 6154
afbf21dc
YS
6155static int __check_buffer_access(struct bpf_verifier_env *env,
6156 const char *buf_info,
6157 const struct bpf_reg_state *reg,
6158 int regno, int off, int size)
9df1c28b
MM
6159{
6160 if (off < 0) {
6161 verbose(env,
4fc00b79 6162 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 6163 regno, buf_info, off, size);
9df1c28b
MM
6164 return -EACCES;
6165 }
6166 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6167 char tn_buf[48];
6168
6169 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6170 verbose(env,
4fc00b79 6171 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
6172 regno, off, tn_buf);
6173 return -EACCES;
6174 }
afbf21dc
YS
6175
6176 return 0;
6177}
6178
6179static int check_tp_buffer_access(struct bpf_verifier_env *env,
6180 const struct bpf_reg_state *reg,
6181 int regno, int off, int size)
6182{
6183 int err;
6184
6185 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6186 if (err)
6187 return err;
6188
9df1c28b
MM
6189 if (off + size > env->prog->aux->max_tp_access)
6190 env->prog->aux->max_tp_access = off + size;
6191
6192 return 0;
6193}
6194
afbf21dc
YS
6195static int check_buffer_access(struct bpf_verifier_env *env,
6196 const struct bpf_reg_state *reg,
6197 int regno, int off, int size,
6198 bool zero_size_allowed,
afbf21dc
YS
6199 u32 *max_access)
6200{
44e9a741 6201 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
afbf21dc
YS
6202 int err;
6203
6204 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6205 if (err)
6206 return err;
6207
6208 if (off + size > *max_access)
6209 *max_access = off + size;
6210
6211 return 0;
6212}
6213
3f50f132
JF
6214/* BPF architecture zero extends alu32 ops into 64-bit registesr */
6215static void zext_32_to_64(struct bpf_reg_state *reg)
6216{
6217 reg->var_off = tnum_subreg(reg->var_off);
6218 __reg_assign_32_into_64(reg);
6219}
9df1c28b 6220
0c17d1d2
JH
6221/* truncate register to smaller size (in bytes)
6222 * must be called with size < BPF_REG_SIZE
6223 */
6224static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6225{
6226 u64 mask;
6227
6228 /* clear high bits in bit representation */
6229 reg->var_off = tnum_cast(reg->var_off, size);
6230
6231 /* fix arithmetic bounds */
6232 mask = ((u64)1 << (size * 8)) - 1;
6233 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6234 reg->umin_value &= mask;
6235 reg->umax_value &= mask;
6236 } else {
6237 reg->umin_value = 0;
6238 reg->umax_value = mask;
6239 }
6240 reg->smin_value = reg->umin_value;
6241 reg->smax_value = reg->umax_value;
3f50f132
JF
6242
6243 /* If size is smaller than 32bit register the 32bit register
6244 * values are also truncated so we push 64-bit bounds into
6245 * 32-bit bounds. Above were truncated < 32-bits already.
6246 */
6247 if (size >= 4)
6248 return;
6249 __reg_combine_64_into_32(reg);
0c17d1d2
JH
6250}
6251
1f9a1ea8
YS
6252static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6253{
6254 if (size == 1) {
6255 reg->smin_value = reg->s32_min_value = S8_MIN;
6256 reg->smax_value = reg->s32_max_value = S8_MAX;
6257 } else if (size == 2) {
6258 reg->smin_value = reg->s32_min_value = S16_MIN;
6259 reg->smax_value = reg->s32_max_value = S16_MAX;
6260 } else {
6261 /* size == 4 */
6262 reg->smin_value = reg->s32_min_value = S32_MIN;
6263 reg->smax_value = reg->s32_max_value = S32_MAX;
6264 }
6265 reg->umin_value = reg->u32_min_value = 0;
6266 reg->umax_value = U64_MAX;
6267 reg->u32_max_value = U32_MAX;
6268 reg->var_off = tnum_unknown;
6269}
6270
6271static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6272{
6273 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6274 u64 top_smax_value, top_smin_value;
6275 u64 num_bits = size * 8;
6276
6277 if (tnum_is_const(reg->var_off)) {
6278 u64_cval = reg->var_off.value;
6279 if (size == 1)
6280 reg->var_off = tnum_const((s8)u64_cval);
6281 else if (size == 2)
6282 reg->var_off = tnum_const((s16)u64_cval);
6283 else
6284 /* size == 4 */
6285 reg->var_off = tnum_const((s32)u64_cval);
6286
6287 u64_cval = reg->var_off.value;
6288 reg->smax_value = reg->smin_value = u64_cval;
6289 reg->umax_value = reg->umin_value = u64_cval;
6290 reg->s32_max_value = reg->s32_min_value = u64_cval;
6291 reg->u32_max_value = reg->u32_min_value = u64_cval;
6292 return;
6293 }
6294
6295 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6296 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6297
6298 if (top_smax_value != top_smin_value)
6299 goto out;
6300
6301 /* find the s64_min and s64_min after sign extension */
6302 if (size == 1) {
6303 init_s64_max = (s8)reg->smax_value;
6304 init_s64_min = (s8)reg->smin_value;
6305 } else if (size == 2) {
6306 init_s64_max = (s16)reg->smax_value;
6307 init_s64_min = (s16)reg->smin_value;
6308 } else {
6309 init_s64_max = (s32)reg->smax_value;
6310 init_s64_min = (s32)reg->smin_value;
6311 }
6312
6313 s64_max = max(init_s64_max, init_s64_min);
6314 s64_min = min(init_s64_max, init_s64_min);
6315
6316 /* both of s64_max/s64_min positive or negative */
09fedc73 6317 if ((s64_max >= 0) == (s64_min >= 0)) {
1f9a1ea8
YS
6318 reg->smin_value = reg->s32_min_value = s64_min;
6319 reg->smax_value = reg->s32_max_value = s64_max;
6320 reg->umin_value = reg->u32_min_value = s64_min;
6321 reg->umax_value = reg->u32_max_value = s64_max;
6322 reg->var_off = tnum_range(s64_min, s64_max);
6323 return;
6324 }
6325
6326out:
6327 set_sext64_default_val(reg, size);
6328}
6329
8100928c
YS
6330static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6331{
6332 if (size == 1) {
6333 reg->s32_min_value = S8_MIN;
6334 reg->s32_max_value = S8_MAX;
6335 } else {
6336 /* size == 2 */
6337 reg->s32_min_value = S16_MIN;
6338 reg->s32_max_value = S16_MAX;
6339 }
6340 reg->u32_min_value = 0;
6341 reg->u32_max_value = U32_MAX;
6342}
6343
6344static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6345{
6346 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6347 u32 top_smax_value, top_smin_value;
6348 u32 num_bits = size * 8;
6349
6350 if (tnum_is_const(reg->var_off)) {
6351 u32_val = reg->var_off.value;
6352 if (size == 1)
6353 reg->var_off = tnum_const((s8)u32_val);
6354 else
6355 reg->var_off = tnum_const((s16)u32_val);
6356
6357 u32_val = reg->var_off.value;
6358 reg->s32_min_value = reg->s32_max_value = u32_val;
6359 reg->u32_min_value = reg->u32_max_value = u32_val;
6360 return;
6361 }
6362
6363 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6364 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6365
6366 if (top_smax_value != top_smin_value)
6367 goto out;
6368
6369 /* find the s32_min and s32_min after sign extension */
6370 if (size == 1) {
6371 init_s32_max = (s8)reg->s32_max_value;
6372 init_s32_min = (s8)reg->s32_min_value;
6373 } else {
6374 /* size == 2 */
6375 init_s32_max = (s16)reg->s32_max_value;
6376 init_s32_min = (s16)reg->s32_min_value;
6377 }
6378 s32_max = max(init_s32_max, init_s32_min);
6379 s32_min = min(init_s32_max, init_s32_min);
6380
09fedc73 6381 if ((s32_min >= 0) == (s32_max >= 0)) {
8100928c
YS
6382 reg->s32_min_value = s32_min;
6383 reg->s32_max_value = s32_max;
6384 reg->u32_min_value = (u32)s32_min;
6385 reg->u32_max_value = (u32)s32_max;
6386 return;
6387 }
6388
6389out:
6390 set_sext32_default_val(reg, size);
6391}
6392
a23740ec
AN
6393static bool bpf_map_is_rdonly(const struct bpf_map *map)
6394{
353050be
DB
6395 /* A map is considered read-only if the following condition are true:
6396 *
6397 * 1) BPF program side cannot change any of the map content. The
6398 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6399 * and was set at map creation time.
6400 * 2) The map value(s) have been initialized from user space by a
6401 * loader and then "frozen", such that no new map update/delete
6402 * operations from syscall side are possible for the rest of
6403 * the map's lifetime from that point onwards.
6404 * 3) Any parallel/pending map update/delete operations from syscall
6405 * side have been completed. Only after that point, it's safe to
6406 * assume that map value(s) are immutable.
6407 */
6408 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6409 READ_ONCE(map->frozen) &&
6410 !bpf_map_write_active(map);
a23740ec
AN
6411}
6412
1f9a1ea8
YS
6413static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6414 bool is_ldsx)
a23740ec
AN
6415{
6416 void *ptr;
6417 u64 addr;
6418 int err;
6419
6420 err = map->ops->map_direct_value_addr(map, &addr, off);
6421 if (err)
6422 return err;
2dedd7d2 6423 ptr = (void *)(long)addr + off;
a23740ec
AN
6424
6425 switch (size) {
6426 case sizeof(u8):
1f9a1ea8 6427 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
a23740ec
AN
6428 break;
6429 case sizeof(u16):
1f9a1ea8 6430 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
a23740ec
AN
6431 break;
6432 case sizeof(u32):
1f9a1ea8 6433 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
a23740ec
AN
6434 break;
6435 case sizeof(u64):
6436 *val = *(u64 *)ptr;
6437 break;
6438 default:
6439 return -EINVAL;
6440 }
6441 return 0;
6442}
6443
6fcd486b 6444#define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
30ee9821 6445#define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6fcd486b 6446#define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
57539b1c 6447
6fcd486b
AS
6448/*
6449 * Allow list few fields as RCU trusted or full trusted.
6450 * This logic doesn't allow mix tagging and will be removed once GCC supports
6451 * btf_type_tag.
6452 */
6453
6454/* RCU trusted: these fields are trusted in RCU CS and never NULL */
6455BTF_TYPE_SAFE_RCU(struct task_struct) {
57539b1c 6456 const cpumask_t *cpus_ptr;
8d093b4e 6457 struct css_set __rcu *cgroups;
6fcd486b
AS
6458 struct task_struct __rcu *real_parent;
6459 struct task_struct *group_leader;
8d093b4e
AS
6460};
6461
30ee9821
AS
6462BTF_TYPE_SAFE_RCU(struct cgroup) {
6463 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6464 struct kernfs_node *kn;
6465};
6466
6fcd486b 6467BTF_TYPE_SAFE_RCU(struct css_set) {
8d093b4e 6468 struct cgroup *dfl_cgrp;
57539b1c
DV
6469};
6470
30ee9821
AS
6471/* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6472BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6473 struct file __rcu *exe_file;
6474};
6475
6476/* skb->sk, req->sk are not RCU protected, but we mark them as such
6477 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6478 */
6479BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6480 struct sock *sk;
6481};
6482
6483BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6484 struct sock *sk;
6485};
6486
6fcd486b
AS
6487/* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6488BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
63260df1 6489 struct seq_file *seq;
6fcd486b
AS
6490};
6491
6492BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
63260df1
AS
6493 struct bpf_iter_meta *meta;
6494 struct task_struct *task;
6fcd486b
AS
6495};
6496
6497BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6498 struct file *file;
6499};
6500
6501BTF_TYPE_SAFE_TRUSTED(struct file) {
6502 struct inode *f_inode;
6503};
6504
6505BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6506 /* no negative dentry-s in places where bpf can see it */
6507 struct inode *d_inode;
6508};
6509
6510BTF_TYPE_SAFE_TRUSTED(struct socket) {
6511 struct sock *sk;
6512};
6513
6514static bool type_is_rcu(struct bpf_verifier_env *env,
6515 struct bpf_reg_state *reg,
63260df1 6516 const char *field_name, u32 btf_id)
57539b1c 6517{
6fcd486b 6518 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
30ee9821 6519 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6fcd486b 6520 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
57539b1c 6521
63260df1 6522 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6fcd486b 6523}
57539b1c 6524
30ee9821
AS
6525static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6526 struct bpf_reg_state *reg,
6527 const char *field_name, u32 btf_id)
6528{
6529 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6530 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6531 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6532
6533 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6534}
6535
6fcd486b
AS
6536static bool type_is_trusted(struct bpf_verifier_env *env,
6537 struct bpf_reg_state *reg,
63260df1 6538 const char *field_name, u32 btf_id)
6fcd486b
AS
6539{
6540 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6541 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6542 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6543 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6544 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6545 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6546
63260df1 6547 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
57539b1c
DV
6548}
6549
9e15db66
AS
6550static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6551 struct bpf_reg_state *regs,
6552 int regno, int off, int size,
6553 enum bpf_access_type atype,
6554 int value_regno)
6555{
6556 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
6557 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6558 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
63260df1 6559 const char *field_name = NULL;
c6f1bfe8 6560 enum bpf_type_flag flag = 0;
b7e852a9 6561 u32 btf_id = 0;
9e15db66
AS
6562 int ret;
6563
c67cae55
AS
6564 if (!env->allow_ptr_leaks) {
6565 verbose(env,
6566 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6567 tname);
6568 return -EPERM;
6569 }
6570 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6571 verbose(env,
6572 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6573 tname);
6574 return -EINVAL;
6575 }
9e15db66
AS
6576 if (off < 0) {
6577 verbose(env,
6578 "R%d is ptr_%s invalid negative access: off=%d\n",
6579 regno, tname, off);
6580 return -EACCES;
6581 }
6582 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6583 char tn_buf[48];
6584
6585 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6586 verbose(env,
6587 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6588 regno, tname, off, tn_buf);
6589 return -EACCES;
6590 }
6591
c6f1bfe8
YS
6592 if (reg->type & MEM_USER) {
6593 verbose(env,
6594 "R%d is ptr_%s access user memory: off=%d\n",
6595 regno, tname, off);
6596 return -EACCES;
6597 }
6598
5844101a
HL
6599 if (reg->type & MEM_PERCPU) {
6600 verbose(env,
6601 "R%d is ptr_%s access percpu memory: off=%d\n",
6602 regno, tname, off);
6603 return -EACCES;
6604 }
6605
7d64c513 6606 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
282de143
KKD
6607 if (!btf_is_kernel(reg->btf)) {
6608 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6609 return -EFAULT;
6610 }
b7e852a9 6611 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
27ae7997 6612 } else {
282de143
KKD
6613 /* Writes are permitted with default btf_struct_access for
6614 * program allocated objects (which always have ref_obj_id > 0),
6615 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6616 */
503e4def 6617 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
27ae7997
MKL
6618 verbose(env, "only read is supported\n");
6619 return -EACCES;
6620 }
6621
6a3cd331 6622 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
01cc55af 6623 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
282de143
KKD
6624 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6625 return -EFAULT;
6626 }
6627
63260df1 6628 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
27ae7997
MKL
6629 }
6630
9e15db66
AS
6631 if (ret < 0)
6632 return ret;
6633
6fcd486b
AS
6634 if (ret != PTR_TO_BTF_ID) {
6635 /* just mark; */
6efe152d 6636
6fcd486b
AS
6637 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6638 /* If this is an untrusted pointer, all pointers formed by walking it
6639 * also inherit the untrusted flag.
6640 */
6641 flag = PTR_UNTRUSTED;
6642
6643 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6644 /* By default any pointer obtained from walking a trusted pointer is no
6645 * longer trusted, unless the field being accessed has explicitly been
6646 * marked as inheriting its parent's state of trust (either full or RCU).
6647 * For example:
6648 * 'cgroups' pointer is untrusted if task->cgroups dereference
6649 * happened in a sleepable program outside of bpf_rcu_read_lock()
6650 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6651 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6652 *
6653 * A regular RCU-protected pointer with __rcu tag can also be deemed
6654 * trusted if we are in an RCU CS. Such pointer can be NULL.
20c09d92 6655 */
63260df1 6656 if (type_is_trusted(env, reg, field_name, btf_id)) {
6fcd486b
AS
6657 flag |= PTR_TRUSTED;
6658 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
63260df1 6659 if (type_is_rcu(env, reg, field_name, btf_id)) {
6fcd486b
AS
6660 /* ignore __rcu tag and mark it MEM_RCU */
6661 flag |= MEM_RCU;
30ee9821
AS
6662 } else if (flag & MEM_RCU ||
6663 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6fcd486b 6664 /* __rcu tagged pointers can be NULL */
30ee9821 6665 flag |= MEM_RCU | PTR_MAYBE_NULL;
7ce4dc3e
YS
6666
6667 /* We always trust them */
6668 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6669 flag & PTR_UNTRUSTED)
6670 flag &= ~PTR_UNTRUSTED;
6fcd486b
AS
6671 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6672 /* keep as-is */
6673 } else {
afeebf9f
AS
6674 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6675 clear_trusted_flags(&flag);
6fcd486b
AS
6676 }
6677 } else {
6678 /*
6679 * If not in RCU CS or MEM_RCU pointer can be NULL then
6680 * aggressively mark as untrusted otherwise such
6681 * pointers will be plain PTR_TO_BTF_ID without flags
6682 * and will be allowed to be passed into helpers for
6683 * compat reasons.
6684 */
6685 flag = PTR_UNTRUSTED;
6686 }
20c09d92 6687 } else {
6fcd486b 6688 /* Old compat. Deprecated */
afeebf9f 6689 clear_trusted_flags(&flag);
20c09d92 6690 }
3f00c523 6691
41c48f3a 6692 if (atype == BPF_READ && value_regno >= 0)
c6f1bfe8 6693 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
41c48f3a
AI
6694
6695 return 0;
6696}
6697
6698static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6699 struct bpf_reg_state *regs,
6700 int regno, int off, int size,
6701 enum bpf_access_type atype,
6702 int value_regno)
6703{
6704 struct bpf_reg_state *reg = regs + regno;
6705 struct bpf_map *map = reg->map_ptr;
6728aea7 6706 struct bpf_reg_state map_reg;
c6f1bfe8 6707 enum bpf_type_flag flag = 0;
41c48f3a
AI
6708 const struct btf_type *t;
6709 const char *tname;
6710 u32 btf_id;
6711 int ret;
6712
6713 if (!btf_vmlinux) {
6714 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6715 return -ENOTSUPP;
6716 }
6717
6718 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6719 verbose(env, "map_ptr access not supported for map type %d\n",
6720 map->map_type);
6721 return -ENOTSUPP;
6722 }
6723
6724 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6725 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6726
c67cae55 6727 if (!env->allow_ptr_leaks) {
41c48f3a 6728 verbose(env,
c67cae55 6729 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
41c48f3a
AI
6730 tname);
6731 return -EPERM;
9e15db66 6732 }
27ae7997 6733
41c48f3a
AI
6734 if (off < 0) {
6735 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6736 regno, tname, off);
6737 return -EACCES;
6738 }
6739
6740 if (atype != BPF_READ) {
6741 verbose(env, "only read from %s is supported\n", tname);
6742 return -EACCES;
6743 }
6744
6728aea7
KKD
6745 /* Simulate access to a PTR_TO_BTF_ID */
6746 memset(&map_reg, 0, sizeof(map_reg));
6747 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
63260df1 6748 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
41c48f3a
AI
6749 if (ret < 0)
6750 return ret;
6751
6752 if (value_regno >= 0)
c6f1bfe8 6753 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
41c48f3a 6754
9e15db66
AS
6755 return 0;
6756}
6757
01f810ac
AM
6758/* Check that the stack access at the given offset is within bounds. The
6759 * maximum valid offset is -1.
6760 *
6761 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6762 * -state->allocated_stack for reads.
6763 */
6764static int check_stack_slot_within_bounds(int off,
6765 struct bpf_func_state *state,
6766 enum bpf_access_type t)
6767{
6768 int min_valid_off;
6769
6770 if (t == BPF_WRITE)
6771 min_valid_off = -MAX_BPF_STACK;
6772 else
6773 min_valid_off = -state->allocated_stack;
6774
6775 if (off < min_valid_off || off > -1)
6776 return -EACCES;
6777 return 0;
6778}
6779
6780/* Check that the stack access at 'regno + off' falls within the maximum stack
6781 * bounds.
6782 *
6783 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6784 */
6785static int check_stack_access_within_bounds(
6786 struct bpf_verifier_env *env,
6787 int regno, int off, int access_size,
61df10c7 6788 enum bpf_access_src src, enum bpf_access_type type)
01f810ac
AM
6789{
6790 struct bpf_reg_state *regs = cur_regs(env);
6791 struct bpf_reg_state *reg = regs + regno;
6792 struct bpf_func_state *state = func(env, reg);
6793 int min_off, max_off;
6794 int err;
6795 char *err_extra;
6796
6797 if (src == ACCESS_HELPER)
6798 /* We don't know if helpers are reading or writing (or both). */
6799 err_extra = " indirect access to";
6800 else if (type == BPF_READ)
6801 err_extra = " read from";
6802 else
6803 err_extra = " write to";
6804
6805 if (tnum_is_const(reg->var_off)) {
6806 min_off = reg->var_off.value + off;
6807 if (access_size > 0)
6808 max_off = min_off + access_size - 1;
6809 else
6810 max_off = min_off;
6811 } else {
6812 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6813 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6814 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6815 err_extra, regno);
6816 return -EACCES;
6817 }
6818 min_off = reg->smin_value + off;
6819 if (access_size > 0)
6820 max_off = reg->smax_value + off + access_size - 1;
6821 else
6822 max_off = min_off;
6823 }
6824
6825 err = check_stack_slot_within_bounds(min_off, state, type);
6826 if (!err)
6827 err = check_stack_slot_within_bounds(max_off, state, type);
6828
6829 if (err) {
6830 if (tnum_is_const(reg->var_off)) {
6831 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6832 err_extra, regno, off, access_size);
6833 } else {
6834 char tn_buf[48];
6835
6836 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6837 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6838 err_extra, regno, tn_buf, access_size);
6839 }
6840 }
6841 return err;
6842}
41c48f3a 6843
17a52670
AS
6844/* check whether memory at (regno + off) is accessible for t = (read | write)
6845 * if t==write, value_regno is a register which value is stored into memory
6846 * if t==read, value_regno is a register which will receive the value from memory
6847 * if t==write && value_regno==-1, some unknown value is stored into memory
6848 * if t==read && value_regno==-1, don't care what we read from memory
6849 */
ca369602
DB
6850static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6851 int off, int bpf_size, enum bpf_access_type t,
1f9a1ea8 6852 int value_regno, bool strict_alignment_once, bool is_ldsx)
17a52670 6853{
638f5b90
AS
6854 struct bpf_reg_state *regs = cur_regs(env);
6855 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 6856 struct bpf_func_state *state;
17a52670
AS
6857 int size, err = 0;
6858
6859 size = bpf_size_to_bytes(bpf_size);
6860 if (size < 0)
6861 return size;
6862
f1174f77 6863 /* alignment checks will add in reg->off themselves */
ca369602 6864 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
6865 if (err)
6866 return err;
17a52670 6867
f1174f77
EC
6868 /* for access checks, reg->off is just part of off */
6869 off += reg->off;
6870
69c087ba
YS
6871 if (reg->type == PTR_TO_MAP_KEY) {
6872 if (t == BPF_WRITE) {
6873 verbose(env, "write to change key R%d not allowed\n", regno);
6874 return -EACCES;
6875 }
6876
6877 err = check_mem_region_access(env, regno, off, size,
6878 reg->map_ptr->key_size, false);
6879 if (err)
6880 return err;
6881 if (value_regno >= 0)
6882 mark_reg_unknown(env, regs, value_regno);
6883 } else if (reg->type == PTR_TO_MAP_VALUE) {
aa3496ac 6884 struct btf_field *kptr_field = NULL;
61df10c7 6885
1be7f75d
AS
6886 if (t == BPF_WRITE && value_regno >= 0 &&
6887 is_pointer_value(env, value_regno)) {
61bd5218 6888 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
6889 return -EACCES;
6890 }
591fe988
DB
6891 err = check_map_access_type(env, regno, off, size, t);
6892 if (err)
6893 return err;
61df10c7
KKD
6894 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6895 if (err)
6896 return err;
6897 if (tnum_is_const(reg->var_off))
aa3496ac
KKD
6898 kptr_field = btf_record_find(reg->map_ptr->record,
6899 off + reg->var_off.value, BPF_KPTR);
6900 if (kptr_field) {
6901 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
61df10c7 6902 } else if (t == BPF_READ && value_regno >= 0) {
a23740ec
AN
6903 struct bpf_map *map = reg->map_ptr;
6904
6905 /* if map is read-only, track its contents as scalars */
6906 if (tnum_is_const(reg->var_off) &&
6907 bpf_map_is_rdonly(map) &&
6908 map->ops->map_direct_value_addr) {
6909 int map_off = off + reg->var_off.value;
6910 u64 val = 0;
6911
6912 err = bpf_map_direct_read(map, map_off, size,
1f9a1ea8 6913 &val, is_ldsx);
a23740ec
AN
6914 if (err)
6915 return err;
6916
6917 regs[value_regno].type = SCALAR_VALUE;
6918 __mark_reg_known(&regs[value_regno], val);
6919 } else {
6920 mark_reg_unknown(env, regs, value_regno);
6921 }
6922 }
34d3a78c
HL
6923 } else if (base_type(reg->type) == PTR_TO_MEM) {
6924 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6925
6926 if (type_may_be_null(reg->type)) {
6927 verbose(env, "R%d invalid mem access '%s'\n", regno,
6928 reg_type_str(env, reg->type));
6929 return -EACCES;
6930 }
6931
6932 if (t == BPF_WRITE && rdonly_mem) {
6933 verbose(env, "R%d cannot write into %s\n",
6934 regno, reg_type_str(env, reg->type));
6935 return -EACCES;
6936 }
6937
457f4436
AN
6938 if (t == BPF_WRITE && value_regno >= 0 &&
6939 is_pointer_value(env, value_regno)) {
6940 verbose(env, "R%d leaks addr into mem\n", value_regno);
6941 return -EACCES;
6942 }
34d3a78c 6943
457f4436
AN
6944 err = check_mem_region_access(env, regno, off, size,
6945 reg->mem_size, false);
34d3a78c 6946 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
457f4436 6947 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 6948 } else if (reg->type == PTR_TO_CTX) {
f1174f77 6949 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 6950 struct btf *btf = NULL;
9e15db66 6951 u32 btf_id = 0;
19de99f7 6952
1be7f75d
AS
6953 if (t == BPF_WRITE && value_regno >= 0 &&
6954 is_pointer_value(env, value_regno)) {
61bd5218 6955 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
6956 return -EACCES;
6957 }
f1174f77 6958
be80a1d3 6959 err = check_ptr_off_reg(env, reg, regno);
58990d1f
DB
6960 if (err < 0)
6961 return err;
6962
c6f1bfe8
YS
6963 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6964 &btf_id);
9e15db66
AS
6965 if (err)
6966 verbose_linfo(env, insn_idx, "; ");
969bf05e 6967 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 6968 /* ctx access returns either a scalar, or a
de8f3a83
DB
6969 * PTR_TO_PACKET[_META,_END]. In the latter
6970 * case, we know the offset is zero.
f1174f77 6971 */
46f8bc92 6972 if (reg_type == SCALAR_VALUE) {
638f5b90 6973 mark_reg_unknown(env, regs, value_regno);
46f8bc92 6974 } else {
638f5b90 6975 mark_reg_known_zero(env, regs,
61bd5218 6976 value_regno);
c25b2ae1 6977 if (type_may_be_null(reg_type))
46f8bc92 6978 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
6979 /* A load of ctx field could have different
6980 * actual load size with the one encoded in the
6981 * insn. When the dst is PTR, it is for sure not
6982 * a sub-register.
6983 */
6984 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
c25b2ae1 6985 if (base_type(reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 6986 regs[value_regno].btf = btf;
9e15db66 6987 regs[value_regno].btf_id = btf_id;
22dc4a0f 6988 }
46f8bc92 6989 }
638f5b90 6990 regs[value_regno].type = reg_type;
969bf05e 6991 }
17a52670 6992
f1174f77 6993 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
6994 /* Basic bounds checks. */
6995 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
6996 if (err)
6997 return err;
8726679a 6998
f4d7e40a
AS
6999 state = func(env, reg);
7000 err = update_stack_depth(env, state, off);
7001 if (err)
7002 return err;
8726679a 7003
01f810ac
AM
7004 if (t == BPF_READ)
7005 err = check_stack_read(env, regno, off, size,
61bd5218 7006 value_regno);
01f810ac
AM
7007 else
7008 err = check_stack_write(env, regno, off, size,
7009 value_regno, insn_idx);
de8f3a83 7010 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 7011 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 7012 verbose(env, "cannot write into packet\n");
969bf05e
AS
7013 return -EACCES;
7014 }
4acf6c0b
BB
7015 if (t == BPF_WRITE && value_regno >= 0 &&
7016 is_pointer_value(env, value_regno)) {
61bd5218
JK
7017 verbose(env, "R%d leaks addr into packet\n",
7018 value_regno);
4acf6c0b
BB
7019 return -EACCES;
7020 }
9fd29c08 7021 err = check_packet_access(env, regno, off, size, false);
969bf05e 7022 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 7023 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
7024 } else if (reg->type == PTR_TO_FLOW_KEYS) {
7025 if (t == BPF_WRITE && value_regno >= 0 &&
7026 is_pointer_value(env, value_regno)) {
7027 verbose(env, "R%d leaks addr into flow keys\n",
7028 value_regno);
7029 return -EACCES;
7030 }
7031
7032 err = check_flow_keys_access(env, off, size);
7033 if (!err && t == BPF_READ && value_regno >= 0)
7034 mark_reg_unknown(env, regs, value_regno);
46f8bc92 7035 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 7036 if (t == BPF_WRITE) {
46f8bc92 7037 verbose(env, "R%d cannot write into %s\n",
c25b2ae1 7038 regno, reg_type_str(env, reg->type));
c64b7983
JS
7039 return -EACCES;
7040 }
5f456649 7041 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
7042 if (!err && value_regno >= 0)
7043 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
7044 } else if (reg->type == PTR_TO_TP_BUFFER) {
7045 err = check_tp_buffer_access(env, reg, regno, off, size);
7046 if (!err && t == BPF_READ && value_regno >= 0)
7047 mark_reg_unknown(env, regs, value_regno);
bff61f6f
HL
7048 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7049 !type_may_be_null(reg->type)) {
9e15db66
AS
7050 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7051 value_regno);
41c48f3a
AI
7052 } else if (reg->type == CONST_PTR_TO_MAP) {
7053 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7054 value_regno);
20b2aff4
HL
7055 } else if (base_type(reg->type) == PTR_TO_BUF) {
7056 bool rdonly_mem = type_is_rdonly_mem(reg->type);
20b2aff4
HL
7057 u32 *max_access;
7058
7059 if (rdonly_mem) {
7060 if (t == BPF_WRITE) {
7061 verbose(env, "R%d cannot write into %s\n",
7062 regno, reg_type_str(env, reg->type));
7063 return -EACCES;
7064 }
20b2aff4
HL
7065 max_access = &env->prog->aux->max_rdonly_access;
7066 } else {
20b2aff4 7067 max_access = &env->prog->aux->max_rdwr_access;
afbf21dc 7068 }
20b2aff4 7069
f6dfbe31 7070 err = check_buffer_access(env, reg, regno, off, size, false,
44e9a741 7071 max_access);
20b2aff4
HL
7072
7073 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
afbf21dc 7074 mark_reg_unknown(env, regs, value_regno);
17a52670 7075 } else {
61bd5218 7076 verbose(env, "R%d invalid mem access '%s'\n", regno,
c25b2ae1 7077 reg_type_str(env, reg->type));
17a52670
AS
7078 return -EACCES;
7079 }
969bf05e 7080
f1174f77 7081 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 7082 regs[value_regno].type == SCALAR_VALUE) {
1f9a1ea8
YS
7083 if (!is_ldsx)
7084 /* b/h/w load zero-extends, mark upper bits as known 0 */
7085 coerce_reg_to_size(&regs[value_regno], size);
7086 else
7087 coerce_reg_to_size_sx(&regs[value_regno], size);
969bf05e 7088 }
17a52670
AS
7089 return err;
7090}
7091
91c960b0 7092static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 7093{
5ffa2550 7094 int load_reg;
17a52670
AS
7095 int err;
7096
5ca419f2
BJ
7097 switch (insn->imm) {
7098 case BPF_ADD:
7099 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
7100 case BPF_AND:
7101 case BPF_AND | BPF_FETCH:
7102 case BPF_OR:
7103 case BPF_OR | BPF_FETCH:
7104 case BPF_XOR:
7105 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
7106 case BPF_XCHG:
7107 case BPF_CMPXCHG:
5ca419f2
BJ
7108 break;
7109 default:
91c960b0
BJ
7110 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7111 return -EINVAL;
7112 }
7113
7114 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7115 verbose(env, "invalid atomic operand size\n");
17a52670
AS
7116 return -EINVAL;
7117 }
7118
7119 /* check src1 operand */
dc503a8a 7120 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7121 if (err)
7122 return err;
7123
7124 /* check src2 operand */
dc503a8a 7125 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7126 if (err)
7127 return err;
7128
5ffa2550
BJ
7129 if (insn->imm == BPF_CMPXCHG) {
7130 /* Check comparison of R0 with memory location */
a82fe085
DB
7131 const u32 aux_reg = BPF_REG_0;
7132
7133 err = check_reg_arg(env, aux_reg, SRC_OP);
5ffa2550
BJ
7134 if (err)
7135 return err;
a82fe085
DB
7136
7137 if (is_pointer_value(env, aux_reg)) {
7138 verbose(env, "R%d leaks addr into mem\n", aux_reg);
7139 return -EACCES;
7140 }
5ffa2550
BJ
7141 }
7142
6bdf6abc 7143 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 7144 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
7145 return -EACCES;
7146 }
7147
ca369602 7148 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 7149 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
7150 is_flow_key_reg(env, insn->dst_reg) ||
7151 is_sk_reg(env, insn->dst_reg)) {
91c960b0 7152 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f 7153 insn->dst_reg,
c25b2ae1 7154 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
7155 return -EACCES;
7156 }
7157
37086bfd
BJ
7158 if (insn->imm & BPF_FETCH) {
7159 if (insn->imm == BPF_CMPXCHG)
7160 load_reg = BPF_REG_0;
7161 else
7162 load_reg = insn->src_reg;
7163
7164 /* check and record load of old value */
7165 err = check_reg_arg(env, load_reg, DST_OP);
7166 if (err)
7167 return err;
7168 } else {
7169 /* This instruction accesses a memory location but doesn't
7170 * actually load it into a register.
7171 */
7172 load_reg = -1;
7173 }
7174
7d3baf0a
DB
7175 /* Check whether we can read the memory, with second call for fetch
7176 * case to simulate the register fill.
7177 */
31fd8581 7178 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1f9a1ea8 7179 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7d3baf0a
DB
7180 if (!err && load_reg >= 0)
7181 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7182 BPF_SIZE(insn->code), BPF_READ, load_reg,
1f9a1ea8 7183 true, false);
17a52670
AS
7184 if (err)
7185 return err;
7186
7d3baf0a 7187 /* Check whether we can write into the same memory. */
5ca419f2 7188 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1f9a1ea8 7189 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
5ca419f2
BJ
7190 if (err)
7191 return err;
7192
5ca419f2 7193 return 0;
17a52670
AS
7194}
7195
01f810ac
AM
7196/* When register 'regno' is used to read the stack (either directly or through
7197 * a helper function) make sure that it's within stack boundary and, depending
7198 * on the access type, that all elements of the stack are initialized.
7199 *
7200 * 'off' includes 'regno->off', but not its dynamic part (if any).
7201 *
7202 * All registers that have been spilled on the stack in the slots within the
7203 * read offsets are marked as read.
7204 */
7205static int check_stack_range_initialized(
7206 struct bpf_verifier_env *env, int regno, int off,
7207 int access_size, bool zero_size_allowed,
61df10c7 7208 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
7209{
7210 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
7211 struct bpf_func_state *state = func(env, reg);
7212 int err, min_off, max_off, i, j, slot, spi;
7213 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7214 enum bpf_access_type bounds_check_type;
7215 /* Some accesses can write anything into the stack, others are
7216 * read-only.
7217 */
7218 bool clobber = false;
2011fccf 7219
01f810ac
AM
7220 if (access_size == 0 && !zero_size_allowed) {
7221 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
7222 return -EACCES;
7223 }
2011fccf 7224
01f810ac
AM
7225 if (type == ACCESS_HELPER) {
7226 /* The bounds checks for writes are more permissive than for
7227 * reads. However, if raw_mode is not set, we'll do extra
7228 * checks below.
7229 */
7230 bounds_check_type = BPF_WRITE;
7231 clobber = true;
7232 } else {
7233 bounds_check_type = BPF_READ;
7234 }
7235 err = check_stack_access_within_bounds(env, regno, off, access_size,
7236 type, bounds_check_type);
7237 if (err)
7238 return err;
7239
17a52670 7240
2011fccf 7241 if (tnum_is_const(reg->var_off)) {
01f810ac 7242 min_off = max_off = reg->var_off.value + off;
2011fccf 7243 } else {
088ec26d
AI
7244 /* Variable offset is prohibited for unprivileged mode for
7245 * simplicity since it requires corresponding support in
7246 * Spectre masking for stack ALU.
7247 * See also retrieve_ptr_limit().
7248 */
2c78ee89 7249 if (!env->bypass_spec_v1) {
088ec26d 7250 char tn_buf[48];
f1174f77 7251
088ec26d 7252 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
7253 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7254 regno, err_extra, tn_buf);
088ec26d
AI
7255 return -EACCES;
7256 }
f2bcd05e
AI
7257 /* Only initialized buffer on stack is allowed to be accessed
7258 * with variable offset. With uninitialized buffer it's hard to
7259 * guarantee that whole memory is marked as initialized on
7260 * helper return since specific bounds are unknown what may
7261 * cause uninitialized stack leaking.
7262 */
7263 if (meta && meta->raw_mode)
7264 meta = NULL;
7265
01f810ac
AM
7266 min_off = reg->smin_value + off;
7267 max_off = reg->smax_value + off;
17a52670
AS
7268 }
7269
435faee1 7270 if (meta && meta->raw_mode) {
ef8fc7a0
KKD
7271 /* Ensure we won't be overwriting dynptrs when simulating byte
7272 * by byte access in check_helper_call using meta.access_size.
7273 * This would be a problem if we have a helper in the future
7274 * which takes:
7275 *
7276 * helper(uninit_mem, len, dynptr)
7277 *
7278 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7279 * may end up writing to dynptr itself when touching memory from
7280 * arg 1. This can be relaxed on a case by case basis for known
7281 * safe cases, but reject due to the possibilitiy of aliasing by
7282 * default.
7283 */
7284 for (i = min_off; i < max_off + access_size; i++) {
7285 int stack_off = -i - 1;
7286
7287 spi = __get_spi(i);
7288 /* raw_mode may write past allocated_stack */
7289 if (state->allocated_stack <= stack_off)
7290 continue;
7291 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7292 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7293 return -EACCES;
7294 }
7295 }
435faee1
DB
7296 meta->access_size = access_size;
7297 meta->regno = regno;
7298 return 0;
7299 }
7300
2011fccf 7301 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
7302 u8 *stype;
7303
2011fccf 7304 slot = -i - 1;
638f5b90 7305 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
7306 if (state->allocated_stack <= slot)
7307 goto err;
7308 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7309 if (*stype == STACK_MISC)
7310 goto mark;
6715df8d
EZ
7311 if ((*stype == STACK_ZERO) ||
7312 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
01f810ac
AM
7313 if (clobber) {
7314 /* helper can write anything into the stack */
7315 *stype = STACK_MISC;
7316 }
cc2b14d5 7317 goto mark;
17a52670 7318 }
1d68f22b 7319
27113c59 7320 if (is_spilled_reg(&state->stack[spi]) &&
cd17d38f
YS
7321 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7322 env->allow_ptr_leaks)) {
01f810ac
AM
7323 if (clobber) {
7324 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7325 for (j = 0; j < BPF_REG_SIZE; j++)
354e8f19 7326 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
01f810ac 7327 }
f7cf25b2
AS
7328 goto mark;
7329 }
7330
cc2b14d5 7331err:
2011fccf 7332 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
7333 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7334 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
7335 } else {
7336 char tn_buf[48];
7337
7338 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
7339 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7340 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 7341 }
cc2b14d5
AS
7342 return -EACCES;
7343mark:
7344 /* reading any byte out of 8-byte 'spill_slot' will cause
7345 * the whole slot to be marked as 'read'
7346 */
679c782d 7347 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
7348 state->stack[spi].spilled_ptr.parent,
7349 REG_LIVE_READ64);
261f4664
KKD
7350 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7351 * be sure that whether stack slot is written to or not. Hence,
7352 * we must still conservatively propagate reads upwards even if
7353 * helper may write to the entire memory range.
7354 */
17a52670 7355 }
2011fccf 7356 return update_stack_depth(env, state, min_off);
17a52670
AS
7357}
7358
06c1c049
GB
7359static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7360 int access_size, bool zero_size_allowed,
7361 struct bpf_call_arg_meta *meta)
7362{
638f5b90 7363 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
20b2aff4 7364 u32 *max_access;
06c1c049 7365
20b2aff4 7366 switch (base_type(reg->type)) {
06c1c049 7367 case PTR_TO_PACKET:
de8f3a83 7368 case PTR_TO_PACKET_META:
9fd29c08
YS
7369 return check_packet_access(env, regno, reg->off, access_size,
7370 zero_size_allowed);
69c087ba 7371 case PTR_TO_MAP_KEY:
7b3552d3
KKD
7372 if (meta && meta->raw_mode) {
7373 verbose(env, "R%d cannot write into %s\n", regno,
7374 reg_type_str(env, reg->type));
7375 return -EACCES;
7376 }
69c087ba
YS
7377 return check_mem_region_access(env, regno, reg->off, access_size,
7378 reg->map_ptr->key_size, false);
06c1c049 7379 case PTR_TO_MAP_VALUE:
591fe988
DB
7380 if (check_map_access_type(env, regno, reg->off, access_size,
7381 meta && meta->raw_mode ? BPF_WRITE :
7382 BPF_READ))
7383 return -EACCES;
9fd29c08 7384 return check_map_access(env, regno, reg->off, access_size,
61df10c7 7385 zero_size_allowed, ACCESS_HELPER);
457f4436 7386 case PTR_TO_MEM:
97e6d7da
KKD
7387 if (type_is_rdonly_mem(reg->type)) {
7388 if (meta && meta->raw_mode) {
7389 verbose(env, "R%d cannot write into %s\n", regno,
7390 reg_type_str(env, reg->type));
7391 return -EACCES;
7392 }
7393 }
457f4436
AN
7394 return check_mem_region_access(env, regno, reg->off,
7395 access_size, reg->mem_size,
7396 zero_size_allowed);
20b2aff4
HL
7397 case PTR_TO_BUF:
7398 if (type_is_rdonly_mem(reg->type)) {
97e6d7da
KKD
7399 if (meta && meta->raw_mode) {
7400 verbose(env, "R%d cannot write into %s\n", regno,
7401 reg_type_str(env, reg->type));
20b2aff4 7402 return -EACCES;
97e6d7da 7403 }
20b2aff4 7404
20b2aff4
HL
7405 max_access = &env->prog->aux->max_rdonly_access;
7406 } else {
20b2aff4
HL
7407 max_access = &env->prog->aux->max_rdwr_access;
7408 }
afbf21dc
YS
7409 return check_buffer_access(env, reg, regno, reg->off,
7410 access_size, zero_size_allowed,
44e9a741 7411 max_access);
0d004c02 7412 case PTR_TO_STACK:
01f810ac
AM
7413 return check_stack_range_initialized(
7414 env,
7415 regno, reg->off, access_size,
7416 zero_size_allowed, ACCESS_HELPER, meta);
3e30be42
AS
7417 case PTR_TO_BTF_ID:
7418 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7419 access_size, BPF_READ, -1);
15baa55f
BT
7420 case PTR_TO_CTX:
7421 /* in case the function doesn't know how to access the context,
7422 * (because we are in a program of type SYSCALL for example), we
7423 * can not statically check its size.
7424 * Dynamically check it now.
7425 */
7426 if (!env->ops->convert_ctx_access) {
7427 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7428 int offset = access_size - 1;
7429
7430 /* Allow zero-byte read from PTR_TO_CTX */
7431 if (access_size == 0)
7432 return zero_size_allowed ? 0 : -EACCES;
7433
7434 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
1f9a1ea8 7435 atype, -1, false, false);
15baa55f
BT
7436 }
7437
7438 fallthrough;
0d004c02
LB
7439 default: /* scalar_value or invalid ptr */
7440 /* Allow zero-byte read from NULL, regardless of pointer type */
7441 if (zero_size_allowed && access_size == 0 &&
7442 register_is_null(reg))
7443 return 0;
7444
c25b2ae1
HL
7445 verbose(env, "R%d type=%s ", regno,
7446 reg_type_str(env, reg->type));
7447 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
0d004c02 7448 return -EACCES;
06c1c049
GB
7449 }
7450}
7451
d583691c
KKD
7452static int check_mem_size_reg(struct bpf_verifier_env *env,
7453 struct bpf_reg_state *reg, u32 regno,
7454 bool zero_size_allowed,
7455 struct bpf_call_arg_meta *meta)
7456{
7457 int err;
7458
7459 /* This is used to refine r0 return value bounds for helpers
7460 * that enforce this value as an upper bound on return values.
7461 * See do_refine_retval_range() for helpers that can refine
7462 * the return value. C type of helper is u32 so we pull register
7463 * bound from umax_value however, if negative verifier errors
7464 * out. Only upper bounds can be learned because retval is an
7465 * int type and negative retvals are allowed.
7466 */
be77354a 7467 meta->msize_max_value = reg->umax_value;
d583691c
KKD
7468
7469 /* The register is SCALAR_VALUE; the access check
7470 * happens using its boundaries.
7471 */
7472 if (!tnum_is_const(reg->var_off))
7473 /* For unprivileged variable accesses, disable raw
7474 * mode so that the program is required to
7475 * initialize all the memory that the helper could
7476 * just partially fill up.
7477 */
7478 meta = NULL;
7479
7480 if (reg->smin_value < 0) {
7481 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7482 regno);
7483 return -EACCES;
7484 }
7485
7486 if (reg->umin_value == 0) {
7487 err = check_helper_mem_access(env, regno - 1, 0,
7488 zero_size_allowed,
7489 meta);
7490 if (err)
7491 return err;
7492 }
7493
7494 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7495 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7496 regno);
7497 return -EACCES;
7498 }
7499 err = check_helper_mem_access(env, regno - 1,
7500 reg->umax_value,
7501 zero_size_allowed, meta);
7502 if (!err)
7503 err = mark_chain_precision(env, regno);
7504 return err;
7505}
7506
e5069b9c
DB
7507int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7508 u32 regno, u32 mem_size)
7509{
be77354a
KKD
7510 bool may_be_null = type_may_be_null(reg->type);
7511 struct bpf_reg_state saved_reg;
7512 struct bpf_call_arg_meta meta;
7513 int err;
7514
e5069b9c
DB
7515 if (register_is_null(reg))
7516 return 0;
7517
be77354a
KKD
7518 memset(&meta, 0, sizeof(meta));
7519 /* Assuming that the register contains a value check if the memory
7520 * access is safe. Temporarily save and restore the register's state as
7521 * the conversion shouldn't be visible to a caller.
7522 */
7523 if (may_be_null) {
7524 saved_reg = *reg;
e5069b9c 7525 mark_ptr_not_null_reg(reg);
e5069b9c
DB
7526 }
7527
be77354a
KKD
7528 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7529 /* Check access for BPF_WRITE */
7530 meta.raw_mode = true;
7531 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7532
7533 if (may_be_null)
7534 *reg = saved_reg;
7535
7536 return err;
e5069b9c
DB
7537}
7538
00b85860
KKD
7539static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7540 u32 regno)
d583691c
KKD
7541{
7542 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7543 bool may_be_null = type_may_be_null(mem_reg->type);
7544 struct bpf_reg_state saved_reg;
be77354a 7545 struct bpf_call_arg_meta meta;
d583691c
KKD
7546 int err;
7547
7548 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7549
be77354a
KKD
7550 memset(&meta, 0, sizeof(meta));
7551
d583691c
KKD
7552 if (may_be_null) {
7553 saved_reg = *mem_reg;
7554 mark_ptr_not_null_reg(mem_reg);
7555 }
7556
be77354a
KKD
7557 err = check_mem_size_reg(env, reg, regno, true, &meta);
7558 /* Check access for BPF_WRITE */
7559 meta.raw_mode = true;
7560 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
d583691c
KKD
7561
7562 if (may_be_null)
7563 *mem_reg = saved_reg;
7564 return err;
7565}
7566
d83525ca 7567/* Implementation details:
4e814da0
KKD
7568 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7569 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
d83525ca 7570 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4e814da0
KKD
7571 * Two separate bpf_obj_new will also have different reg->id.
7572 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7573 * clears reg->id after value_or_null->value transition, since the verifier only
7574 * cares about the range of access to valid map value pointer and doesn't care
7575 * about actual address of the map element.
d83525ca
AS
7576 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7577 * reg->id > 0 after value_or_null->value transition. By doing so
7578 * two bpf_map_lookups will be considered two different pointers that
4e814da0
KKD
7579 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7580 * returned from bpf_obj_new.
d83525ca
AS
7581 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7582 * dead-locks.
7583 * Since only one bpf_spin_lock is allowed the checks are simpler than
7584 * reg_is_refcounted() logic. The verifier needs to remember only
7585 * one spin_lock instead of array of acquired_refs.
d0d78c1d 7586 * cur_state->active_lock remembers which map value element or allocated
4e814da0 7587 * object got locked and clears it after bpf_spin_unlock.
d83525ca
AS
7588 */
7589static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7590 bool is_lock)
7591{
7592 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7593 struct bpf_verifier_state *cur = env->cur_state;
7594 bool is_const = tnum_is_const(reg->var_off);
d83525ca 7595 u64 val = reg->var_off.value;
4e814da0
KKD
7596 struct bpf_map *map = NULL;
7597 struct btf *btf = NULL;
7598 struct btf_record *rec;
d83525ca 7599
d83525ca
AS
7600 if (!is_const) {
7601 verbose(env,
7602 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7603 regno);
7604 return -EINVAL;
7605 }
4e814da0
KKD
7606 if (reg->type == PTR_TO_MAP_VALUE) {
7607 map = reg->map_ptr;
7608 if (!map->btf) {
7609 verbose(env,
7610 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7611 map->name);
7612 return -EINVAL;
7613 }
7614 } else {
7615 btf = reg->btf;
d83525ca 7616 }
4e814da0
KKD
7617
7618 rec = reg_btf_record(reg);
7619 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7620 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7621 map ? map->name : "kptr");
d83525ca
AS
7622 return -EINVAL;
7623 }
4e814da0 7624 if (rec->spin_lock_off != val + reg->off) {
db559117 7625 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
4e814da0 7626 val + reg->off, rec->spin_lock_off);
d83525ca
AS
7627 return -EINVAL;
7628 }
7629 if (is_lock) {
d0d78c1d 7630 if (cur->active_lock.ptr) {
d83525ca
AS
7631 verbose(env,
7632 "Locking two bpf_spin_locks are not allowed\n");
7633 return -EINVAL;
7634 }
d0d78c1d
KKD
7635 if (map)
7636 cur->active_lock.ptr = map;
7637 else
7638 cur->active_lock.ptr = btf;
7639 cur->active_lock.id = reg->id;
d83525ca 7640 } else {
d0d78c1d
KKD
7641 void *ptr;
7642
7643 if (map)
7644 ptr = map;
7645 else
7646 ptr = btf;
7647
7648 if (!cur->active_lock.ptr) {
d83525ca
AS
7649 verbose(env, "bpf_spin_unlock without taking a lock\n");
7650 return -EINVAL;
7651 }
d0d78c1d
KKD
7652 if (cur->active_lock.ptr != ptr ||
7653 cur->active_lock.id != reg->id) {
d83525ca
AS
7654 verbose(env, "bpf_spin_unlock of different lock\n");
7655 return -EINVAL;
7656 }
534e86bc 7657
6a3cd331 7658 invalidate_non_owning_refs(env);
534e86bc 7659
6a3cd331
DM
7660 cur->active_lock.ptr = NULL;
7661 cur->active_lock.id = 0;
d83525ca
AS
7662 }
7663 return 0;
7664}
7665
b00628b1
AS
7666static int process_timer_func(struct bpf_verifier_env *env, int regno,
7667 struct bpf_call_arg_meta *meta)
7668{
7669 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7670 bool is_const = tnum_is_const(reg->var_off);
7671 struct bpf_map *map = reg->map_ptr;
7672 u64 val = reg->var_off.value;
7673
7674 if (!is_const) {
7675 verbose(env,
7676 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7677 regno);
7678 return -EINVAL;
7679 }
7680 if (!map->btf) {
7681 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7682 map->name);
7683 return -EINVAL;
7684 }
db559117
KKD
7685 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7686 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
68134668
AS
7687 return -EINVAL;
7688 }
db559117 7689 if (map->record->timer_off != val + reg->off) {
68134668 7690 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
db559117 7691 val + reg->off, map->record->timer_off);
b00628b1
AS
7692 return -EINVAL;
7693 }
7694 if (meta->map_ptr) {
7695 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7696 return -EFAULT;
7697 }
3e8ce298 7698 meta->map_uid = reg->map_uid;
b00628b1
AS
7699 meta->map_ptr = map;
7700 return 0;
7701}
7702
c0a5a21c
KKD
7703static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7704 struct bpf_call_arg_meta *meta)
7705{
7706 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
c0a5a21c 7707 struct bpf_map *map_ptr = reg->map_ptr;
aa3496ac 7708 struct btf_field *kptr_field;
c0a5a21c 7709 u32 kptr_off;
c0a5a21c
KKD
7710
7711 if (!tnum_is_const(reg->var_off)) {
7712 verbose(env,
7713 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7714 regno);
7715 return -EINVAL;
7716 }
7717 if (!map_ptr->btf) {
7718 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7719 map_ptr->name);
7720 return -EINVAL;
7721 }
aa3496ac
KKD
7722 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7723 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
c0a5a21c
KKD
7724 return -EINVAL;
7725 }
7726
7727 meta->map_ptr = map_ptr;
7728 kptr_off = reg->off + reg->var_off.value;
aa3496ac
KKD
7729 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7730 if (!kptr_field) {
c0a5a21c
KKD
7731 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7732 return -EACCES;
7733 }
36d8bdf7 7734 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
c0a5a21c
KKD
7735 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7736 return -EACCES;
7737 }
aa3496ac 7738 meta->kptr_field = kptr_field;
c0a5a21c
KKD
7739 return 0;
7740}
7741
27060531
KKD
7742/* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7743 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7744 *
7745 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7746 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7747 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7748 *
7749 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7750 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7751 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7752 * mutate the view of the dynptr and also possibly destroy it. In the latter
7753 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7754 * memory that dynptr points to.
7755 *
7756 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7757 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7758 * readonly dynptr view yet, hence only the first case is tracked and checked.
7759 *
7760 * This is consistent with how C applies the const modifier to a struct object,
7761 * where the pointer itself inside bpf_dynptr becomes const but not what it
7762 * points to.
7763 *
7764 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7765 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7766 */
1d18feb2 7767static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
361f129f 7768 enum bpf_arg_type arg_type, int clone_ref_obj_id)
6b75bd3d
KKD
7769{
7770 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1d18feb2 7771 int err;
6b75bd3d 7772
27060531
KKD
7773 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7774 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7775 */
7776 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7777 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7778 return -EFAULT;
7779 }
79168a66 7780
27060531
KKD
7781 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7782 * constructing a mutable bpf_dynptr object.
7783 *
7784 * Currently, this is only possible with PTR_TO_STACK
7785 * pointing to a region of at least 16 bytes which doesn't
7786 * contain an existing bpf_dynptr.
7787 *
7788 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7789 * mutated or destroyed. However, the memory it points to
7790 * may be mutated.
7791 *
7792 * None - Points to a initialized dynptr that can be mutated and
7793 * destroyed, including mutation of the memory it points
7794 * to.
6b75bd3d 7795 */
6b75bd3d 7796 if (arg_type & MEM_UNINIT) {
1d18feb2
JK
7797 int i;
7798
7e0dac28 7799 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6b75bd3d
KKD
7800 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7801 return -EINVAL;
7802 }
7803
1d18feb2
JK
7804 /* we write BPF_DW bits (8 bytes) at a time */
7805 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7806 err = check_mem_access(env, insn_idx, regno,
1f9a1ea8 7807 i, BPF_DW, BPF_WRITE, -1, false, false);
1d18feb2
JK
7808 if (err)
7809 return err;
6b75bd3d
KKD
7810 }
7811
361f129f 7812 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
27060531
KKD
7813 } else /* MEM_RDONLY and None case from above */ {
7814 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7815 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7816 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7817 return -EINVAL;
7818 }
7819
7e0dac28 7820 if (!is_dynptr_reg_valid_init(env, reg)) {
6b75bd3d
KKD
7821 verbose(env,
7822 "Expected an initialized dynptr as arg #%d\n",
7823 regno);
7824 return -EINVAL;
7825 }
7826
27060531
KKD
7827 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7828 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6b75bd3d
KKD
7829 verbose(env,
7830 "Expected a dynptr of type %s as arg #%d\n",
d54e0f6c 7831 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6b75bd3d
KKD
7832 return -EINVAL;
7833 }
d6fefa11
KKD
7834
7835 err = mark_dynptr_read(env, reg);
6b75bd3d 7836 }
1d18feb2 7837 return err;
6b75bd3d
KKD
7838}
7839
06accc87
AN
7840static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7841{
7842 struct bpf_func_state *state = func(env, reg);
7843
7844 return state->stack[spi].spilled_ptr.ref_obj_id;
7845}
7846
7847static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7848{
7849 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7850}
7851
7852static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7853{
7854 return meta->kfunc_flags & KF_ITER_NEW;
7855}
7856
7857static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7858{
7859 return meta->kfunc_flags & KF_ITER_NEXT;
7860}
7861
7862static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7863{
7864 return meta->kfunc_flags & KF_ITER_DESTROY;
7865}
7866
7867static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7868{
7869 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7870 * kfunc is iter state pointer
7871 */
7872 return arg == 0 && is_iter_kfunc(meta);
7873}
7874
7875static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7876 struct bpf_kfunc_call_arg_meta *meta)
7877{
7878 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7879 const struct btf_type *t;
7880 const struct btf_param *arg;
7881 int spi, err, i, nr_slots;
7882 u32 btf_id;
7883
7884 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7885 arg = &btf_params(meta->func_proto)[0];
7886 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7887 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7888 nr_slots = t->size / BPF_REG_SIZE;
7889
06accc87
AN
7890 if (is_iter_new_kfunc(meta)) {
7891 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7892 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7893 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7894 iter_type_str(meta->btf, btf_id), regno);
7895 return -EINVAL;
7896 }
7897
7898 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7899 err = check_mem_access(env, insn_idx, regno,
1f9a1ea8 7900 i, BPF_DW, BPF_WRITE, -1, false, false);
06accc87
AN
7901 if (err)
7902 return err;
7903 }
7904
dfab99df 7905 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
06accc87
AN
7906 if (err)
7907 return err;
7908 } else {
7909 /* iter_next() or iter_destroy() expect initialized iter state*/
dfab99df
CZ
7910 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7911 switch (err) {
7912 case 0:
7913 break;
7914 case -EINVAL:
06accc87
AN
7915 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7916 iter_type_str(meta->btf, btf_id), regno);
dfab99df
CZ
7917 return err;
7918 case -EPROTO:
7919 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7920 return err;
7921 default:
7922 return err;
06accc87
AN
7923 }
7924
b63cbc49
AN
7925 spi = iter_get_spi(env, reg, nr_slots);
7926 if (spi < 0)
7927 return spi;
7928
06accc87
AN
7929 err = mark_iter_read(env, reg, spi, nr_slots);
7930 if (err)
7931 return err;
7932
b63cbc49
AN
7933 /* remember meta->iter info for process_iter_next_call() */
7934 meta->iter.spi = spi;
7935 meta->iter.frameno = reg->frameno;
06accc87
AN
7936 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7937
7938 if (is_iter_destroy_kfunc(meta)) {
7939 err = unmark_stack_slots_iter(env, reg, nr_slots);
7940 if (err)
7941 return err;
7942 }
7943 }
7944
7945 return 0;
7946}
7947
2793a8b0
EZ
7948/* Look for a previous loop entry at insn_idx: nearest parent state
7949 * stopped at insn_idx with callsites matching those in cur->frame.
7950 */
7951static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7952 struct bpf_verifier_state *cur,
7953 int insn_idx)
7954{
7955 struct bpf_verifier_state_list *sl;
7956 struct bpf_verifier_state *st;
7957
7958 /* Explored states are pushed in stack order, most recent states come first */
7959 sl = *explored_state(env, insn_idx);
7960 for (; sl; sl = sl->next) {
7961 /* If st->branches != 0 state is a part of current DFS verification path,
7962 * hence cur & st for a loop.
7963 */
7964 st = &sl->state;
7965 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7966 st->dfs_depth < cur->dfs_depth)
7967 return st;
7968 }
7969
7970 return NULL;
7971}
7972
7973static void reset_idmap_scratch(struct bpf_verifier_env *env);
7974static bool regs_exact(const struct bpf_reg_state *rold,
7975 const struct bpf_reg_state *rcur,
7976 struct bpf_idmap *idmap);
7977
7978static void maybe_widen_reg(struct bpf_verifier_env *env,
7979 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7980 struct bpf_idmap *idmap)
7981{
7982 if (rold->type != SCALAR_VALUE)
7983 return;
7984 if (rold->type != rcur->type)
7985 return;
7986 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7987 return;
7988 __mark_reg_unknown(env, rcur);
7989}
7990
7991static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7992 struct bpf_verifier_state *old,
7993 struct bpf_verifier_state *cur)
7994{
7995 struct bpf_func_state *fold, *fcur;
7996 int i, fr;
7997
7998 reset_idmap_scratch(env);
7999 for (fr = old->curframe; fr >= 0; fr--) {
8000 fold = old->frame[fr];
8001 fcur = cur->frame[fr];
8002
8003 for (i = 0; i < MAX_BPF_REG; i++)
8004 maybe_widen_reg(env,
8005 &fold->regs[i],
8006 &fcur->regs[i],
8007 &env->idmap_scratch);
8008
8009 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8010 if (!is_spilled_reg(&fold->stack[i]) ||
8011 !is_spilled_reg(&fcur->stack[i]))
8012 continue;
8013
8014 maybe_widen_reg(env,
8015 &fold->stack[i].spilled_ptr,
8016 &fcur->stack[i].spilled_ptr,
8017 &env->idmap_scratch);
8018 }
8019 }
8020 return 0;
8021}
8022
06accc87
AN
8023/* process_iter_next_call() is called when verifier gets to iterator's next
8024 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8025 * to it as just "iter_next()" in comments below.
8026 *
8027 * BPF verifier relies on a crucial contract for any iter_next()
8028 * implementation: it should *eventually* return NULL, and once that happens
8029 * it should keep returning NULL. That is, once iterator exhausts elements to
8030 * iterate, it should never reset or spuriously return new elements.
8031 *
8032 * With the assumption of such contract, process_iter_next_call() simulates
8033 * a fork in the verifier state to validate loop logic correctness and safety
8034 * without having to simulate infinite amount of iterations.
8035 *
8036 * In current state, we first assume that iter_next() returned NULL and
8037 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8038 * conditions we should not form an infinite loop and should eventually reach
8039 * exit.
8040 *
8041 * Besides that, we also fork current state and enqueue it for later
8042 * verification. In a forked state we keep iterator state as ACTIVE
8043 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8044 * also bump iteration depth to prevent erroneous infinite loop detection
8045 * later on (see iter_active_depths_differ() comment for details). In this
8046 * state we assume that we'll eventually loop back to another iter_next()
8047 * calls (it could be in exactly same location or in some other instruction,
8048 * it doesn't matter, we don't make any unnecessary assumptions about this,
8049 * everything revolves around iterator state in a stack slot, not which
8050 * instruction is calling iter_next()). When that happens, we either will come
8051 * to iter_next() with equivalent state and can conclude that next iteration
8052 * will proceed in exactly the same way as we just verified, so it's safe to
8053 * assume that loop converges. If not, we'll go on another iteration
8054 * simulation with a different input state, until all possible starting states
8055 * are validated or we reach maximum number of instructions limit.
8056 *
8057 * This way, we will either exhaustively discover all possible input states
8058 * that iterator loop can start with and eventually will converge, or we'll
8059 * effectively regress into bounded loop simulation logic and either reach
8060 * maximum number of instructions if loop is not provably convergent, or there
8061 * is some statically known limit on number of iterations (e.g., if there is
8062 * an explicit `if n > 100 then break;` statement somewhere in the loop).
8063 *
2793a8b0
EZ
8064 * Iteration convergence logic in is_state_visited() relies on exact
8065 * states comparison, which ignores read and precision marks.
8066 * This is necessary because read and precision marks are not finalized
8067 * while in the loop. Exact comparison might preclude convergence for
8068 * simple programs like below:
8069 *
8070 * i = 0;
8071 * while(iter_next(&it))
8072 * i++;
8073 *
8074 * At each iteration step i++ would produce a new distinct state and
8075 * eventually instruction processing limit would be reached.
8076 *
8077 * To avoid such behavior speculatively forget (widen) range for
8078 * imprecise scalar registers, if those registers were not precise at the
8079 * end of the previous iteration and do not match exactly.
8080 *
8081 * This is a conservative heuristic that allows to verify wide range of programs,
8082 * however it precludes verification of programs that conjure an
8083 * imprecise value on the first loop iteration and use it as precise on a second.
8084 * For example, the following safe program would fail to verify:
8085 *
8086 * struct bpf_num_iter it;
8087 * int arr[10];
8088 * int i = 0, a = 0;
8089 * bpf_iter_num_new(&it, 0, 10);
8090 * while (bpf_iter_num_next(&it)) {
8091 * if (a == 0) {
8092 * a = 1;
8093 * i = 7; // Because i changed verifier would forget
8094 * // it's range on second loop entry.
8095 * } else {
8096 * arr[i] = 42; // This would fail to verify.
8097 * }
8098 * }
8099 * bpf_iter_num_destroy(&it);
06accc87
AN
8100 */
8101static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8102 struct bpf_kfunc_call_arg_meta *meta)
8103{
2793a8b0 8104 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
06accc87
AN
8105 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8106 struct bpf_reg_state *cur_iter, *queued_iter;
8107 int iter_frameno = meta->iter.frameno;
8108 int iter_spi = meta->iter.spi;
8109
8110 BTF_TYPE_EMIT(struct bpf_iter);
8111
8112 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8113
8114 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8115 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8116 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8117 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8118 return -EFAULT;
8119 }
8120
8121 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
2793a8b0
EZ
8122 /* Because iter_next() call is a checkpoint is_state_visitied()
8123 * should guarantee parent state with same call sites and insn_idx.
8124 */
8125 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8126 !same_callsites(cur_st->parent, cur_st)) {
8127 verbose(env, "bug: bad parent state for iter next call");
8128 return -EFAULT;
8129 }
8130 /* Note cur_st->parent in the call below, it is necessary to skip
8131 * checkpoint created for cur_st by is_state_visited()
8132 * right at this instruction.
8133 */
8134 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
06accc87
AN
8135 /* branch out active iter state */
8136 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8137 if (!queued_st)
8138 return -ENOMEM;
8139
8140 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8141 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8142 queued_iter->iter.depth++;
2793a8b0
EZ
8143 if (prev_st)
8144 widen_imprecise_scalars(env, prev_st, queued_st);
06accc87
AN
8145
8146 queued_fr = queued_st->frame[queued_st->curframe];
8147 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8148 }
8149
8150 /* switch to DRAINED state, but keep the depth unchanged */
8151 /* mark current iter state as drained and assume returned NULL */
8152 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8153 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
8154
8155 return 0;
8156}
8157
90133415
DB
8158static bool arg_type_is_mem_size(enum bpf_arg_type type)
8159{
8160 return type == ARG_CONST_SIZE ||
8161 type == ARG_CONST_SIZE_OR_ZERO;
8162}
8163
8f14852e
KKD
8164static bool arg_type_is_release(enum bpf_arg_type type)
8165{
8166 return type & OBJ_RELEASE;
8167}
8168
97e03f52
JK
8169static bool arg_type_is_dynptr(enum bpf_arg_type type)
8170{
8171 return base_type(type) == ARG_PTR_TO_DYNPTR;
8172}
8173
57c3bb72
AI
8174static int int_ptr_type_to_size(enum bpf_arg_type type)
8175{
8176 if (type == ARG_PTR_TO_INT)
8177 return sizeof(u32);
8178 else if (type == ARG_PTR_TO_LONG)
8179 return sizeof(u64);
8180
8181 return -EINVAL;
8182}
8183
912f442c
LB
8184static int resolve_map_arg_type(struct bpf_verifier_env *env,
8185 const struct bpf_call_arg_meta *meta,
8186 enum bpf_arg_type *arg_type)
8187{
8188 if (!meta->map_ptr) {
8189 /* kernel subsystem misconfigured verifier */
8190 verbose(env, "invalid map_ptr to access map->type\n");
8191 return -EACCES;
8192 }
8193
8194 switch (meta->map_ptr->map_type) {
8195 case BPF_MAP_TYPE_SOCKMAP:
8196 case BPF_MAP_TYPE_SOCKHASH:
8197 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 8198 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
8199 } else {
8200 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8201 return -EINVAL;
8202 }
8203 break;
9330986c
JK
8204 case BPF_MAP_TYPE_BLOOM_FILTER:
8205 if (meta->func_id == BPF_FUNC_map_peek_elem)
8206 *arg_type = ARG_PTR_TO_MAP_VALUE;
8207 break;
912f442c
LB
8208 default:
8209 break;
8210 }
8211 return 0;
8212}
8213
f79e7ea5
LB
8214struct bpf_reg_types {
8215 const enum bpf_reg_type types[10];
1df8f55a 8216 u32 *btf_id;
f79e7ea5
LB
8217};
8218
f79e7ea5
LB
8219static const struct bpf_reg_types sock_types = {
8220 .types = {
8221 PTR_TO_SOCK_COMMON,
8222 PTR_TO_SOCKET,
8223 PTR_TO_TCP_SOCK,
8224 PTR_TO_XDP_SOCK,
8225 },
8226};
8227
49a2a4d4 8228#ifdef CONFIG_NET
1df8f55a
MKL
8229static const struct bpf_reg_types btf_id_sock_common_types = {
8230 .types = {
8231 PTR_TO_SOCK_COMMON,
8232 PTR_TO_SOCKET,
8233 PTR_TO_TCP_SOCK,
8234 PTR_TO_XDP_SOCK,
8235 PTR_TO_BTF_ID,
3f00c523 8236 PTR_TO_BTF_ID | PTR_TRUSTED,
1df8f55a
MKL
8237 },
8238 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8239};
49a2a4d4 8240#endif
1df8f55a 8241
f79e7ea5
LB
8242static const struct bpf_reg_types mem_types = {
8243 .types = {
8244 PTR_TO_STACK,
8245 PTR_TO_PACKET,
8246 PTR_TO_PACKET_META,
69c087ba 8247 PTR_TO_MAP_KEY,
f79e7ea5
LB
8248 PTR_TO_MAP_VALUE,
8249 PTR_TO_MEM,
894f2a8b 8250 PTR_TO_MEM | MEM_RINGBUF,
20b2aff4 8251 PTR_TO_BUF,
3e30be42 8252 PTR_TO_BTF_ID | PTR_TRUSTED,
f79e7ea5
LB
8253 },
8254};
8255
8256static const struct bpf_reg_types int_ptr_types = {
8257 .types = {
8258 PTR_TO_STACK,
8259 PTR_TO_PACKET,
8260 PTR_TO_PACKET_META,
69c087ba 8261 PTR_TO_MAP_KEY,
f79e7ea5
LB
8262 PTR_TO_MAP_VALUE,
8263 },
8264};
8265
4e814da0
KKD
8266static const struct bpf_reg_types spin_lock_types = {
8267 .types = {
8268 PTR_TO_MAP_VALUE,
8269 PTR_TO_BTF_ID | MEM_ALLOC,
8270 }
8271};
8272
f79e7ea5
LB
8273static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8274static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8275static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
894f2a8b 8276static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
f79e7ea5 8277static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
3f00c523
DV
8278static const struct bpf_reg_types btf_ptr_types = {
8279 .types = {
8280 PTR_TO_BTF_ID,
8281 PTR_TO_BTF_ID | PTR_TRUSTED,
fca1aa75 8282 PTR_TO_BTF_ID | MEM_RCU,
3f00c523
DV
8283 },
8284};
8285static const struct bpf_reg_types percpu_btf_ptr_types = {
8286 .types = {
8287 PTR_TO_BTF_ID | MEM_PERCPU,
01cc55af 8288 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
3f00c523
DV
8289 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8290 }
8291};
69c087ba
YS
8292static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8293static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 8294static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
b00628b1 8295static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
c0a5a21c 8296static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
20571567
DV
8297static const struct bpf_reg_types dynptr_types = {
8298 .types = {
8299 PTR_TO_STACK,
27060531 8300 CONST_PTR_TO_DYNPTR,
20571567
DV
8301 }
8302};
f79e7ea5 8303
0789e13b 8304static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
d1673304
DM
8305 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8306 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
f79e7ea5
LB
8307 [ARG_CONST_SIZE] = &scalar_types,
8308 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8309 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8310 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8311 [ARG_PTR_TO_CTX] = &context_types,
f79e7ea5 8312 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 8313#ifdef CONFIG_NET
1df8f55a 8314 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 8315#endif
f79e7ea5 8316 [ARG_PTR_TO_SOCKET] = &fullsock_types,
f79e7ea5
LB
8317 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8318 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8319 [ARG_PTR_TO_MEM] = &mem_types,
894f2a8b 8320 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
f79e7ea5
LB
8321 [ARG_PTR_TO_INT] = &int_ptr_types,
8322 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 8323 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba 8324 [ARG_PTR_TO_FUNC] = &func_ptr_types,
48946bd6 8325 [ARG_PTR_TO_STACK] = &stack_ptr_types,
fff13c4b 8326 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
b00628b1 8327 [ARG_PTR_TO_TIMER] = &timer_types,
c0a5a21c 8328 [ARG_PTR_TO_KPTR] = &kptr_types,
20571567 8329 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
f79e7ea5
LB
8330};
8331
8332static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2 8333 enum bpf_arg_type arg_type,
c0a5a21c
KKD
8334 const u32 *arg_btf_id,
8335 struct bpf_call_arg_meta *meta)
f79e7ea5
LB
8336{
8337 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8338 enum bpf_reg_type expected, type = reg->type;
a968d5e2 8339 const struct bpf_reg_types *compatible;
f79e7ea5
LB
8340 int i, j;
8341
48946bd6 8342 compatible = compatible_reg_types[base_type(arg_type)];
a968d5e2
MKL
8343 if (!compatible) {
8344 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8345 return -EFAULT;
8346 }
8347
216e3cd2
HL
8348 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8349 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8350 *
8351 * Same for MAYBE_NULL:
8352 *
8353 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8354 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8355 *
2012c867
DR
8356 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8357 *
216e3cd2
HL
8358 * Therefore we fold these flags depending on the arg_type before comparison.
8359 */
8360 if (arg_type & MEM_RDONLY)
8361 type &= ~MEM_RDONLY;
8362 if (arg_type & PTR_MAYBE_NULL)
8363 type &= ~PTR_MAYBE_NULL;
2012c867
DR
8364 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8365 type &= ~DYNPTR_TYPE_FLAG_MASK;
216e3cd2 8366
36d8bdf7 8367 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
738c96d5 8368 type &= ~MEM_ALLOC;
36d8bdf7
YS
8369 type &= ~MEM_PERCPU;
8370 }
738c96d5 8371
f79e7ea5
LB
8372 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8373 expected = compatible->types[i];
8374 if (expected == NOT_INIT)
8375 break;
8376
8377 if (type == expected)
a968d5e2 8378 goto found;
f79e7ea5
LB
8379 }
8380
216e3cd2 8381 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
f79e7ea5 8382 for (j = 0; j + 1 < i; j++)
c25b2ae1
HL
8383 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8384 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
f79e7ea5 8385 return -EACCES;
a968d5e2
MKL
8386
8387found:
da03e43a
KKD
8388 if (base_type(reg->type) != PTR_TO_BTF_ID)
8389 return 0;
8390
3e30be42
AS
8391 if (compatible == &mem_types) {
8392 if (!(arg_type & MEM_RDONLY)) {
8393 verbose(env,
8394 "%s() may write into memory pointed by R%d type=%s\n",
8395 func_id_name(meta->func_id),
8396 regno, reg_type_str(env, reg->type));
8397 return -EACCES;
8398 }
8399 return 0;
8400 }
8401
da03e43a
KKD
8402 switch ((int)reg->type) {
8403 case PTR_TO_BTF_ID:
8404 case PTR_TO_BTF_ID | PTR_TRUSTED:
8405 case PTR_TO_BTF_ID | MEM_RCU:
add68b84
AS
8406 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8407 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
da03e43a 8408 {
2ab3b380
KKD
8409 /* For bpf_sk_release, it needs to match against first member
8410 * 'struct sock_common', hence make an exception for it. This
8411 * allows bpf_sk_release to work for multiple socket types.
8412 */
8413 bool strict_type_match = arg_type_is_release(arg_type) &&
8414 meta->func_id != BPF_FUNC_sk_release;
8415
add68b84
AS
8416 if (type_may_be_null(reg->type) &&
8417 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8418 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8419 return -EACCES;
8420 }
8421
1df8f55a
MKL
8422 if (!arg_btf_id) {
8423 if (!compatible->btf_id) {
8424 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8425 return -EFAULT;
8426 }
8427 arg_btf_id = compatible->btf_id;
8428 }
8429
c0a5a21c 8430 if (meta->func_id == BPF_FUNC_kptr_xchg) {
aa3496ac 8431 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
c0a5a21c 8432 return -EACCES;
47e34cb7
DM
8433 } else {
8434 if (arg_btf_id == BPF_PTR_POISON) {
8435 verbose(env, "verifier internal error:");
8436 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8437 regno);
8438 return -EACCES;
8439 }
8440
8441 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8442 btf_vmlinux, *arg_btf_id,
8443 strict_type_match)) {
8444 verbose(env, "R%d is of type %s but %s is expected\n",
b32a5dae
DM
8445 regno, btf_type_name(reg->btf, reg->btf_id),
8446 btf_type_name(btf_vmlinux, *arg_btf_id));
47e34cb7
DM
8447 return -EACCES;
8448 }
a968d5e2 8449 }
da03e43a
KKD
8450 break;
8451 }
8452 case PTR_TO_BTF_ID | MEM_ALLOC:
36d8bdf7 8453 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
738c96d5
DM
8454 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8455 meta->func_id != BPF_FUNC_kptr_xchg) {
4e814da0
KKD
8456 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8457 return -EFAULT;
8458 }
ab6c637a
YS
8459 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8460 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8461 return -EACCES;
8462 }
da03e43a
KKD
8463 break;
8464 case PTR_TO_BTF_ID | MEM_PERCPU:
01cc55af 8465 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
da03e43a
KKD
8466 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8467 /* Handled by helper specific checks */
8468 break;
8469 default:
8470 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8471 return -EFAULT;
a968d5e2 8472 }
a968d5e2 8473 return 0;
f79e7ea5
LB
8474}
8475
6a3cd331
DM
8476static struct btf_field *
8477reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8478{
8479 struct btf_field *field;
8480 struct btf_record *rec;
8481
8482 rec = reg_btf_record(reg);
8483 if (!rec)
8484 return NULL;
8485
8486 field = btf_record_find(rec, off, fields);
8487 if (!field)
8488 return NULL;
8489
8490 return field;
8491}
8492
25b35dd2
KKD
8493int check_func_arg_reg_off(struct bpf_verifier_env *env,
8494 const struct bpf_reg_state *reg, int regno,
8f14852e 8495 enum bpf_arg_type arg_type)
25b35dd2 8496{
184c9bdb 8497 u32 type = reg->type;
25b35dd2 8498
184c9bdb
KKD
8499 /* When referenced register is passed to release function, its fixed
8500 * offset must be 0.
8501 *
8502 * We will check arg_type_is_release reg has ref_obj_id when storing
8503 * meta->release_regno.
8504 */
8505 if (arg_type_is_release(arg_type)) {
8506 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8507 * may not directly point to the object being released, but to
8508 * dynptr pointing to such object, which might be at some offset
8509 * on the stack. In that case, we simply to fallback to the
8510 * default handling.
8511 */
8512 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8513 return 0;
6a3cd331 8514
184c9bdb
KKD
8515 /* Doing check_ptr_off_reg check for the offset will catch this
8516 * because fixed_off_ok is false, but checking here allows us
8517 * to give the user a better error message.
8518 */
8519 if (reg->off) {
8520 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8521 regno);
8522 return -EINVAL;
8523 }
8524 return __check_ptr_off_reg(env, reg, regno, false);
8525 }
8526
8527 switch (type) {
8528 /* Pointer types where both fixed and variable offset is explicitly allowed: */
97e03f52 8529 case PTR_TO_STACK:
25b35dd2
KKD
8530 case PTR_TO_PACKET:
8531 case PTR_TO_PACKET_META:
8532 case PTR_TO_MAP_KEY:
8533 case PTR_TO_MAP_VALUE:
8534 case PTR_TO_MEM:
8535 case PTR_TO_MEM | MEM_RDONLY:
894f2a8b 8536 case PTR_TO_MEM | MEM_RINGBUF:
25b35dd2
KKD
8537 case PTR_TO_BUF:
8538 case PTR_TO_BUF | MEM_RDONLY:
97e03f52 8539 case SCALAR_VALUE:
184c9bdb 8540 return 0;
25b35dd2
KKD
8541 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8542 * fixed offset.
8543 */
8544 case PTR_TO_BTF_ID:
282de143 8545 case PTR_TO_BTF_ID | MEM_ALLOC:
3f00c523 8546 case PTR_TO_BTF_ID | PTR_TRUSTED:
fca1aa75 8547 case PTR_TO_BTF_ID | MEM_RCU:
6a3cd331 8548 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
0816b8c6 8549 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
24d5bb80 8550 /* When referenced PTR_TO_BTF_ID is passed to release function,
184c9bdb
KKD
8551 * its fixed offset must be 0. In the other cases, fixed offset
8552 * can be non-zero. This was already checked above. So pass
8553 * fixed_off_ok as true to allow fixed offset for all other
8554 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8555 * still need to do checks instead of returning.
24d5bb80 8556 */
184c9bdb 8557 return __check_ptr_off_reg(env, reg, regno, true);
25b35dd2 8558 default:
184c9bdb 8559 return __check_ptr_off_reg(env, reg, regno, false);
25b35dd2 8560 }
25b35dd2
KKD
8561}
8562
485ec51e
JK
8563static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8564 const struct bpf_func_proto *fn,
8565 struct bpf_reg_state *regs)
8566{
8567 struct bpf_reg_state *state = NULL;
8568 int i;
8569
8570 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8571 if (arg_type_is_dynptr(fn->arg_type[i])) {
8572 if (state) {
8573 verbose(env, "verifier internal error: multiple dynptr args\n");
8574 return NULL;
8575 }
8576 state = &regs[BPF_REG_1 + i];
8577 }
8578
8579 if (!state)
8580 verbose(env, "verifier internal error: no dynptr arg found\n");
8581
8582 return state;
8583}
8584
f8064ab9 8585static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
34d4ef57
JK
8586{
8587 struct bpf_func_state *state = func(env, reg);
27060531 8588 int spi;
34d4ef57 8589
27060531 8590 if (reg->type == CONST_PTR_TO_DYNPTR)
f8064ab9
KKD
8591 return reg->id;
8592 spi = dynptr_get_spi(env, reg);
8593 if (spi < 0)
8594 return spi;
8595 return state->stack[spi].spilled_ptr.id;
8596}
8597
79168a66 8598static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
34d4ef57
JK
8599{
8600 struct bpf_func_state *state = func(env, reg);
27060531 8601 int spi;
27060531 8602
27060531
KKD
8603 if (reg->type == CONST_PTR_TO_DYNPTR)
8604 return reg->ref_obj_id;
79168a66
KKD
8605 spi = dynptr_get_spi(env, reg);
8606 if (spi < 0)
8607 return spi;
27060531 8608 return state->stack[spi].spilled_ptr.ref_obj_id;
34d4ef57
JK
8609}
8610
b5964b96
JK
8611static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8612 struct bpf_reg_state *reg)
8613{
8614 struct bpf_func_state *state = func(env, reg);
8615 int spi;
8616
8617 if (reg->type == CONST_PTR_TO_DYNPTR)
8618 return reg->dynptr.type;
8619
8620 spi = __get_spi(reg->off);
8621 if (spi < 0) {
8622 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8623 return BPF_DYNPTR_TYPE_INVALID;
8624 }
8625
8626 return state->stack[spi].spilled_ptr.dynptr.type;
8627}
8628
af7ec138
YS
8629static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8630 struct bpf_call_arg_meta *meta,
1d18feb2
JK
8631 const struct bpf_func_proto *fn,
8632 int insn_idx)
17a52670 8633{
af7ec138 8634 u32 regno = BPF_REG_1 + arg;
638f5b90 8635 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 8636 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 8637 enum bpf_reg_type type = reg->type;
508362ac 8638 u32 *arg_btf_id = NULL;
17a52670
AS
8639 int err = 0;
8640
80f1d68c 8641 if (arg_type == ARG_DONTCARE)
17a52670
AS
8642 return 0;
8643
dc503a8a
EC
8644 err = check_reg_arg(env, regno, SRC_OP);
8645 if (err)
8646 return err;
17a52670 8647
1be7f75d
AS
8648 if (arg_type == ARG_ANYTHING) {
8649 if (is_pointer_value(env, regno)) {
61bd5218
JK
8650 verbose(env, "R%d leaks addr into helper function\n",
8651 regno);
1be7f75d
AS
8652 return -EACCES;
8653 }
80f1d68c 8654 return 0;
1be7f75d 8655 }
80f1d68c 8656
de8f3a83 8657 if (type_is_pkt_pointer(type) &&
3a0af8fd 8658 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 8659 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
8660 return -EACCES;
8661 }
8662
16d1e00c 8663 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
912f442c
LB
8664 err = resolve_map_arg_type(env, meta, &arg_type);
8665 if (err)
8666 return err;
8667 }
8668
48946bd6 8669 if (register_is_null(reg) && type_may_be_null(arg_type))
fd1b0d60
LB
8670 /* A NULL register has a SCALAR_VALUE type, so skip
8671 * type checking.
8672 */
8673 goto skip_type_check;
8674
508362ac 8675 /* arg_btf_id and arg_size are in a union. */
4e814da0
KKD
8676 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8677 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
508362ac
MM
8678 arg_btf_id = fn->arg_btf_id[arg];
8679
8680 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
f79e7ea5
LB
8681 if (err)
8682 return err;
8683
8f14852e 8684 err = check_func_arg_reg_off(env, reg, regno, arg_type);
25b35dd2
KKD
8685 if (err)
8686 return err;
d7b9454a 8687
fd1b0d60 8688skip_type_check:
8f14852e 8689 if (arg_type_is_release(arg_type)) {
bc34dee6
JK
8690 if (arg_type_is_dynptr(arg_type)) {
8691 struct bpf_func_state *state = func(env, reg);
27060531 8692 int spi;
bc34dee6 8693
27060531
KKD
8694 /* Only dynptr created on stack can be released, thus
8695 * the get_spi and stack state checks for spilled_ptr
8696 * should only be done before process_dynptr_func for
8697 * PTR_TO_STACK.
8698 */
8699 if (reg->type == PTR_TO_STACK) {
79168a66 8700 spi = dynptr_get_spi(env, reg);
f5b625e5 8701 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
27060531
KKD
8702 verbose(env, "arg %d is an unacquired reference\n", regno);
8703 return -EINVAL;
8704 }
8705 } else {
8706 verbose(env, "cannot release unowned const bpf_dynptr\n");
bc34dee6
JK
8707 return -EINVAL;
8708 }
8709 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8f14852e
KKD
8710 verbose(env, "R%d must be referenced when passed to release function\n",
8711 regno);
8712 return -EINVAL;
8713 }
8714 if (meta->release_regno) {
8715 verbose(env, "verifier internal error: more than one release argument\n");
8716 return -EFAULT;
8717 }
8718 meta->release_regno = regno;
8719 }
8720
02f7c958 8721 if (reg->ref_obj_id) {
457f4436
AN
8722 if (meta->ref_obj_id) {
8723 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8724 regno, reg->ref_obj_id,
8725 meta->ref_obj_id);
8726 return -EFAULT;
8727 }
8728 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
8729 }
8730
8ab4cdcf
JK
8731 switch (base_type(arg_type)) {
8732 case ARG_CONST_MAP_PTR:
17a52670 8733 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3e8ce298
AS
8734 if (meta->map_ptr) {
8735 /* Use map_uid (which is unique id of inner map) to reject:
8736 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8737 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8738 * if (inner_map1 && inner_map2) {
8739 * timer = bpf_map_lookup_elem(inner_map1);
8740 * if (timer)
8741 * // mismatch would have been allowed
8742 * bpf_timer_init(timer, inner_map2);
8743 * }
8744 *
8745 * Comparing map_ptr is enough to distinguish normal and outer maps.
8746 */
8747 if (meta->map_ptr != reg->map_ptr ||
8748 meta->map_uid != reg->map_uid) {
8749 verbose(env,
8750 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8751 meta->map_uid, reg->map_uid);
8752 return -EINVAL;
8753 }
b00628b1 8754 }
33ff9823 8755 meta->map_ptr = reg->map_ptr;
3e8ce298 8756 meta->map_uid = reg->map_uid;
8ab4cdcf
JK
8757 break;
8758 case ARG_PTR_TO_MAP_KEY:
17a52670
AS
8759 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8760 * check that [key, key + map->key_size) are within
8761 * stack limits and initialized
8762 */
33ff9823 8763 if (!meta->map_ptr) {
17a52670
AS
8764 /* in function declaration map_ptr must come before
8765 * map_key, so that it's verified and known before
8766 * we have to check map_key here. Otherwise it means
8767 * that kernel subsystem misconfigured verifier
8768 */
61bd5218 8769 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
8770 return -EACCES;
8771 }
d71962f3
PC
8772 err = check_helper_mem_access(env, regno,
8773 meta->map_ptr->key_size, false,
8774 NULL);
8ab4cdcf
JK
8775 break;
8776 case ARG_PTR_TO_MAP_VALUE:
48946bd6
HL
8777 if (type_may_be_null(arg_type) && register_is_null(reg))
8778 return 0;
8779
17a52670
AS
8780 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8781 * check [value, value + map->value_size) validity
8782 */
33ff9823 8783 if (!meta->map_ptr) {
17a52670 8784 /* kernel subsystem misconfigured verifier */
61bd5218 8785 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
8786 return -EACCES;
8787 }
16d1e00c 8788 meta->raw_mode = arg_type & MEM_UNINIT;
d71962f3
PC
8789 err = check_helper_mem_access(env, regno,
8790 meta->map_ptr->value_size, false,
2ea864c5 8791 meta);
8ab4cdcf
JK
8792 break;
8793 case ARG_PTR_TO_PERCPU_BTF_ID:
eaa6bcb7
HL
8794 if (!reg->btf_id) {
8795 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8796 return -EACCES;
8797 }
22dc4a0f 8798 meta->ret_btf = reg->btf;
eaa6bcb7 8799 meta->ret_btf_id = reg->btf_id;
8ab4cdcf
JK
8800 break;
8801 case ARG_PTR_TO_SPIN_LOCK:
5d92ddc3
DM
8802 if (in_rbtree_lock_required_cb(env)) {
8803 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8804 return -EACCES;
8805 }
c18f0b6a 8806 if (meta->func_id == BPF_FUNC_spin_lock) {
ac50fe51
KKD
8807 err = process_spin_lock(env, regno, true);
8808 if (err)
8809 return err;
c18f0b6a 8810 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
ac50fe51
KKD
8811 err = process_spin_lock(env, regno, false);
8812 if (err)
8813 return err;
c18f0b6a
LB
8814 } else {
8815 verbose(env, "verifier internal error\n");
8816 return -EFAULT;
8817 }
8ab4cdcf
JK
8818 break;
8819 case ARG_PTR_TO_TIMER:
ac50fe51
KKD
8820 err = process_timer_func(env, regno, meta);
8821 if (err)
8822 return err;
8ab4cdcf
JK
8823 break;
8824 case ARG_PTR_TO_FUNC:
69c087ba 8825 meta->subprogno = reg->subprogno;
8ab4cdcf
JK
8826 break;
8827 case ARG_PTR_TO_MEM:
a2bbe7cc
LB
8828 /* The access to this pointer is only checked when we hit the
8829 * next is_mem_size argument below.
8830 */
16d1e00c 8831 meta->raw_mode = arg_type & MEM_UNINIT;
508362ac
MM
8832 if (arg_type & MEM_FIXED_SIZE) {
8833 err = check_helper_mem_access(env, regno,
8834 fn->arg_size[arg], false,
8835 meta);
8836 }
8ab4cdcf
JK
8837 break;
8838 case ARG_CONST_SIZE:
8839 err = check_mem_size_reg(env, reg, regno, false, meta);
8840 break;
8841 case ARG_CONST_SIZE_OR_ZERO:
8842 err = check_mem_size_reg(env, reg, regno, true, meta);
8843 break;
8844 case ARG_PTR_TO_DYNPTR:
361f129f 8845 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
ac50fe51
KKD
8846 if (err)
8847 return err;
8ab4cdcf
JK
8848 break;
8849 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
457f4436 8850 if (!tnum_is_const(reg->var_off)) {
28a8add6 8851 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
8852 regno);
8853 return -EACCES;
8854 }
8855 meta->mem_size = reg->var_off.value;
2fc31465
KKD
8856 err = mark_chain_precision(env, regno);
8857 if (err)
8858 return err;
8ab4cdcf
JK
8859 break;
8860 case ARG_PTR_TO_INT:
8861 case ARG_PTR_TO_LONG:
8862 {
57c3bb72
AI
8863 int size = int_ptr_type_to_size(arg_type);
8864
8865 err = check_helper_mem_access(env, regno, size, false, meta);
8866 if (err)
8867 return err;
8868 err = check_ptr_alignment(env, reg, 0, size, true);
8ab4cdcf
JK
8869 break;
8870 }
8871 case ARG_PTR_TO_CONST_STR:
8872 {
fff13c4b
FR
8873 struct bpf_map *map = reg->map_ptr;
8874 int map_off;
8875 u64 map_addr;
8876 char *str_ptr;
8877
a8fad73e 8878 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
8879 verbose(env, "R%d does not point to a readonly map'\n", regno);
8880 return -EACCES;
8881 }
8882
8883 if (!tnum_is_const(reg->var_off)) {
8884 verbose(env, "R%d is not a constant address'\n", regno);
8885 return -EACCES;
8886 }
8887
8888 if (!map->ops->map_direct_value_addr) {
8889 verbose(env, "no direct value access support for this map type\n");
8890 return -EACCES;
8891 }
8892
8893 err = check_map_access(env, regno, reg->off,
61df10c7
KKD
8894 map->value_size - reg->off, false,
8895 ACCESS_HELPER);
fff13c4b
FR
8896 if (err)
8897 return err;
8898
8899 map_off = reg->off + reg->var_off.value;
8900 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8901 if (err) {
8902 verbose(env, "direct value access on string failed\n");
8903 return err;
8904 }
8905
8906 str_ptr = (char *)(long)(map_addr);
8907 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8908 verbose(env, "string is not zero-terminated\n");
8909 return -EINVAL;
8910 }
8ab4cdcf
JK
8911 break;
8912 }
8913 case ARG_PTR_TO_KPTR:
ac50fe51
KKD
8914 err = process_kptr_func(env, regno, meta);
8915 if (err)
8916 return err;
8ab4cdcf 8917 break;
17a52670
AS
8918 }
8919
8920 return err;
8921}
8922
0126240f
LB
8923static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8924{
8925 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 8926 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
8927
8928 if (func_id != BPF_FUNC_map_update_elem)
8929 return false;
8930
8931 /* It's not possible to get access to a locked struct sock in these
8932 * contexts, so updating is safe.
8933 */
8934 switch (type) {
8935 case BPF_PROG_TYPE_TRACING:
8936 if (eatype == BPF_TRACE_ITER)
8937 return true;
8938 break;
8939 case BPF_PROG_TYPE_SOCKET_FILTER:
8940 case BPF_PROG_TYPE_SCHED_CLS:
8941 case BPF_PROG_TYPE_SCHED_ACT:
8942 case BPF_PROG_TYPE_XDP:
8943 case BPF_PROG_TYPE_SK_REUSEPORT:
8944 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8945 case BPF_PROG_TYPE_SK_LOOKUP:
8946 return true;
8947 default:
8948 break;
8949 }
8950
8951 verbose(env, "cannot update sockmap in this context\n");
8952 return false;
8953}
8954
e411901c
MF
8955static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8956{
95acd881
TA
8957 return env->prog->jit_requested &&
8958 bpf_jit_supports_subprog_tailcalls();
e411901c
MF
8959}
8960
61bd5218
JK
8961static int check_map_func_compatibility(struct bpf_verifier_env *env,
8962 struct bpf_map *map, int func_id)
35578d79 8963{
35578d79
KX
8964 if (!map)
8965 return 0;
8966
6aff67c8
AS
8967 /* We need a two way check, first is from map perspective ... */
8968 switch (map->map_type) {
8969 case BPF_MAP_TYPE_PROG_ARRAY:
8970 if (func_id != BPF_FUNC_tail_call)
8971 goto error;
8972 break;
8973 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8974 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 8975 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 8976 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
8977 func_id != BPF_FUNC_perf_event_read_value &&
8978 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
8979 goto error;
8980 break;
457f4436
AN
8981 case BPF_MAP_TYPE_RINGBUF:
8982 if (func_id != BPF_FUNC_ringbuf_output &&
8983 func_id != BPF_FUNC_ringbuf_reserve &&
bc34dee6
JK
8984 func_id != BPF_FUNC_ringbuf_query &&
8985 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8986 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8987 func_id != BPF_FUNC_ringbuf_discard_dynptr)
457f4436
AN
8988 goto error;
8989 break;
583c1f42 8990 case BPF_MAP_TYPE_USER_RINGBUF:
20571567
DV
8991 if (func_id != BPF_FUNC_user_ringbuf_drain)
8992 goto error;
8993 break;
6aff67c8
AS
8994 case BPF_MAP_TYPE_STACK_TRACE:
8995 if (func_id != BPF_FUNC_get_stackid)
8996 goto error;
8997 break;
4ed8ec52 8998 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 8999 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 9000 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
9001 goto error;
9002 break;
cd339431 9003 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 9004 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
9005 if (func_id != BPF_FUNC_get_local_storage)
9006 goto error;
9007 break;
546ac1ff 9008 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 9009 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
9010 if (func_id != BPF_FUNC_redirect_map &&
9011 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
9012 goto error;
9013 break;
fbfc504a
BT
9014 /* Restrict bpf side of cpumap and xskmap, open when use-cases
9015 * appear.
9016 */
6710e112
JDB
9017 case BPF_MAP_TYPE_CPUMAP:
9018 if (func_id != BPF_FUNC_redirect_map)
9019 goto error;
9020 break;
fada7fdc
JL
9021 case BPF_MAP_TYPE_XSKMAP:
9022 if (func_id != BPF_FUNC_redirect_map &&
9023 func_id != BPF_FUNC_map_lookup_elem)
9024 goto error;
9025 break;
56f668df 9026 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 9027 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
9028 if (func_id != BPF_FUNC_map_lookup_elem)
9029 goto error;
16a43625 9030 break;
174a79ff
JF
9031 case BPF_MAP_TYPE_SOCKMAP:
9032 if (func_id != BPF_FUNC_sk_redirect_map &&
9033 func_id != BPF_FUNC_sock_map_update &&
4f738adb 9034 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 9035 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 9036 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
9037 func_id != BPF_FUNC_map_lookup_elem &&
9038 !may_update_sockmap(env, func_id))
174a79ff
JF
9039 goto error;
9040 break;
81110384
JF
9041 case BPF_MAP_TYPE_SOCKHASH:
9042 if (func_id != BPF_FUNC_sk_redirect_hash &&
9043 func_id != BPF_FUNC_sock_hash_update &&
9044 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 9045 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 9046 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
9047 func_id != BPF_FUNC_map_lookup_elem &&
9048 !may_update_sockmap(env, func_id))
81110384
JF
9049 goto error;
9050 break;
2dbb9b9e
MKL
9051 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9052 if (func_id != BPF_FUNC_sk_select_reuseport)
9053 goto error;
9054 break;
f1a2e44a
MV
9055 case BPF_MAP_TYPE_QUEUE:
9056 case BPF_MAP_TYPE_STACK:
9057 if (func_id != BPF_FUNC_map_peek_elem &&
9058 func_id != BPF_FUNC_map_pop_elem &&
9059 func_id != BPF_FUNC_map_push_elem)
9060 goto error;
9061 break;
6ac99e8f
MKL
9062 case BPF_MAP_TYPE_SK_STORAGE:
9063 if (func_id != BPF_FUNC_sk_storage_get &&
9db44fdd
KKD
9064 func_id != BPF_FUNC_sk_storage_delete &&
9065 func_id != BPF_FUNC_kptr_xchg)
6ac99e8f
MKL
9066 goto error;
9067 break;
8ea63684
KS
9068 case BPF_MAP_TYPE_INODE_STORAGE:
9069 if (func_id != BPF_FUNC_inode_storage_get &&
9db44fdd
KKD
9070 func_id != BPF_FUNC_inode_storage_delete &&
9071 func_id != BPF_FUNC_kptr_xchg)
8ea63684
KS
9072 goto error;
9073 break;
4cf1bc1f
KS
9074 case BPF_MAP_TYPE_TASK_STORAGE:
9075 if (func_id != BPF_FUNC_task_storage_get &&
9db44fdd
KKD
9076 func_id != BPF_FUNC_task_storage_delete &&
9077 func_id != BPF_FUNC_kptr_xchg)
4cf1bc1f
KS
9078 goto error;
9079 break;
c4bcfb38
YS
9080 case BPF_MAP_TYPE_CGRP_STORAGE:
9081 if (func_id != BPF_FUNC_cgrp_storage_get &&
9db44fdd
KKD
9082 func_id != BPF_FUNC_cgrp_storage_delete &&
9083 func_id != BPF_FUNC_kptr_xchg)
c4bcfb38
YS
9084 goto error;
9085 break;
9330986c
JK
9086 case BPF_MAP_TYPE_BLOOM_FILTER:
9087 if (func_id != BPF_FUNC_map_peek_elem &&
9088 func_id != BPF_FUNC_map_push_elem)
9089 goto error;
9090 break;
6aff67c8
AS
9091 default:
9092 break;
9093 }
9094
9095 /* ... and second from the function itself. */
9096 switch (func_id) {
9097 case BPF_FUNC_tail_call:
9098 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9099 goto error;
e411901c
MF
9100 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9101 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
9102 return -EINVAL;
9103 }
6aff67c8
AS
9104 break;
9105 case BPF_FUNC_perf_event_read:
9106 case BPF_FUNC_perf_event_output:
908432ca 9107 case BPF_FUNC_perf_event_read_value:
a7658e1a 9108 case BPF_FUNC_skb_output:
d831ee84 9109 case BPF_FUNC_xdp_output:
6aff67c8
AS
9110 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9111 goto error;
9112 break;
5b029a32
DB
9113 case BPF_FUNC_ringbuf_output:
9114 case BPF_FUNC_ringbuf_reserve:
9115 case BPF_FUNC_ringbuf_query:
bc34dee6
JK
9116 case BPF_FUNC_ringbuf_reserve_dynptr:
9117 case BPF_FUNC_ringbuf_submit_dynptr:
9118 case BPF_FUNC_ringbuf_discard_dynptr:
5b029a32
DB
9119 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9120 goto error;
9121 break;
20571567
DV
9122 case BPF_FUNC_user_ringbuf_drain:
9123 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9124 goto error;
9125 break;
6aff67c8
AS
9126 case BPF_FUNC_get_stackid:
9127 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9128 goto error;
9129 break;
60d20f91 9130 case BPF_FUNC_current_task_under_cgroup:
747ea55e 9131 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
9132 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9133 goto error;
9134 break;
97f91a7c 9135 case BPF_FUNC_redirect_map:
9c270af3 9136 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 9137 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
9138 map->map_type != BPF_MAP_TYPE_CPUMAP &&
9139 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
9140 goto error;
9141 break;
174a79ff 9142 case BPF_FUNC_sk_redirect_map:
4f738adb 9143 case BPF_FUNC_msg_redirect_map:
81110384 9144 case BPF_FUNC_sock_map_update:
174a79ff
JF
9145 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9146 goto error;
9147 break;
81110384
JF
9148 case BPF_FUNC_sk_redirect_hash:
9149 case BPF_FUNC_msg_redirect_hash:
9150 case BPF_FUNC_sock_hash_update:
9151 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
9152 goto error;
9153 break;
cd339431 9154 case BPF_FUNC_get_local_storage:
b741f163
RG
9155 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9156 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
9157 goto error;
9158 break;
2dbb9b9e 9159 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
9160 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9161 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9162 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
9163 goto error;
9164 break;
f1a2e44a 9165 case BPF_FUNC_map_pop_elem:
f1a2e44a
MV
9166 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9167 map->map_type != BPF_MAP_TYPE_STACK)
9168 goto error;
9169 break;
9330986c
JK
9170 case BPF_FUNC_map_peek_elem:
9171 case BPF_FUNC_map_push_elem:
9172 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9173 map->map_type != BPF_MAP_TYPE_STACK &&
9174 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9175 goto error;
9176 break;
07343110
FZ
9177 case BPF_FUNC_map_lookup_percpu_elem:
9178 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9179 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9180 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9181 goto error;
9182 break;
6ac99e8f
MKL
9183 case BPF_FUNC_sk_storage_get:
9184 case BPF_FUNC_sk_storage_delete:
9185 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9186 goto error;
9187 break;
8ea63684
KS
9188 case BPF_FUNC_inode_storage_get:
9189 case BPF_FUNC_inode_storage_delete:
9190 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9191 goto error;
9192 break;
4cf1bc1f
KS
9193 case BPF_FUNC_task_storage_get:
9194 case BPF_FUNC_task_storage_delete:
9195 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9196 goto error;
9197 break;
c4bcfb38
YS
9198 case BPF_FUNC_cgrp_storage_get:
9199 case BPF_FUNC_cgrp_storage_delete:
9200 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9201 goto error;
9202 break;
6aff67c8
AS
9203 default:
9204 break;
35578d79
KX
9205 }
9206
9207 return 0;
6aff67c8 9208error:
61bd5218 9209 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 9210 map->map_type, func_id_name(func_id), func_id);
6aff67c8 9211 return -EINVAL;
35578d79
KX
9212}
9213
90133415 9214static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
9215{
9216 int count = 0;
9217
39f19ebb 9218 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 9219 count++;
39f19ebb 9220 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 9221 count++;
39f19ebb 9222 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 9223 count++;
39f19ebb 9224 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 9225 count++;
39f19ebb 9226 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
9227 count++;
9228
90133415
DB
9229 /* We only support one arg being in raw mode at the moment,
9230 * which is sufficient for the helper functions we have
9231 * right now.
9232 */
9233 return count <= 1;
9234}
9235
508362ac 9236static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
90133415 9237{
508362ac
MM
9238 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9239 bool has_size = fn->arg_size[arg] != 0;
9240 bool is_next_size = false;
9241
9242 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9243 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9244
9245 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9246 return is_next_size;
9247
9248 return has_size == is_next_size || is_next_size == is_fixed;
90133415
DB
9249}
9250
9251static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9252{
9253 /* bpf_xxx(..., buf, len) call will access 'len'
9254 * bytes from memory 'buf'. Both arg types need
9255 * to be paired, so make sure there's no buggy
9256 * helper function specification.
9257 */
9258 if (arg_type_is_mem_size(fn->arg1_type) ||
508362ac
MM
9259 check_args_pair_invalid(fn, 0) ||
9260 check_args_pair_invalid(fn, 1) ||
9261 check_args_pair_invalid(fn, 2) ||
9262 check_args_pair_invalid(fn, 3) ||
9263 check_args_pair_invalid(fn, 4))
90133415
DB
9264 return false;
9265
9266 return true;
9267}
9268
9436ef6e
LB
9269static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9270{
9271 int i;
9272
1df8f55a 9273 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4e814da0
KKD
9274 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9275 return !!fn->arg_btf_id[i];
9276 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9277 return fn->arg_btf_id[i] == BPF_PTR_POISON;
508362ac
MM
9278 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9279 /* arg_btf_id and arg_size are in a union. */
9280 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9281 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
1df8f55a
MKL
9282 return false;
9283 }
9284
9436ef6e
LB
9285 return true;
9286}
9287
0c9a7a7e 9288static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
9289{
9290 return check_raw_mode_ok(fn) &&
fd978bf7 9291 check_arg_pair_ok(fn) &&
b2d8ef19 9292 check_btf_id_ok(fn) ? 0 : -EINVAL;
435faee1
DB
9293}
9294
de8f3a83
DB
9295/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9296 * are now invalid, so turn them into unknown SCALAR_VALUE.
66e3a13e
JK
9297 *
9298 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9299 * since these slices point to packet data.
f1174f77 9300 */
b239da34 9301static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 9302{
b239da34
KKD
9303 struct bpf_func_state *state;
9304 struct bpf_reg_state *reg;
969bf05e 9305
b239da34 9306 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
66e3a13e 9307 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
dbd8d228 9308 mark_reg_invalid(env, reg);
b239da34 9309 }));
f4d7e40a
AS
9310}
9311
6d94e741
AS
9312enum {
9313 AT_PKT_END = -1,
9314 BEYOND_PKT_END = -2,
9315};
9316
9317static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9318{
9319 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9320 struct bpf_reg_state *reg = &state->regs[regn];
9321
9322 if (reg->type != PTR_TO_PACKET)
9323 /* PTR_TO_PACKET_META is not supported yet */
9324 return;
9325
9326 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9327 * How far beyond pkt_end it goes is unknown.
9328 * if (!range_open) it's the case of pkt >= pkt_end
9329 * if (range_open) it's the case of pkt > pkt_end
9330 * hence this pointer is at least 1 byte bigger than pkt_end
9331 */
9332 if (range_open)
9333 reg->range = BEYOND_PKT_END;
9334 else
9335 reg->range = AT_PKT_END;
9336}
9337
fd978bf7
JS
9338/* The pointer with the specified id has released its reference to kernel
9339 * resources. Identify all copies of the same pointer and clear the reference.
9340 */
9341static int release_reference(struct bpf_verifier_env *env,
1b986589 9342 int ref_obj_id)
fd978bf7 9343{
b239da34
KKD
9344 struct bpf_func_state *state;
9345 struct bpf_reg_state *reg;
1b986589 9346 int err;
fd978bf7 9347
1b986589
MKL
9348 err = release_reference_state(cur_func(env), ref_obj_id);
9349 if (err)
9350 return err;
9351
b239da34 9352 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
dbd8d228
KKD
9353 if (reg->ref_obj_id == ref_obj_id)
9354 mark_reg_invalid(env, reg);
b239da34 9355 }));
fd978bf7 9356
1b986589 9357 return 0;
fd978bf7
JS
9358}
9359
6a3cd331
DM
9360static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9361{
9362 struct bpf_func_state *unused;
9363 struct bpf_reg_state *reg;
9364
9365 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9366 if (type_is_non_owning_ref(reg->type))
dbd8d228 9367 mark_reg_invalid(env, reg);
6a3cd331
DM
9368 }));
9369}
9370
51c39bb1
AS
9371static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9372 struct bpf_reg_state *regs)
9373{
9374 int i;
9375
9376 /* after the call registers r0 - r5 were scratched */
9377 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9378 mark_reg_not_init(env, regs, caller_saved[i]);
683b96f9 9379 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
51c39bb1
AS
9380 }
9381}
9382
14351375
YS
9383typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9384 struct bpf_func_state *caller,
9385 struct bpf_func_state *callee,
9386 int insn_idx);
9387
be2ef816
AN
9388static int set_callee_state(struct bpf_verifier_env *env,
9389 struct bpf_func_state *caller,
9390 struct bpf_func_state *callee, int insn_idx);
9391
58124a98
EZ
9392static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9393 set_callee_state_fn set_callee_state_cb,
9394 struct bpf_verifier_state *state)
f4d7e40a 9395{
f4d7e40a 9396 struct bpf_func_state *caller, *callee;
14351375 9397 int err;
f4d7e40a 9398
aada9ce6 9399 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 9400 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 9401 state->curframe + 2);
f4d7e40a
AS
9402 return -E2BIG;
9403 }
9404
f4d7e40a
AS
9405 if (state->frame[state->curframe + 1]) {
9406 verbose(env, "verifier bug. Frame %d already allocated\n",
9407 state->curframe + 1);
9408 return -EFAULT;
9409 }
9410
58124a98
EZ
9411 caller = state->frame[state->curframe];
9412 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9413 if (!callee)
9414 return -ENOMEM;
9415 state->frame[state->curframe + 1] = callee;
9416
9417 /* callee cannot access r0, r6 - r9 for reading and has to write
9418 * into its own stack before reading from it.
9419 * callee can read/write into caller's stack
9420 */
9421 init_func_state(env, callee,
9422 /* remember the callsite, it will be used by bpf_exit */
9423 callsite,
9424 state->curframe + 1 /* frameno within this callchain */,
9425 subprog /* subprog number within this prog */);
9426 /* Transfer references to the callee */
9427 err = copy_reference_state(callee, caller);
9428 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9429 if (err)
9430 goto err_out;
9431
9432 /* only increment it after check_reg_arg() finished */
9433 state->curframe++;
9434
9435 return 0;
9436
9437err_out:
9438 free_func_state(callee);
9439 state->frame[state->curframe + 1] = NULL;
9440 return err;
9441}
9442
ab5cfac1
EZ
9443static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9444 int insn_idx, int subprog,
9445 set_callee_state_fn set_callee_state_cb)
58124a98 9446{
ab5cfac1 9447 struct bpf_verifier_state *state = env->cur_state, *callback_state;
58124a98
EZ
9448 struct bpf_func_state *caller, *callee;
9449 int err;
9450
9451 caller = state->frame[state->curframe];
95f2f26f 9452 err = btf_check_subprog_call(env, subprog, caller->regs);
51c39bb1
AS
9453 if (err == -EFAULT)
9454 return err;
51c39bb1 9455
be2ef816
AN
9456 /* set_callee_state is used for direct subprog calls, but we are
9457 * interested in validating only BPF helpers that can call subprogs as
9458 * callbacks
9459 */
ab5cfac1
EZ
9460 env->subprog_info[subprog].is_cb = true;
9461 if (bpf_pseudo_kfunc_call(insn) &&
9462 !is_sync_callback_calling_kfunc(insn->imm)) {
9463 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9464 func_id_name(insn->imm), insn->imm);
9465 return -EFAULT;
9466 } else if (!bpf_pseudo_kfunc_call(insn) &&
9467 !is_callback_calling_function(insn->imm)) { /* helper */
9468 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9469 func_id_name(insn->imm), insn->imm);
9470 return -EFAULT;
be2ef816
AN
9471 }
9472
bfc6bb74 9473 if (insn->code == (BPF_JMP | BPF_CALL) &&
a5bebc4f 9474 insn->src_reg == 0 &&
bfc6bb74
AS
9475 insn->imm == BPF_FUNC_timer_set_callback) {
9476 struct bpf_verifier_state *async_cb;
9477
9478 /* there is no real recursion here. timer callbacks are async */
7ddc80a4 9479 env->subprog_info[subprog].is_async_cb = true;
bfc6bb74 9480 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
ab5cfac1 9481 insn_idx, subprog);
bfc6bb74
AS
9482 if (!async_cb)
9483 return -EFAULT;
9484 callee = async_cb->frame[0];
9485 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9486
9487 /* Convert bpf_timer_set_callback() args into timer callback args */
ab5cfac1 9488 err = set_callee_state_cb(env, caller, callee, insn_idx);
bfc6bb74
AS
9489 if (err)
9490 return err;
9491
ab5cfac1
EZ
9492 return 0;
9493 }
9494
9495 /* for callback functions enqueue entry to callback and
9496 * proceed with next instruction within current frame.
9497 */
9498 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9499 if (!callback_state)
9500 return -ENOMEM;
9501
9502 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9503 callback_state);
9504 if (err)
9505 return err;
9506
9507 callback_state->callback_unroll_depth++;
bb124da6
EZ
9508 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9509 caller->callback_depth = 0;
ab5cfac1
EZ
9510 return 0;
9511}
9512
9513static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9514 int *insn_idx)
9515{
9516 struct bpf_verifier_state *state = env->cur_state;
9517 struct bpf_func_state *caller;
9518 int err, subprog, target_insn;
9519
9520 target_insn = *insn_idx + insn->imm + 1;
9521 subprog = find_subprog(env, target_insn);
9522 if (subprog < 0) {
9523 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9524 return -EFAULT;
9525 }
9526
9527 caller = state->frame[state->curframe];
9528 err = btf_check_subprog_call(env, subprog, caller->regs);
9529 if (err == -EFAULT)
9530 return err;
9531 if (subprog_is_global(env, subprog)) {
9532 if (err) {
9533 verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9534 return err;
9535 }
9536
9537 if (env->log.level & BPF_LOG_LEVEL)
9538 verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
bfc6bb74 9539 clear_caller_saved_regs(env, caller->regs);
ab5cfac1
EZ
9540
9541 /* All global functions return a 64-bit SCALAR_VALUE */
bfc6bb74
AS
9542 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9543 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
ab5cfac1 9544
bfc6bb74
AS
9545 /* continue with next insn after call */
9546 return 0;
9547 }
9548
ab5cfac1
EZ
9549 /* for regular function entry setup new frame and continue
9550 * from that frame.
9551 */
9552 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
fd978bf7 9553 if (err)
58124a98 9554 return err;
f4d7e40a 9555
51c39bb1 9556 clear_caller_saved_regs(env, caller->regs);
f4d7e40a 9557
f4d7e40a 9558 /* and go analyze first insn of the callee */
14351375 9559 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 9560
06ee7115 9561 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 9562 verbose(env, "caller:\n");
0f55f9ed 9563 print_verifier_state(env, caller, true);
f4d7e40a 9564 verbose(env, "callee:\n");
58124a98 9565 print_verifier_state(env, state->frame[state->curframe], true);
f4d7e40a 9566 }
eb86559a 9567
58124a98 9568 return 0;
f4d7e40a
AS
9569}
9570
314ee05e
YS
9571int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9572 struct bpf_func_state *caller,
9573 struct bpf_func_state *callee)
9574{
9575 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9576 * void *callback_ctx, u64 flags);
9577 * callback_fn(struct bpf_map *map, void *key, void *value,
9578 * void *callback_ctx);
9579 */
9580 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9581
9582 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9583 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9584 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9585
9586 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9587 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9588 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9589
9590 /* pointer to stack or null */
9591 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9592
9593 /* unused */
9594 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9595 return 0;
9596}
9597
14351375
YS
9598static int set_callee_state(struct bpf_verifier_env *env,
9599 struct bpf_func_state *caller,
9600 struct bpf_func_state *callee, int insn_idx)
9601{
9602 int i;
9603
9604 /* copy r1 - r5 args that callee can access. The copy includes parent
9605 * pointers, which connects us up to the liveness chain
9606 */
9607 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9608 callee->regs[i] = caller->regs[i];
9609 return 0;
9610}
9611
69c087ba
YS
9612static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9613 struct bpf_func_state *caller,
9614 struct bpf_func_state *callee,
9615 int insn_idx)
9616{
9617 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9618 struct bpf_map *map;
9619 int err;
9620
9621 if (bpf_map_ptr_poisoned(insn_aux)) {
9622 verbose(env, "tail_call abusing map_ptr\n");
9623 return -EINVAL;
9624 }
9625
9626 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9627 if (!map->ops->map_set_for_each_callback_args ||
9628 !map->ops->map_for_each_callback) {
9629 verbose(env, "callback function not allowed for map\n");
9630 return -ENOTSUPP;
9631 }
9632
9633 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9634 if (err)
9635 return err;
9636
9637 callee->in_callback_fn = true;
1bfe26fb 9638 callee->callback_ret_range = tnum_range(0, 1);
69c087ba
YS
9639 return 0;
9640}
9641
e6f2dd0f
JK
9642static int set_loop_callback_state(struct bpf_verifier_env *env,
9643 struct bpf_func_state *caller,
9644 struct bpf_func_state *callee,
9645 int insn_idx)
9646{
9647 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9648 * u64 flags);
9649 * callback_fn(u32 index, void *callback_ctx);
9650 */
9651 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9652 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9653
9654 /* unused */
9655 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9656 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9657 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9658
9659 callee->in_callback_fn = true;
1bfe26fb 9660 callee->callback_ret_range = tnum_range(0, 1);
e6f2dd0f
JK
9661 return 0;
9662}
9663
b00628b1
AS
9664static int set_timer_callback_state(struct bpf_verifier_env *env,
9665 struct bpf_func_state *caller,
9666 struct bpf_func_state *callee,
9667 int insn_idx)
9668{
9669 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9670
9671 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9672 * callback_fn(struct bpf_map *map, void *key, void *value);
9673 */
9674 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9675 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9676 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9677
9678 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9679 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9680 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9681
9682 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9683 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9684 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9685
9686 /* unused */
9687 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9688 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
bfc6bb74 9689 callee->in_async_callback_fn = true;
1bfe26fb 9690 callee->callback_ret_range = tnum_range(0, 1);
b00628b1
AS
9691 return 0;
9692}
9693
7c7e3d31
SL
9694static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9695 struct bpf_func_state *caller,
9696 struct bpf_func_state *callee,
9697 int insn_idx)
9698{
9699 /* bpf_find_vma(struct task_struct *task, u64 addr,
9700 * void *callback_fn, void *callback_ctx, u64 flags)
9701 * (callback_fn)(struct task_struct *task,
9702 * struct vm_area_struct *vma, void *callback_ctx);
9703 */
9704 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9705
9706 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9707 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9708 callee->regs[BPF_REG_2].btf = btf_vmlinux;
d19ddb47 9709 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7c7e3d31
SL
9710
9711 /* pointer to stack or null */
9712 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9713
9714 /* unused */
9715 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9716 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9717 callee->in_callback_fn = true;
1bfe26fb 9718 callee->callback_ret_range = tnum_range(0, 1);
7c7e3d31
SL
9719 return 0;
9720}
9721
20571567
DV
9722static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9723 struct bpf_func_state *caller,
9724 struct bpf_func_state *callee,
9725 int insn_idx)
9726{
9727 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9728 * callback_ctx, u64 flags);
27060531 9729 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
20571567
DV
9730 */
9731 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
f8064ab9 9732 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
20571567
DV
9733 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9734
9735 /* unused */
9736 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9737 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9738 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9739
9740 callee->in_callback_fn = true;
c92a7a52 9741 callee->callback_ret_range = tnum_range(0, 1);
20571567
DV
9742 return 0;
9743}
9744
5d92ddc3
DM
9745static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9746 struct bpf_func_state *caller,
9747 struct bpf_func_state *callee,
9748 int insn_idx)
9749{
d2dcc67d 9750 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
5d92ddc3
DM
9751 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9752 *
d2dcc67d 9753 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
5d92ddc3
DM
9754 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9755 * by this point, so look at 'root'
9756 */
9757 struct btf_field *field;
9758
9759 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9760 BPF_RB_ROOT);
9761 if (!field || !field->graph_root.value_btf_id)
9762 return -EFAULT;
9763
9764 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9765 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9766 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9767 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9768
9769 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9770 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9771 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9772 callee->in_callback_fn = true;
9773 callee->callback_ret_range = tnum_range(0, 1);
9774 return 0;
9775}
9776
9777static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9778
9779/* Are we currently verifying the callback for a rbtree helper that must
9780 * be called with lock held? If so, no need to complain about unreleased
9781 * lock
9782 */
9783static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9784{
9785 struct bpf_verifier_state *state = env->cur_state;
9786 struct bpf_insn *insn = env->prog->insnsi;
9787 struct bpf_func_state *callee;
9788 int kfunc_btf_id;
9789
9790 if (!state->curframe)
9791 return false;
9792
9793 callee = state->frame[state->curframe];
9794
9795 if (!callee->in_callback_fn)
9796 return false;
9797
9798 kfunc_btf_id = insn[callee->callsite].imm;
9799 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9800}
9801
f4d7e40a
AS
9802static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9803{
cafe2c21 9804 struct bpf_verifier_state *state = env->cur_state, *prev_st;
f4d7e40a
AS
9805 struct bpf_func_state *caller, *callee;
9806 struct bpf_reg_state *r0;
cafe2c21 9807 bool in_callback_fn;
fd978bf7 9808 int err;
f4d7e40a
AS
9809
9810 callee = state->frame[state->curframe];
9811 r0 = &callee->regs[BPF_REG_0];
9812 if (r0->type == PTR_TO_STACK) {
9813 /* technically it's ok to return caller's stack pointer
9814 * (or caller's caller's pointer) back to the caller,
9815 * since these pointers are valid. Only current stack
9816 * pointer will be invalid as soon as function exits,
9817 * but let's be conservative
9818 */
9819 verbose(env, "cannot return stack pointer to the caller\n");
9820 return -EINVAL;
9821 }
9822
eb86559a 9823 caller = state->frame[state->curframe - 1];
69c087ba
YS
9824 if (callee->in_callback_fn) {
9825 /* enforce R0 return value range [0, 1]. */
1bfe26fb 9826 struct tnum range = callee->callback_ret_range;
69c087ba
YS
9827
9828 if (r0->type != SCALAR_VALUE) {
9829 verbose(env, "R0 not a scalar value\n");
9830 return -EACCES;
9831 }
9832 if (!tnum_in(range, r0->var_off)) {
9833 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9834 return -EINVAL;
9835 }
ab5cfac1
EZ
9836 if (!calls_callback(env, callee->callsite)) {
9837 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9838 *insn_idx, callee->callsite);
9839 return -EFAULT;
9840 }
69c087ba
YS
9841 } else {
9842 /* return to the caller whatever r0 had in the callee */
9843 caller->regs[BPF_REG_0] = *r0;
9844 }
f4d7e40a 9845
9d9d00ac
KKD
9846 /* callback_fn frame should have released its own additions to parent's
9847 * reference state at this point, or check_reference_leak would
9848 * complain, hence it must be the same as the caller. There is no need
9849 * to copy it back.
9850 */
9851 if (!callee->in_callback_fn) {
9852 /* Transfer references to the caller */
9853 err = copy_reference_state(caller, callee);
9854 if (err)
9855 return err;
9856 }
fd978bf7 9857
ab5cfac1
EZ
9858 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9859 * there function call logic would reschedule callback visit. If iteration
9860 * converges is_state_visited() would prune that visit eventually.
9861 */
cafe2c21
EZ
9862 in_callback_fn = callee->in_callback_fn;
9863 if (in_callback_fn)
ab5cfac1
EZ
9864 *insn_idx = callee->callsite;
9865 else
9866 *insn_idx = callee->callsite + 1;
9867
06ee7115 9868 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 9869 verbose(env, "returning from callee:\n");
0f55f9ed 9870 print_verifier_state(env, callee, true);
f4d7e40a 9871 verbose(env, "to caller at %d:\n", *insn_idx);
0f55f9ed 9872 print_verifier_state(env, caller, true);
f4d7e40a 9873 }
f18b03fa
KKD
9874 /* clear everything in the callee. In case of exceptional exits using
9875 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
f4d7e40a 9876 free_func_state(callee);
eb86559a 9877 state->frame[state->curframe--] = NULL;
cafe2c21
EZ
9878
9879 /* for callbacks widen imprecise scalars to make programs like below verify:
9880 *
9881 * struct ctx { int i; }
9882 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9883 * ...
9884 * struct ctx = { .i = 0; }
9885 * bpf_loop(100, cb, &ctx, 0);
9886 *
9887 * This is similar to what is done in process_iter_next_call() for open
9888 * coded iterators.
9889 */
9890 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9891 if (prev_st) {
9892 err = widen_imprecise_scalars(env, prev_st, state);
9893 if (err)
9894 return err;
9895 }
f4d7e40a
AS
9896 return 0;
9897}
9898
849fa506
YS
9899static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9900 int func_id,
9901 struct bpf_call_arg_meta *meta)
9902{
9903 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9904
f42bcd16 9905 if (ret_type != RET_INTEGER)
849fa506
YS
9906 return;
9907
f42bcd16
AN
9908 switch (func_id) {
9909 case BPF_FUNC_get_stack:
9910 case BPF_FUNC_get_task_stack:
9911 case BPF_FUNC_probe_read_str:
9912 case BPF_FUNC_probe_read_kernel_str:
9913 case BPF_FUNC_probe_read_user_str:
9914 ret_reg->smax_value = meta->msize_max_value;
9915 ret_reg->s32_max_value = meta->msize_max_value;
9916 ret_reg->smin_value = -MAX_ERRNO;
9917 ret_reg->s32_min_value = -MAX_ERRNO;
9918 reg_bounds_sync(ret_reg);
9919 break;
9920 case BPF_FUNC_get_smp_processor_id:
9921 ret_reg->umax_value = nr_cpu_ids - 1;
9922 ret_reg->u32_max_value = nr_cpu_ids - 1;
9923 ret_reg->smax_value = nr_cpu_ids - 1;
9924 ret_reg->s32_max_value = nr_cpu_ids - 1;
9925 ret_reg->umin_value = 0;
9926 ret_reg->u32_min_value = 0;
9927 ret_reg->smin_value = 0;
9928 ret_reg->s32_min_value = 0;
9929 reg_bounds_sync(ret_reg);
9930 break;
9931 }
849fa506
YS
9932}
9933
c93552c4
DB
9934static int
9935record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9936 int func_id, int insn_idx)
9937{
9938 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 9939 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
9940
9941 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
9942 func_id != BPF_FUNC_map_lookup_elem &&
9943 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
9944 func_id != BPF_FUNC_map_delete_elem &&
9945 func_id != BPF_FUNC_map_push_elem &&
9946 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 9947 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f 9948 func_id != BPF_FUNC_for_each_map_elem &&
07343110
FZ
9949 func_id != BPF_FUNC_redirect_map &&
9950 func_id != BPF_FUNC_map_lookup_percpu_elem)
c93552c4 9951 return 0;
09772d92 9952
591fe988 9953 if (map == NULL) {
c93552c4
DB
9954 verbose(env, "kernel subsystem misconfigured verifier\n");
9955 return -EINVAL;
9956 }
9957
591fe988
DB
9958 /* In case of read-only, some additional restrictions
9959 * need to be applied in order to prevent altering the
9960 * state of the map from program side.
9961 */
9962 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9963 (func_id == BPF_FUNC_map_delete_elem ||
9964 func_id == BPF_FUNC_map_update_elem ||
9965 func_id == BPF_FUNC_map_push_elem ||
9966 func_id == BPF_FUNC_map_pop_elem)) {
9967 verbose(env, "write into map forbidden\n");
9968 return -EACCES;
9969 }
9970
d2e4c1e6 9971 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 9972 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 9973 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 9974 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 9975 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 9976 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
9977 return 0;
9978}
9979
d2e4c1e6
DB
9980static int
9981record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9982 int func_id, int insn_idx)
9983{
9984 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9985 struct bpf_reg_state *regs = cur_regs(env), *reg;
9986 struct bpf_map *map = meta->map_ptr;
a657182a 9987 u64 val, max;
cc52d914 9988 int err;
d2e4c1e6
DB
9989
9990 if (func_id != BPF_FUNC_tail_call)
9991 return 0;
9992 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9993 verbose(env, "kernel subsystem misconfigured verifier\n");
9994 return -EINVAL;
9995 }
9996
d2e4c1e6 9997 reg = &regs[BPF_REG_3];
a657182a
DB
9998 val = reg->var_off.value;
9999 max = map->max_entries;
d2e4c1e6 10000
a657182a 10001 if (!(register_is_const(reg) && val < max)) {
d2e4c1e6
DB
10002 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10003 return 0;
10004 }
10005
cc52d914
DB
10006 err = mark_chain_precision(env, BPF_REG_3);
10007 if (err)
10008 return err;
d2e4c1e6
DB
10009 if (bpf_map_key_unseen(aux))
10010 bpf_map_key_store(aux, val);
10011 else if (!bpf_map_key_poisoned(aux) &&
10012 bpf_map_key_immediate(aux) != val)
10013 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10014 return 0;
10015}
10016
f18b03fa 10017static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
fd978bf7
JS
10018{
10019 struct bpf_func_state *state = cur_func(env);
9d9d00ac 10020 bool refs_lingering = false;
fd978bf7
JS
10021 int i;
10022
f18b03fa 10023 if (!exception_exit && state->frameno && !state->in_callback_fn)
9d9d00ac
KKD
10024 return 0;
10025
fd978bf7 10026 for (i = 0; i < state->acquired_refs; i++) {
f18b03fa 10027 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9d9d00ac 10028 continue;
fd978bf7
JS
10029 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10030 state->refs[i].id, state->refs[i].insn_idx);
9d9d00ac 10031 refs_lingering = true;
fd978bf7 10032 }
9d9d00ac 10033 return refs_lingering ? -EINVAL : 0;
fd978bf7
JS
10034}
10035
7b15523a
FR
10036static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10037 struct bpf_reg_state *regs)
10038{
10039 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10040 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10041 struct bpf_map *fmt_map = fmt_reg->map_ptr;
78aa1cc9 10042 struct bpf_bprintf_data data = {};
7b15523a
FR
10043 int err, fmt_map_off, num_args;
10044 u64 fmt_addr;
10045 char *fmt;
10046
10047 /* data must be an array of u64 */
10048 if (data_len_reg->var_off.value % 8)
10049 return -EINVAL;
10050 num_args = data_len_reg->var_off.value / 8;
10051
10052 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10053 * and map_direct_value_addr is set.
10054 */
10055 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10056 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10057 fmt_map_off);
8e8ee109
FR
10058 if (err) {
10059 verbose(env, "verifier bug\n");
10060 return -EFAULT;
10061 }
7b15523a
FR
10062 fmt = (char *)(long)fmt_addr + fmt_map_off;
10063
10064 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10065 * can focus on validating the format specifiers.
10066 */
78aa1cc9 10067 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7b15523a
FR
10068 if (err < 0)
10069 verbose(env, "Invalid format string\n");
10070
10071 return err;
10072}
10073
9b99edca
JO
10074static int check_get_func_ip(struct bpf_verifier_env *env)
10075{
9b99edca
JO
10076 enum bpf_prog_type type = resolve_prog_type(env->prog);
10077 int func_id = BPF_FUNC_get_func_ip;
10078
10079 if (type == BPF_PROG_TYPE_TRACING) {
f92c1e18 10080 if (!bpf_prog_has_trampoline(env->prog)) {
9b99edca
JO
10081 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10082 func_id_name(func_id), func_id);
10083 return -ENOTSUPP;
10084 }
10085 return 0;
9ffd9f3f
JO
10086 } else if (type == BPF_PROG_TYPE_KPROBE) {
10087 return 0;
9b99edca
JO
10088 }
10089
10090 verbose(env, "func %s#%d not supported for program type %d\n",
10091 func_id_name(func_id), func_id, type);
10092 return -ENOTSUPP;
10093}
10094
1ade2371
EZ
10095static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10096{
10097 return &env->insn_aux_data[env->insn_idx];
10098}
10099
10100static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10101{
10102 struct bpf_reg_state *regs = cur_regs(env);
10103 struct bpf_reg_state *reg = &regs[BPF_REG_4];
10104 bool reg_is_null = register_is_null(reg);
10105
10106 if (reg_is_null)
10107 mark_chain_precision(env, BPF_REG_4);
10108
10109 return reg_is_null;
10110}
10111
10112static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10113{
10114 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10115
10116 if (!state->initialized) {
10117 state->initialized = 1;
10118 state->fit_for_inline = loop_flag_is_zero(env);
10119 state->callback_subprogno = subprogno;
10120 return;
10121 }
10122
10123 if (!state->fit_for_inline)
10124 return;
10125
10126 state->fit_for_inline = (loop_flag_is_zero(env) &&
10127 state->callback_subprogno == subprogno);
10128}
10129
69c087ba
YS
10130static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10131 int *insn_idx_p)
17a52670 10132{
aef9d4a3 10133 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
01cc55af 10134 bool returns_cpu_specific_alloc_ptr = false;
17a52670 10135 const struct bpf_func_proto *fn = NULL;
3c480732 10136 enum bpf_return_type ret_type;
c25b2ae1 10137 enum bpf_type_flag ret_flag;
638f5b90 10138 struct bpf_reg_state *regs;
33ff9823 10139 struct bpf_call_arg_meta meta;
69c087ba 10140 int insn_idx = *insn_idx_p;
969bf05e 10141 bool changes_data;
69c087ba 10142 int i, err, func_id;
17a52670
AS
10143
10144 /* find function prototype */
69c087ba 10145 func_id = insn->imm;
17a52670 10146 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
10147 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10148 func_id);
17a52670
AS
10149 return -EINVAL;
10150 }
10151
00176a34 10152 if (env->ops->get_func_proto)
5e43f899 10153 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 10154 if (!fn) {
61bd5218
JK
10155 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10156 func_id);
17a52670
AS
10157 return -EINVAL;
10158 }
10159
10160 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 10161 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 10162 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
10163 return -EINVAL;
10164 }
10165
eae2e83e
JO
10166 if (fn->allowed && !fn->allowed(env->prog)) {
10167 verbose(env, "helper call is not allowed in probe\n");
10168 return -EINVAL;
10169 }
10170
01685c5b
YS
10171 if (!env->prog->aux->sleepable && fn->might_sleep) {
10172 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10173 return -EINVAL;
10174 }
10175
04514d13 10176 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 10177 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
10178 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10179 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10180 func_id_name(func_id), func_id);
10181 return -EINVAL;
10182 }
969bf05e 10183
33ff9823 10184 memset(&meta, 0, sizeof(meta));
36bbef52 10185 meta.pkt_access = fn->pkt_access;
33ff9823 10186
0c9a7a7e 10187 err = check_func_proto(fn, func_id);
435faee1 10188 if (err) {
61bd5218 10189 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 10190 func_id_name(func_id), func_id);
435faee1
DB
10191 return err;
10192 }
10193
9bb00b28
YS
10194 if (env->cur_state->active_rcu_lock) {
10195 if (fn->might_sleep) {
10196 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10197 func_id_name(func_id), func_id);
10198 return -EINVAL;
10199 }
10200
10201 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10202 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10203 }
10204
d83525ca 10205 meta.func_id = func_id;
17a52670 10206 /* check args */
523a4cf4 10207 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
1d18feb2 10208 err = check_func_arg(env, i, &meta, fn, insn_idx);
a7658e1a
AS
10209 if (err)
10210 return err;
10211 }
17a52670 10212
c93552c4
DB
10213 err = record_func_map(env, &meta, func_id, insn_idx);
10214 if (err)
10215 return err;
10216
d2e4c1e6
DB
10217 err = record_func_key(env, &meta, func_id, insn_idx);
10218 if (err)
10219 return err;
10220
435faee1
DB
10221 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10222 * is inferred from register state.
10223 */
10224 for (i = 0; i < meta.access_size; i++) {
ca369602 10225 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
1f9a1ea8 10226 BPF_WRITE, -1, false, false);
435faee1
DB
10227 if (err)
10228 return err;
10229 }
10230
8f14852e
KKD
10231 regs = cur_regs(env);
10232
10233 if (meta.release_regno) {
10234 err = -EINVAL;
27060531
KKD
10235 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10236 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10237 * is safe to do directly.
10238 */
10239 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10240 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10241 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10242 return -EFAULT;
10243 }
97e03f52 10244 err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
5b221ecb
YS
10245 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10246 u32 ref_obj_id = meta.ref_obj_id;
10247 bool in_rcu = in_rcu_cs(env);
10248 struct bpf_func_state *state;
10249 struct bpf_reg_state *reg;
10250
10251 err = release_reference_state(cur_func(env), ref_obj_id);
10252 if (!err) {
10253 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10254 if (reg->ref_obj_id == ref_obj_id) {
10255 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10256 reg->ref_obj_id = 0;
10257 reg->type &= ~MEM_ALLOC;
10258 reg->type |= MEM_RCU;
10259 } else {
10260 mark_reg_invalid(env, reg);
10261 }
10262 }
10263 }));
10264 }
27060531 10265 } else if (meta.ref_obj_id) {
8f14852e 10266 err = release_reference(env, meta.ref_obj_id);
27060531
KKD
10267 } else if (register_is_null(&regs[meta.release_regno])) {
10268 /* meta.ref_obj_id can only be 0 if register that is meant to be
10269 * released is NULL, which must be > R0.
10270 */
8f14852e 10271 err = 0;
27060531 10272 }
46f8bc92
MKL
10273 if (err) {
10274 verbose(env, "func %s#%d reference has not been acquired before\n",
10275 func_id_name(func_id), func_id);
fd978bf7 10276 return err;
46f8bc92 10277 }
fd978bf7
JS
10278 }
10279
e6f2dd0f
JK
10280 switch (func_id) {
10281 case BPF_FUNC_tail_call:
f18b03fa 10282 err = check_reference_leak(env, false);
e6f2dd0f
JK
10283 if (err) {
10284 verbose(env, "tail_call would lead to reference leak\n");
10285 return err;
10286 }
10287 break;
10288 case BPF_FUNC_get_local_storage:
10289 /* check that flags argument in get_local_storage(map, flags) is 0,
10290 * this is required because get_local_storage() can't return an error.
10291 */
10292 if (!register_is_null(&regs[BPF_REG_2])) {
10293 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10294 return -EINVAL;
10295 }
10296 break;
10297 case BPF_FUNC_for_each_map_elem:
ab5cfac1
EZ
10298 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10299 set_map_elem_callback_state);
e6f2dd0f
JK
10300 break;
10301 case BPF_FUNC_timer_set_callback:
ab5cfac1
EZ
10302 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10303 set_timer_callback_state);
e6f2dd0f
JK
10304 break;
10305 case BPF_FUNC_find_vma:
ab5cfac1
EZ
10306 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10307 set_find_vma_callback_state);
e6f2dd0f
JK
10308 break;
10309 case BPF_FUNC_snprintf:
7b15523a 10310 err = check_bpf_snprintf_call(env, regs);
e6f2dd0f
JK
10311 break;
10312 case BPF_FUNC_loop:
1ade2371 10313 update_loop_inline_state(env, meta.subprogno);
bb124da6
EZ
10314 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10315 * is finished, thus mark it precise.
10316 */
10317 err = mark_chain_precision(env, BPF_REG_1);
10318 if (err)
10319 return err;
10320 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10321 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10322 set_loop_callback_state);
10323 } else {
10324 cur_func(env)->callback_depth = 0;
10325 if (env->log.level & BPF_LOG_LEVEL2)
10326 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10327 env->cur_state->curframe);
10328 }
e6f2dd0f 10329 break;
263ae152
JK
10330 case BPF_FUNC_dynptr_from_mem:
10331 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10332 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10333 reg_type_str(env, regs[BPF_REG_1].type));
10334 return -EACCES;
10335 }
69fd337a
SF
10336 break;
10337 case BPF_FUNC_set_retval:
aef9d4a3
SF
10338 if (prog_type == BPF_PROG_TYPE_LSM &&
10339 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
69fd337a
SF
10340 if (!env->prog->aux->attach_func_proto->type) {
10341 /* Make sure programs that attach to void
10342 * hooks don't try to modify return value.
10343 */
10344 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10345 return -EINVAL;
10346 }
10347 }
10348 break;
88374342 10349 case BPF_FUNC_dynptr_data:
485ec51e
JK
10350 {
10351 struct bpf_reg_state *reg;
10352 int id, ref_obj_id;
20571567 10353
485ec51e
JK
10354 reg = get_dynptr_arg_reg(env, fn, regs);
10355 if (!reg)
10356 return -EFAULT;
f8064ab9 10357
f8064ab9 10358
485ec51e
JK
10359 if (meta.dynptr_id) {
10360 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10361 return -EFAULT;
88374342 10362 }
485ec51e
JK
10363 if (meta.ref_obj_id) {
10364 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
88374342
JK
10365 return -EFAULT;
10366 }
485ec51e
JK
10367
10368 id = dynptr_id(env, reg);
10369 if (id < 0) {
10370 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10371 return id;
10372 }
10373
10374 ref_obj_id = dynptr_ref_obj_id(env, reg);
10375 if (ref_obj_id < 0) {
10376 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10377 return ref_obj_id;
10378 }
10379
10380 meta.dynptr_id = id;
10381 meta.ref_obj_id = ref_obj_id;
10382
88374342 10383 break;
485ec51e 10384 }
b5964b96
JK
10385 case BPF_FUNC_dynptr_write:
10386 {
10387 enum bpf_dynptr_type dynptr_type;
10388 struct bpf_reg_state *reg;
10389
10390 reg = get_dynptr_arg_reg(env, fn, regs);
10391 if (!reg)
10392 return -EFAULT;
10393
10394 dynptr_type = dynptr_get_type(env, reg);
10395 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10396 return -EFAULT;
10397
10398 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10399 /* this will trigger clear_all_pkt_pointers(), which will
10400 * invalidate all dynptr slices associated with the skb
10401 */
10402 changes_data = true;
10403
10404 break;
10405 }
01cc55af
YS
10406 case BPF_FUNC_per_cpu_ptr:
10407 case BPF_FUNC_this_cpu_ptr:
10408 {
10409 struct bpf_reg_state *reg = &regs[BPF_REG_1];
10410 const struct btf_type *type;
10411
10412 if (reg->type & MEM_RCU) {
10413 type = btf_type_by_id(reg->btf, reg->btf_id);
10414 if (!type || !btf_type_is_struct(type)) {
10415 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10416 return -EFAULT;
10417 }
10418 returns_cpu_specific_alloc_ptr = true;
10419 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10420 }
10421 break;
10422 }
20571567 10423 case BPF_FUNC_user_ringbuf_drain:
ab5cfac1
EZ
10424 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10425 set_user_ringbuf_callback_state);
20571567 10426 break;
7b15523a
FR
10427 }
10428
e6f2dd0f
JK
10429 if (err)
10430 return err;
10431
17a52670 10432 /* reset caller saved regs */
dc503a8a 10433 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 10434 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
10435 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10436 }
17a52670 10437
5327ed3d
JW
10438 /* helper call returns 64-bit value. */
10439 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10440
dc503a8a 10441 /* update return register (already marked as written above) */
3c480732 10442 ret_type = fn->ret_type;
0c9a7a7e
JK
10443 ret_flag = type_flag(ret_type);
10444
10445 switch (base_type(ret_type)) {
10446 case RET_INTEGER:
f1174f77 10447 /* sets type to SCALAR_VALUE */
61bd5218 10448 mark_reg_unknown(env, regs, BPF_REG_0);
0c9a7a7e
JK
10449 break;
10450 case RET_VOID:
17a52670 10451 regs[BPF_REG_0].type = NOT_INIT;
0c9a7a7e
JK
10452 break;
10453 case RET_PTR_TO_MAP_VALUE:
f1174f77 10454 /* There is no offset yet applied, variable or fixed */
61bd5218 10455 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
10456 /* remember map_ptr, so that check_map_access()
10457 * can check 'value_size' boundary of memory access
10458 * to map element returned from bpf_map_lookup_elem()
10459 */
33ff9823 10460 if (meta.map_ptr == NULL) {
61bd5218
JK
10461 verbose(env,
10462 "kernel subsystem misconfigured verifier\n");
17a52670
AS
10463 return -EINVAL;
10464 }
33ff9823 10465 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3e8ce298 10466 regs[BPF_REG_0].map_uid = meta.map_uid;
c25b2ae1
HL
10467 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10468 if (!type_may_be_null(ret_type) &&
db559117 10469 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
c25b2ae1 10470 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301 10471 }
0c9a7a7e
JK
10472 break;
10473 case RET_PTR_TO_SOCKET:
c64b7983 10474 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 10475 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
0c9a7a7e
JK
10476 break;
10477 case RET_PTR_TO_SOCK_COMMON:
85a51f8c 10478 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 10479 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
0c9a7a7e
JK
10480 break;
10481 case RET_PTR_TO_TCP_SOCK:
655a51e5 10482 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 10483 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
0c9a7a7e 10484 break;
2de2669b 10485 case RET_PTR_TO_MEM:
457f4436 10486 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 10487 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
457f4436 10488 regs[BPF_REG_0].mem_size = meta.mem_size;
0c9a7a7e
JK
10489 break;
10490 case RET_PTR_TO_MEM_OR_BTF_ID:
10491 {
eaa6bcb7
HL
10492 const struct btf_type *t;
10493
10494 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 10495 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
10496 if (!btf_type_is_struct(t)) {
10497 u32 tsize;
10498 const struct btf_type *ret;
10499 const char *tname;
10500
10501 /* resolve the type size of ksym. */
22dc4a0f 10502 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 10503 if (IS_ERR(ret)) {
22dc4a0f 10504 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
10505 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10506 tname, PTR_ERR(ret));
10507 return -EINVAL;
10508 }
c25b2ae1 10509 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
eaa6bcb7
HL
10510 regs[BPF_REG_0].mem_size = tsize;
10511 } else {
01cc55af
YS
10512 if (returns_cpu_specific_alloc_ptr) {
10513 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10514 } else {
10515 /* MEM_RDONLY may be carried from ret_flag, but it
10516 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10517 * it will confuse the check of PTR_TO_BTF_ID in
10518 * check_mem_access().
10519 */
10520 ret_flag &= ~MEM_RDONLY;
10521 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10522 }
34d3a78c 10523
22dc4a0f 10524 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
10525 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10526 }
0c9a7a7e
JK
10527 break;
10528 }
10529 case RET_PTR_TO_BTF_ID:
10530 {
c0a5a21c 10531 struct btf *ret_btf;
af7ec138
YS
10532 int ret_btf_id;
10533
10534 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 10535 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
c0a5a21c 10536 if (func_id == BPF_FUNC_kptr_xchg) {
aa3496ac
KKD
10537 ret_btf = meta.kptr_field->kptr.btf;
10538 ret_btf_id = meta.kptr_field->kptr.btf_id;
36d8bdf7 10539 if (!btf_is_kernel(ret_btf)) {
738c96d5 10540 regs[BPF_REG_0].type |= MEM_ALLOC;
36d8bdf7
YS
10541 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10542 regs[BPF_REG_0].type |= MEM_PERCPU;
10543 }
c0a5a21c 10544 } else {
47e34cb7
DM
10545 if (fn->ret_btf_id == BPF_PTR_POISON) {
10546 verbose(env, "verifier internal error:");
10547 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10548 func_id_name(func_id));
10549 return -EINVAL;
10550 }
c0a5a21c
KKD
10551 ret_btf = btf_vmlinux;
10552 ret_btf_id = *fn->ret_btf_id;
10553 }
af7ec138 10554 if (ret_btf_id == 0) {
3c480732
HL
10555 verbose(env, "invalid return type %u of func %s#%d\n",
10556 base_type(ret_type), func_id_name(func_id),
10557 func_id);
af7ec138
YS
10558 return -EINVAL;
10559 }
c0a5a21c 10560 regs[BPF_REG_0].btf = ret_btf;
af7ec138 10561 regs[BPF_REG_0].btf_id = ret_btf_id;
0c9a7a7e
JK
10562 break;
10563 }
10564 default:
3c480732
HL
10565 verbose(env, "unknown return type %u of func %s#%d\n",
10566 base_type(ret_type), func_id_name(func_id), func_id);
17a52670
AS
10567 return -EINVAL;
10568 }
04fd61ab 10569
c25b2ae1 10570 if (type_may_be_null(regs[BPF_REG_0].type))
93c230e3
MKL
10571 regs[BPF_REG_0].id = ++env->id_gen;
10572
b2d8ef19
DM
10573 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10574 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10575 func_id_name(func_id), func_id);
10576 return -EFAULT;
10577 }
10578
f8064ab9
KKD
10579 if (is_dynptr_ref_function(func_id))
10580 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10581
88374342 10582 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
1b986589
MKL
10583 /* For release_reference() */
10584 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 10585 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
10586 int id = acquire_reference_state(env, insn_idx);
10587
10588 if (id < 0)
10589 return id;
10590 /* For mark_ptr_or_null_reg() */
10591 regs[BPF_REG_0].id = id;
10592 /* For release_reference() */
10593 regs[BPF_REG_0].ref_obj_id = id;
10594 }
1b986589 10595
849fa506
YS
10596 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10597
61bd5218 10598 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
10599 if (err)
10600 return err;
04fd61ab 10601
fa28dcb8
SL
10602 if ((func_id == BPF_FUNC_get_stack ||
10603 func_id == BPF_FUNC_get_task_stack) &&
10604 !env->prog->has_callchain_buf) {
c195651e
YS
10605 const char *err_str;
10606
10607#ifdef CONFIG_PERF_EVENTS
10608 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10609 err_str = "cannot get callchain buffer for func %s#%d\n";
10610#else
10611 err = -ENOTSUPP;
10612 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10613#endif
10614 if (err) {
10615 verbose(env, err_str, func_id_name(func_id), func_id);
10616 return err;
10617 }
10618
10619 env->prog->has_callchain_buf = true;
10620 }
10621
5d99cb2c
SL
10622 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10623 env->prog->call_get_stack = true;
10624
9b99edca
JO
10625 if (func_id == BPF_FUNC_get_func_ip) {
10626 if (check_get_func_ip(env))
10627 return -ENOTSUPP;
10628 env->prog->call_get_func_ip = true;
10629 }
10630
969bf05e
AS
10631 if (changes_data)
10632 clear_all_pkt_pointers(env);
10633 return 0;
10634}
10635
e6ac2450
MKL
10636/* mark_btf_func_reg_size() is used when the reg size is determined by
10637 * the BTF func_proto's return value size and argument.
10638 */
10639static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10640 size_t reg_size)
10641{
10642 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10643
10644 if (regno == BPF_REG_0) {
10645 /* Function return value */
10646 reg->live |= REG_LIVE_WRITTEN;
10647 reg->subreg_def = reg_size == sizeof(u64) ?
10648 DEF_NOT_SUBREG : env->insn_idx + 1;
10649 } else {
10650 /* Function argument */
10651 if (reg_size == sizeof(u64)) {
10652 mark_insn_zext(env, reg);
10653 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10654 } else {
10655 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10656 }
10657 }
10658}
10659
00b85860
KKD
10660static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10661{
10662 return meta->kfunc_flags & KF_ACQUIRE;
10663}
a5d82727 10664
00b85860
KKD
10665static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10666{
10667 return meta->kfunc_flags & KF_RELEASE;
10668}
e6ac2450 10669
00b85860
KKD
10670static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10671{
6c831c46 10672 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
00b85860 10673}
4dd48c6f 10674
00b85860
KKD
10675static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10676{
10677 return meta->kfunc_flags & KF_SLEEPABLE;
10678}
5c073f26 10679
00b85860
KKD
10680static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10681{
10682 return meta->kfunc_flags & KF_DESTRUCTIVE;
10683}
eb1f7f71 10684
fca1aa75
YS
10685static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10686{
10687 return meta->kfunc_flags & KF_RCU;
10688}
10689
dfab99df
CZ
10690static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10691{
10692 return meta->kfunc_flags & KF_RCU_PROTECTED;
10693}
10694
a50388db
KKD
10695static bool __kfunc_param_match_suffix(const struct btf *btf,
10696 const struct btf_param *arg,
10697 const char *suffix)
00b85860 10698{
a50388db 10699 int suffix_len = strlen(suffix), len;
00b85860 10700 const char *param_name;
e6ac2450 10701
00b85860
KKD
10702 /* In the future, this can be ported to use BTF tagging */
10703 param_name = btf_name_by_offset(btf, arg->name_off);
10704 if (str_is_empty(param_name))
10705 return false;
10706 len = strlen(param_name);
a50388db 10707 if (len < suffix_len)
00b85860 10708 return false;
a50388db
KKD
10709 param_name += len - suffix_len;
10710 return !strncmp(param_name, suffix, suffix_len);
10711}
5c073f26 10712
a50388db
KKD
10713static bool is_kfunc_arg_mem_size(const struct btf *btf,
10714 const struct btf_param *arg,
10715 const struct bpf_reg_state *reg)
10716{
10717 const struct btf_type *t;
5c073f26 10718
a50388db
KKD
10719 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10720 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
00b85860 10721 return false;
eb1f7f71 10722
a50388db
KKD
10723 return __kfunc_param_match_suffix(btf, arg, "__sz");
10724}
eb1f7f71 10725
66e3a13e
JK
10726static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10727 const struct btf_param *arg,
10728 const struct bpf_reg_state *reg)
10729{
10730 const struct btf_type *t;
10731
10732 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10733 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10734 return false;
10735
10736 return __kfunc_param_match_suffix(btf, arg, "__szk");
10737}
10738
3bda08b6
DR
10739static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10740{
10741 return __kfunc_param_match_suffix(btf, arg, "__opt");
10742}
10743
a50388db
KKD
10744static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10745{
10746 return __kfunc_param_match_suffix(btf, arg, "__k");
00b85860 10747}
eb1f7f71 10748
958cf2e2
KKD
10749static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10750{
10751 return __kfunc_param_match_suffix(btf, arg, "__ign");
10752}
5c073f26 10753
ac9f0605
KKD
10754static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10755{
10756 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10757}
e6ac2450 10758
d96d937d
JK
10759static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10760{
10761 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10762}
10763
7c50b1cb
DM
10764static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10765{
10766 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10767}
10768
cb3ecf79
CZ
10769static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10770{
10771 return __kfunc_param_match_suffix(btf, arg, "__nullable");
10772}
10773
00b85860
KKD
10774static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10775 const struct btf_param *arg,
10776 const char *name)
10777{
10778 int len, target_len = strlen(name);
10779 const char *param_name;
e6ac2450 10780
00b85860
KKD
10781 param_name = btf_name_by_offset(btf, arg->name_off);
10782 if (str_is_empty(param_name))
10783 return false;
10784 len = strlen(param_name);
10785 if (len != target_len)
10786 return false;
10787 if (strcmp(param_name, name))
10788 return false;
e6ac2450 10789
00b85860 10790 return true;
e6ac2450
MKL
10791}
10792
00b85860
KKD
10793enum {
10794 KF_ARG_DYNPTR_ID,
8cab76ec
KKD
10795 KF_ARG_LIST_HEAD_ID,
10796 KF_ARG_LIST_NODE_ID,
cd6791b4
DM
10797 KF_ARG_RB_ROOT_ID,
10798 KF_ARG_RB_NODE_ID,
00b85860 10799};
b03c9f9f 10800
00b85860
KKD
10801BTF_ID_LIST(kf_arg_btf_ids)
10802BTF_ID(struct, bpf_dynptr_kern)
8cab76ec
KKD
10803BTF_ID(struct, bpf_list_head)
10804BTF_ID(struct, bpf_list_node)
bd1279ae
DM
10805BTF_ID(struct, bpf_rb_root)
10806BTF_ID(struct, bpf_rb_node)
b03c9f9f 10807
8cab76ec
KKD
10808static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10809 const struct btf_param *arg, int type)
3f50f132 10810{
00b85860
KKD
10811 const struct btf_type *t;
10812 u32 res_id;
3f50f132 10813
00b85860
KKD
10814 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10815 if (!t)
10816 return false;
10817 if (!btf_type_is_ptr(t))
10818 return false;
10819 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10820 if (!t)
10821 return false;
8cab76ec 10822 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
3f50f132
JF
10823}
10824
8cab76ec 10825static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
b03c9f9f 10826{
8cab76ec 10827 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
969bf05e
AS
10828}
10829
8cab76ec 10830static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
3f50f132 10831{
8cab76ec 10832 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
3f50f132
JF
10833}
10834
8cab76ec 10835static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
bb7f0f98 10836{
8cab76ec 10837 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
00b85860
KKD
10838}
10839
cd6791b4
DM
10840static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10841{
10842 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10843}
10844
10845static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10846{
10847 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10848}
10849
5d92ddc3
DM
10850static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10851 const struct btf_param *arg)
10852{
10853 const struct btf_type *t;
10854
10855 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10856 if (!t)
10857 return false;
10858
10859 return true;
10860}
10861
00b85860
KKD
10862/* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10863static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10864 const struct btf *btf,
10865 const struct btf_type *t, int rec)
10866{
10867 const struct btf_type *member_type;
10868 const struct btf_member *member;
10869 u32 i;
10870
10871 if (!btf_type_is_struct(t))
10872 return false;
10873
10874 for_each_member(i, t, member) {
10875 const struct btf_array *array;
10876
10877 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10878 if (btf_type_is_struct(member_type)) {
10879 if (rec >= 3) {
10880 verbose(env, "max struct nesting depth exceeded\n");
10881 return false;
10882 }
10883 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10884 return false;
10885 continue;
10886 }
10887 if (btf_type_is_array(member_type)) {
10888 array = btf_array(member_type);
10889 if (!array->nelems)
10890 return false;
10891 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10892 if (!btf_type_is_scalar(member_type))
10893 return false;
10894 continue;
10895 }
10896 if (!btf_type_is_scalar(member_type))
10897 return false;
10898 }
10899 return true;
10900}
10901
00b85860
KKD
10902enum kfunc_ptr_arg_type {
10903 KF_ARG_PTR_TO_CTX,
7c50b1cb
DM
10904 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10905 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
00b85860 10906 KF_ARG_PTR_TO_DYNPTR,
06accc87 10907 KF_ARG_PTR_TO_ITER,
8cab76ec
KKD
10908 KF_ARG_PTR_TO_LIST_HEAD,
10909 KF_ARG_PTR_TO_LIST_NODE,
7c50b1cb 10910 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
00b85860 10911 KF_ARG_PTR_TO_MEM,
7c50b1cb 10912 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
5d92ddc3 10913 KF_ARG_PTR_TO_CALLBACK,
cd6791b4
DM
10914 KF_ARG_PTR_TO_RB_ROOT,
10915 KF_ARG_PTR_TO_RB_NODE,
cb3ecf79 10916 KF_ARG_PTR_TO_NULL,
00b85860
KKD
10917};
10918
ac9f0605
KKD
10919enum special_kfunc_type {
10920 KF_bpf_obj_new_impl,
10921 KF_bpf_obj_drop_impl,
7c50b1cb 10922 KF_bpf_refcount_acquire_impl,
d2dcc67d
DM
10923 KF_bpf_list_push_front_impl,
10924 KF_bpf_list_push_back_impl,
8cab76ec
KKD
10925 KF_bpf_list_pop_front,
10926 KF_bpf_list_pop_back,
fd264ca0 10927 KF_bpf_cast_to_kern_ctx,
a35b9af4 10928 KF_bpf_rdonly_cast,
9bb00b28
YS
10929 KF_bpf_rcu_read_lock,
10930 KF_bpf_rcu_read_unlock,
bd1279ae 10931 KF_bpf_rbtree_remove,
d2dcc67d 10932 KF_bpf_rbtree_add_impl,
bd1279ae 10933 KF_bpf_rbtree_first,
b5964b96 10934 KF_bpf_dynptr_from_skb,
05421aec 10935 KF_bpf_dynptr_from_xdp,
66e3a13e
JK
10936 KF_bpf_dynptr_slice,
10937 KF_bpf_dynptr_slice_rdwr,
361f129f 10938 KF_bpf_dynptr_clone,
36d8bdf7
YS
10939 KF_bpf_percpu_obj_new_impl,
10940 KF_bpf_percpu_obj_drop_impl,
f18b03fa 10941 KF_bpf_throw,
9c66dc94 10942 KF_bpf_iter_css_task_new,
ac9f0605
KKD
10943};
10944
10945BTF_SET_START(special_kfunc_set)
10946BTF_ID(func, bpf_obj_new_impl)
10947BTF_ID(func, bpf_obj_drop_impl)
7c50b1cb 10948BTF_ID(func, bpf_refcount_acquire_impl)
d2dcc67d
DM
10949BTF_ID(func, bpf_list_push_front_impl)
10950BTF_ID(func, bpf_list_push_back_impl)
8cab76ec
KKD
10951BTF_ID(func, bpf_list_pop_front)
10952BTF_ID(func, bpf_list_pop_back)
fd264ca0 10953BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 10954BTF_ID(func, bpf_rdonly_cast)
bd1279ae 10955BTF_ID(func, bpf_rbtree_remove)
d2dcc67d 10956BTF_ID(func, bpf_rbtree_add_impl)
bd1279ae 10957BTF_ID(func, bpf_rbtree_first)
b5964b96 10958BTF_ID(func, bpf_dynptr_from_skb)
05421aec 10959BTF_ID(func, bpf_dynptr_from_xdp)
66e3a13e
JK
10960BTF_ID(func, bpf_dynptr_slice)
10961BTF_ID(func, bpf_dynptr_slice_rdwr)
361f129f 10962BTF_ID(func, bpf_dynptr_clone)
36d8bdf7
YS
10963BTF_ID(func, bpf_percpu_obj_new_impl)
10964BTF_ID(func, bpf_percpu_obj_drop_impl)
f18b03fa 10965BTF_ID(func, bpf_throw)
05670f81 10966#ifdef CONFIG_CGROUPS
9c66dc94 10967BTF_ID(func, bpf_iter_css_task_new)
05670f81 10968#endif
ac9f0605
KKD
10969BTF_SET_END(special_kfunc_set)
10970
10971BTF_ID_LIST(special_kfunc_list)
10972BTF_ID(func, bpf_obj_new_impl)
10973BTF_ID(func, bpf_obj_drop_impl)
7c50b1cb 10974BTF_ID(func, bpf_refcount_acquire_impl)
d2dcc67d
DM
10975BTF_ID(func, bpf_list_push_front_impl)
10976BTF_ID(func, bpf_list_push_back_impl)
8cab76ec
KKD
10977BTF_ID(func, bpf_list_pop_front)
10978BTF_ID(func, bpf_list_pop_back)
fd264ca0 10979BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 10980BTF_ID(func, bpf_rdonly_cast)
9bb00b28
YS
10981BTF_ID(func, bpf_rcu_read_lock)
10982BTF_ID(func, bpf_rcu_read_unlock)
bd1279ae 10983BTF_ID(func, bpf_rbtree_remove)
d2dcc67d 10984BTF_ID(func, bpf_rbtree_add_impl)
bd1279ae 10985BTF_ID(func, bpf_rbtree_first)
b5964b96 10986BTF_ID(func, bpf_dynptr_from_skb)
05421aec 10987BTF_ID(func, bpf_dynptr_from_xdp)
66e3a13e
JK
10988BTF_ID(func, bpf_dynptr_slice)
10989BTF_ID(func, bpf_dynptr_slice_rdwr)
361f129f 10990BTF_ID(func, bpf_dynptr_clone)
36d8bdf7
YS
10991BTF_ID(func, bpf_percpu_obj_new_impl)
10992BTF_ID(func, bpf_percpu_obj_drop_impl)
f18b03fa 10993BTF_ID(func, bpf_throw)
05670f81 10994#ifdef CONFIG_CGROUPS
9c66dc94 10995BTF_ID(func, bpf_iter_css_task_new)
05670f81
MB
10996#else
10997BTF_ID_UNUSED
10998#endif
9bb00b28 10999
7793fc3b
DM
11000static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11001{
11002 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11003 meta->arg_owning_ref) {
11004 return false;
11005 }
11006
11007 return meta->kfunc_flags & KF_RET_NULL;
11008}
11009
9bb00b28
YS
11010static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11011{
11012 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11013}
11014
11015static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11016{
11017 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11018}
ac9f0605 11019
00b85860
KKD
11020static enum kfunc_ptr_arg_type
11021get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11022 struct bpf_kfunc_call_arg_meta *meta,
11023 const struct btf_type *t, const struct btf_type *ref_t,
11024 const char *ref_tname, const struct btf_param *args,
11025 int argno, int nargs)
11026{
11027 u32 regno = argno + 1;
11028 struct bpf_reg_state *regs = cur_regs(env);
11029 struct bpf_reg_state *reg = &regs[regno];
11030 bool arg_mem_size = false;
11031
fd264ca0
YS
11032 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11033 return KF_ARG_PTR_TO_CTX;
11034
00b85860
KKD
11035 /* In this function, we verify the kfunc's BTF as per the argument type,
11036 * leaving the rest of the verification with respect to the register
11037 * type to our caller. When a set of conditions hold in the BTF type of
11038 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11039 */
11040 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11041 return KF_ARG_PTR_TO_CTX;
11042
ac9f0605
KKD
11043 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11044 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11045
7c50b1cb
DM
11046 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11047 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
00b85860
KKD
11048
11049 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11050 return KF_ARG_PTR_TO_DYNPTR;
11051
06accc87
AN
11052 if (is_kfunc_arg_iter(meta, argno))
11053 return KF_ARG_PTR_TO_ITER;
11054
8cab76ec
KKD
11055 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11056 return KF_ARG_PTR_TO_LIST_HEAD;
11057
11058 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11059 return KF_ARG_PTR_TO_LIST_NODE;
11060
cd6791b4
DM
11061 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11062 return KF_ARG_PTR_TO_RB_ROOT;
11063
11064 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11065 return KF_ARG_PTR_TO_RB_NODE;
11066
00b85860
KKD
11067 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11068 if (!btf_type_is_struct(ref_t)) {
11069 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11070 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11071 return -EINVAL;
11072 }
11073 return KF_ARG_PTR_TO_BTF_ID;
11074 }
11075
5d92ddc3
DM
11076 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11077 return KF_ARG_PTR_TO_CALLBACK;
11078
cb3ecf79
CZ
11079 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11080 return KF_ARG_PTR_TO_NULL;
66e3a13e
JK
11081
11082 if (argno + 1 < nargs &&
11083 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11084 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
00b85860
KKD
11085 arg_mem_size = true;
11086
11087 /* This is the catch all argument type of register types supported by
11088 * check_helper_mem_access. However, we only allow when argument type is
11089 * pointer to scalar, or struct composed (recursively) of scalars. When
11090 * arg_mem_size is true, the pointer can be void *.
11091 */
11092 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11093 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11094 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11095 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11096 return -EINVAL;
11097 }
11098 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11099}
11100
11101static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11102 struct bpf_reg_state *reg,
11103 const struct btf_type *ref_t,
11104 const char *ref_tname, u32 ref_id,
11105 struct bpf_kfunc_call_arg_meta *meta,
11106 int argno)
11107{
11108 const struct btf_type *reg_ref_t;
11109 bool strict_type_match = false;
11110 const struct btf *reg_btf;
11111 const char *reg_ref_tname;
11112 u32 reg_ref_id;
11113
3f00c523 11114 if (base_type(reg->type) == PTR_TO_BTF_ID) {
00b85860
KKD
11115 reg_btf = reg->btf;
11116 reg_ref_id = reg->btf_id;
11117 } else {
11118 reg_btf = btf_vmlinux;
11119 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11120 }
11121
b613d335
DV
11122 /* Enforce strict type matching for calls to kfuncs that are acquiring
11123 * or releasing a reference, or are no-cast aliases. We do _not_
11124 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11125 * as we want to enable BPF programs to pass types that are bitwise
11126 * equivalent without forcing them to explicitly cast with something
11127 * like bpf_cast_to_kern_ctx().
11128 *
11129 * For example, say we had a type like the following:
11130 *
11131 * struct bpf_cpumask {
11132 * cpumask_t cpumask;
11133 * refcount_t usage;
11134 * };
11135 *
11136 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11137 * to a struct cpumask, so it would be safe to pass a struct
11138 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11139 *
11140 * The philosophy here is similar to how we allow scalars of different
11141 * types to be passed to kfuncs as long as the size is the same. The
11142 * only difference here is that we're simply allowing
11143 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11144 * resolve types.
11145 */
11146 if (is_kfunc_acquire(meta) ||
11147 (is_kfunc_release(meta) && reg->ref_obj_id) ||
11148 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
00b85860
KKD
11149 strict_type_match = true;
11150
b613d335
DV
11151 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11152
00b85860
KKD
11153 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11154 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11155 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11156 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11157 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11158 btf_type_str(reg_ref_t), reg_ref_tname);
11159 return -EINVAL;
11160 }
11161 return 0;
11162}
11163
6a3cd331 11164static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
534e86bc 11165{
6a3cd331 11166 struct bpf_verifier_state *state = env->cur_state;
0816b8c6 11167 struct btf_record *rec = reg_btf_record(reg);
6a3cd331
DM
11168
11169 if (!state->active_lock.ptr) {
11170 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11171 return -EFAULT;
11172 }
11173
11174 if (type_flag(reg->type) & NON_OWN_REF) {
11175 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11176 return -EFAULT;
11177 }
11178
11179 reg->type |= NON_OWN_REF;
0816b8c6
DM
11180 if (rec->refcount_off >= 0)
11181 reg->type |= MEM_RCU;
11182
6a3cd331
DM
11183 return 0;
11184}
11185
11186static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11187{
11188 struct bpf_func_state *state, *unused;
534e86bc
KKD
11189 struct bpf_reg_state *reg;
11190 int i;
11191
6a3cd331
DM
11192 state = cur_func(env);
11193
534e86bc 11194 if (!ref_obj_id) {
6a3cd331
DM
11195 verbose(env, "verifier internal error: ref_obj_id is zero for "
11196 "owning -> non-owning conversion\n");
534e86bc
KKD
11197 return -EFAULT;
11198 }
6a3cd331 11199
534e86bc 11200 for (i = 0; i < state->acquired_refs; i++) {
6a3cd331
DM
11201 if (state->refs[i].id != ref_obj_id)
11202 continue;
11203
11204 /* Clear ref_obj_id here so release_reference doesn't clobber
11205 * the whole reg
11206 */
11207 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11208 if (reg->ref_obj_id == ref_obj_id) {
11209 reg->ref_obj_id = 0;
11210 ref_set_non_owning(env, reg);
534e86bc 11211 }
6a3cd331
DM
11212 }));
11213 return 0;
534e86bc 11214 }
6a3cd331 11215
534e86bc
KKD
11216 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11217 return -EFAULT;
11218}
11219
8cab76ec
KKD
11220/* Implementation details:
11221 *
11222 * Each register points to some region of memory, which we define as an
11223 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11224 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11225 * allocation. The lock and the data it protects are colocated in the same
11226 * memory region.
11227 *
11228 * Hence, everytime a register holds a pointer value pointing to such
11229 * allocation, the verifier preserves a unique reg->id for it.
11230 *
11231 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11232 * bpf_spin_lock is called.
11233 *
11234 * To enable this, lock state in the verifier captures two values:
11235 * active_lock.ptr = Register's type specific pointer
11236 * active_lock.id = A unique ID for each register pointer value
11237 *
11238 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11239 * supported register types.
11240 *
11241 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11242 * allocated objects is the reg->btf pointer.
11243 *
11244 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11245 * can establish the provenance of the map value statically for each distinct
11246 * lookup into such maps. They always contain a single map value hence unique
11247 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11248 *
11249 * So, in case of global variables, they use array maps with max_entries = 1,
11250 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11251 * into the same map value as max_entries is 1, as described above).
11252 *
11253 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11254 * outer map pointer (in verifier context), but each lookup into an inner map
11255 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11256 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11257 * will get different reg->id assigned to each lookup, hence different
11258 * active_lock.id.
11259 *
11260 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11261 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11262 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11263 */
11264static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11265{
11266 void *ptr;
11267 u32 id;
11268
11269 switch ((int)reg->type) {
11270 case PTR_TO_MAP_VALUE:
11271 ptr = reg->map_ptr;
11272 break;
11273 case PTR_TO_BTF_ID | MEM_ALLOC:
11274 ptr = reg->btf;
11275 break;
11276 default:
11277 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11278 return -EFAULT;
11279 }
11280 id = reg->id;
11281
11282 if (!env->cur_state->active_lock.ptr)
11283 return -EINVAL;
11284 if (env->cur_state->active_lock.ptr != ptr ||
11285 env->cur_state->active_lock.id != id) {
11286 verbose(env, "held lock and object are not in the same allocation\n");
11287 return -EINVAL;
11288 }
11289 return 0;
11290}
11291
11292static bool is_bpf_list_api_kfunc(u32 btf_id)
11293{
d2dcc67d
DM
11294 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11295 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
8cab76ec
KKD
11296 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11297 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11298}
11299
cd6791b4
DM
11300static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11301{
d2dcc67d 11302 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
cd6791b4
DM
11303 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11304 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11305}
11306
11307static bool is_bpf_graph_api_kfunc(u32 btf_id)
11308{
7c50b1cb
DM
11309 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11310 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
cd6791b4
DM
11311}
11312
ab5cfac1 11313static bool is_sync_callback_calling_kfunc(u32 btf_id)
5d92ddc3 11314{
d2dcc67d 11315 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
5d92ddc3
DM
11316}
11317
f18b03fa
KKD
11318static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11319{
11320 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11321 insn->imm == special_kfunc_list[KF_bpf_throw];
11322}
11323
5d92ddc3
DM
11324static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11325{
11326 return is_bpf_rbtree_api_kfunc(btf_id);
11327}
11328
cd6791b4
DM
11329static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11330 enum btf_field_type head_field_type,
11331 u32 kfunc_btf_id)
11332{
11333 bool ret;
11334
11335 switch (head_field_type) {
11336 case BPF_LIST_HEAD:
11337 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11338 break;
11339 case BPF_RB_ROOT:
11340 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11341 break;
11342 default:
11343 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11344 btf_field_type_name(head_field_type));
11345 return false;
11346 }
11347
11348 if (!ret)
11349 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11350 btf_field_type_name(head_field_type));
11351 return ret;
11352}
11353
11354static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11355 enum btf_field_type node_field_type,
11356 u32 kfunc_btf_id)
8cab76ec 11357{
cd6791b4
DM
11358 bool ret;
11359
11360 switch (node_field_type) {
11361 case BPF_LIST_NODE:
d2dcc67d
DM
11362 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11363 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
cd6791b4
DM
11364 break;
11365 case BPF_RB_NODE:
11366 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
d2dcc67d 11367 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
cd6791b4
DM
11368 break;
11369 default:
11370 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11371 btf_field_type_name(node_field_type));
11372 return false;
11373 }
11374
11375 if (!ret)
11376 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11377 btf_field_type_name(node_field_type));
11378 return ret;
11379}
11380
11381static int
11382__process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11383 struct bpf_reg_state *reg, u32 regno,
11384 struct bpf_kfunc_call_arg_meta *meta,
11385 enum btf_field_type head_field_type,
11386 struct btf_field **head_field)
11387{
11388 const char *head_type_name;
8cab76ec
KKD
11389 struct btf_field *field;
11390 struct btf_record *rec;
cd6791b4 11391 u32 head_off;
8cab76ec 11392
cd6791b4
DM
11393 if (meta->btf != btf_vmlinux) {
11394 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
8cab76ec
KKD
11395 return -EFAULT;
11396 }
11397
cd6791b4
DM
11398 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11399 return -EFAULT;
11400
11401 head_type_name = btf_field_type_name(head_field_type);
8cab76ec
KKD
11402 if (!tnum_is_const(reg->var_off)) {
11403 verbose(env,
cd6791b4
DM
11404 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11405 regno, head_type_name);
8cab76ec
KKD
11406 return -EINVAL;
11407 }
11408
11409 rec = reg_btf_record(reg);
cd6791b4
DM
11410 head_off = reg->off + reg->var_off.value;
11411 field = btf_record_find(rec, head_off, head_field_type);
8cab76ec 11412 if (!field) {
cd6791b4 11413 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
8cab76ec
KKD
11414 return -EINVAL;
11415 }
11416
11417 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11418 if (check_reg_allocation_locked(env, reg)) {
cd6791b4
DM
11419 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11420 rec->spin_lock_off, head_type_name);
8cab76ec
KKD
11421 return -EINVAL;
11422 }
11423
cd6791b4
DM
11424 if (*head_field) {
11425 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
8cab76ec
KKD
11426 return -EFAULT;
11427 }
cd6791b4 11428 *head_field = field;
8cab76ec
KKD
11429 return 0;
11430}
11431
cd6791b4 11432static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8cab76ec
KKD
11433 struct bpf_reg_state *reg, u32 regno,
11434 struct bpf_kfunc_call_arg_meta *meta)
11435{
cd6791b4
DM
11436 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11437 &meta->arg_list_head.field);
11438}
11439
11440static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11441 struct bpf_reg_state *reg, u32 regno,
11442 struct bpf_kfunc_call_arg_meta *meta)
11443{
11444 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11445 &meta->arg_rbtree_root.field);
11446}
11447
11448static int
11449__process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11450 struct bpf_reg_state *reg, u32 regno,
11451 struct bpf_kfunc_call_arg_meta *meta,
11452 enum btf_field_type head_field_type,
11453 enum btf_field_type node_field_type,
11454 struct btf_field **node_field)
11455{
11456 const char *node_type_name;
8cab76ec
KKD
11457 const struct btf_type *et, *t;
11458 struct btf_field *field;
cd6791b4 11459 u32 node_off;
8cab76ec 11460
cd6791b4
DM
11461 if (meta->btf != btf_vmlinux) {
11462 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
8cab76ec
KKD
11463 return -EFAULT;
11464 }
11465
cd6791b4
DM
11466 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11467 return -EFAULT;
11468
11469 node_type_name = btf_field_type_name(node_field_type);
8cab76ec
KKD
11470 if (!tnum_is_const(reg->var_off)) {
11471 verbose(env,
cd6791b4
DM
11472 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11473 regno, node_type_name);
8cab76ec
KKD
11474 return -EINVAL;
11475 }
11476
cd6791b4
DM
11477 node_off = reg->off + reg->var_off.value;
11478 field = reg_find_field_offset(reg, node_off, node_field_type);
11479 if (!field || field->offset != node_off) {
11480 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
8cab76ec
KKD
11481 return -EINVAL;
11482 }
11483
cd6791b4 11484 field = *node_field;
8cab76ec 11485
30465003 11486 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
8cab76ec 11487 t = btf_type_by_id(reg->btf, reg->btf_id);
30465003
DM
11488 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11489 field->graph_root.value_btf_id, true)) {
cd6791b4 11490 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
8cab76ec 11491 "in struct %s, but arg is at offset=%d in struct %s\n",
cd6791b4
DM
11492 btf_field_type_name(head_field_type),
11493 btf_field_type_name(node_field_type),
30465003
DM
11494 field->graph_root.node_offset,
11495 btf_name_by_offset(field->graph_root.btf, et->name_off),
cd6791b4 11496 node_off, btf_name_by_offset(reg->btf, t->name_off));
8cab76ec
KKD
11497 return -EINVAL;
11498 }
2140a6e3
DM
11499 meta->arg_btf = reg->btf;
11500 meta->arg_btf_id = reg->btf_id;
8cab76ec 11501
cd6791b4
DM
11502 if (node_off != field->graph_root.node_offset) {
11503 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11504 node_off, btf_field_type_name(node_field_type),
11505 field->graph_root.node_offset,
30465003 11506 btf_name_by_offset(field->graph_root.btf, et->name_off));
8cab76ec
KKD
11507 return -EINVAL;
11508 }
6a3cd331
DM
11509
11510 return 0;
8cab76ec
KKD
11511}
11512
cd6791b4
DM
11513static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11514 struct bpf_reg_state *reg, u32 regno,
11515 struct bpf_kfunc_call_arg_meta *meta)
11516{
11517 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11518 BPF_LIST_HEAD, BPF_LIST_NODE,
11519 &meta->arg_list_head.field);
11520}
11521
11522static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11523 struct bpf_reg_state *reg, u32 regno,
11524 struct bpf_kfunc_call_arg_meta *meta)
11525{
11526 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11527 BPF_RB_ROOT, BPF_RB_NODE,
11528 &meta->arg_rbtree_root.field);
11529}
11530
3091b667
CZ
11531/*
11532 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11533 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11534 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11535 * them can only be attached to some specific hook points.
11536 */
9c66dc94
CZ
11537static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11538{
11539 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11540
11541 switch (prog_type) {
11542 case BPF_PROG_TYPE_LSM:
11543 return true;
3091b667
CZ
11544 case BPF_PROG_TYPE_TRACING:
11545 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11546 return true;
11547 fallthrough;
9c66dc94 11548 default:
3091b667 11549 return env->prog->aux->sleepable;
9c66dc94
CZ
11550 }
11551}
11552
1d18feb2
JK
11553static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11554 int insn_idx)
00b85860
KKD
11555{
11556 const char *func_name = meta->func_name, *ref_tname;
11557 const struct btf *btf = meta->btf;
11558 const struct btf_param *args;
7c50b1cb 11559 struct btf_record *rec;
00b85860
KKD
11560 u32 i, nargs;
11561 int ret;
11562
11563 args = (const struct btf_param *)(meta->func_proto + 1);
11564 nargs = btf_type_vlen(meta->func_proto);
11565 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11566 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11567 MAX_BPF_FUNC_REG_ARGS);
11568 return -EINVAL;
11569 }
11570
11571 /* Check that BTF function arguments match actual types that the
11572 * verifier sees.
11573 */
11574 for (i = 0; i < nargs; i++) {
11575 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11576 const struct btf_type *t, *ref_t, *resolve_ret;
11577 enum bpf_arg_type arg_type = ARG_DONTCARE;
11578 u32 regno = i + 1, ref_id, type_size;
11579 bool is_ret_buf_sz = false;
11580 int kf_arg_type;
11581
11582 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
958cf2e2
KKD
11583
11584 if (is_kfunc_arg_ignore(btf, &args[i]))
11585 continue;
11586
00b85860
KKD
11587 if (btf_type_is_scalar(t)) {
11588 if (reg->type != SCALAR_VALUE) {
11589 verbose(env, "R%d is not a scalar\n", regno);
11590 return -EINVAL;
11591 }
a50388db
KKD
11592
11593 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11594 if (meta->arg_constant.found) {
11595 verbose(env, "verifier internal error: only one constant argument permitted\n");
11596 return -EFAULT;
11597 }
11598 if (!tnum_is_const(reg->var_off)) {
11599 verbose(env, "R%d must be a known constant\n", regno);
11600 return -EINVAL;
11601 }
11602 ret = mark_chain_precision(env, regno);
11603 if (ret < 0)
11604 return ret;
11605 meta->arg_constant.found = true;
11606 meta->arg_constant.value = reg->var_off.value;
11607 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
00b85860
KKD
11608 meta->r0_rdonly = true;
11609 is_ret_buf_sz = true;
11610 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11611 is_ret_buf_sz = true;
11612 }
11613
11614 if (is_ret_buf_sz) {
11615 if (meta->r0_size) {
11616 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11617 return -EINVAL;
11618 }
11619
11620 if (!tnum_is_const(reg->var_off)) {
11621 verbose(env, "R%d is not a const\n", regno);
11622 return -EINVAL;
11623 }
11624
11625 meta->r0_size = reg->var_off.value;
11626 ret = mark_chain_precision(env, regno);
11627 if (ret)
11628 return ret;
11629 }
11630 continue;
11631 }
11632
11633 if (!btf_type_is_ptr(t)) {
11634 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11635 return -EINVAL;
11636 }
11637
20c09d92 11638 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
cb3ecf79
CZ
11639 (register_is_null(reg) || type_may_be_null(reg->type)) &&
11640 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
caf713c3
DV
11641 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11642 return -EACCES;
11643 }
11644
00b85860
KKD
11645 if (reg->ref_obj_id) {
11646 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11647 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11648 regno, reg->ref_obj_id,
11649 meta->ref_obj_id);
11650 return -EFAULT;
11651 }
11652 meta->ref_obj_id = reg->ref_obj_id;
11653 if (is_kfunc_release(meta))
11654 meta->release_regno = regno;
11655 }
11656
11657 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11658 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11659
11660 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11661 if (kf_arg_type < 0)
11662 return kf_arg_type;
11663
11664 switch (kf_arg_type) {
cb3ecf79
CZ
11665 case KF_ARG_PTR_TO_NULL:
11666 continue;
ac9f0605 11667 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
00b85860 11668 case KF_ARG_PTR_TO_BTF_ID:
fca1aa75 11669 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
00b85860 11670 break;
3f00c523
DV
11671
11672 if (!is_trusted_reg(reg)) {
fca1aa75
YS
11673 if (!is_kfunc_rcu(meta)) {
11674 verbose(env, "R%d must be referenced or trusted\n", regno);
11675 return -EINVAL;
11676 }
11677 if (!is_rcu_reg(reg)) {
11678 verbose(env, "R%d must be a rcu pointer\n", regno);
11679 return -EINVAL;
11680 }
00b85860 11681 }
fca1aa75 11682
00b85860
KKD
11683 fallthrough;
11684 case KF_ARG_PTR_TO_CTX:
11685 /* Trusted arguments have the same offset checks as release arguments */
11686 arg_type |= OBJ_RELEASE;
11687 break;
00b85860 11688 case KF_ARG_PTR_TO_DYNPTR:
06accc87 11689 case KF_ARG_PTR_TO_ITER:
8cab76ec
KKD
11690 case KF_ARG_PTR_TO_LIST_HEAD:
11691 case KF_ARG_PTR_TO_LIST_NODE:
cd6791b4
DM
11692 case KF_ARG_PTR_TO_RB_ROOT:
11693 case KF_ARG_PTR_TO_RB_NODE:
00b85860
KKD
11694 case KF_ARG_PTR_TO_MEM:
11695 case KF_ARG_PTR_TO_MEM_SIZE:
5d92ddc3 11696 case KF_ARG_PTR_TO_CALLBACK:
7c50b1cb 11697 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
00b85860
KKD
11698 /* Trusted by default */
11699 break;
11700 default:
11701 WARN_ON_ONCE(1);
11702 return -EFAULT;
11703 }
11704
11705 if (is_kfunc_release(meta) && reg->ref_obj_id)
11706 arg_type |= OBJ_RELEASE;
11707 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11708 if (ret < 0)
11709 return ret;
11710
11711 switch (kf_arg_type) {
11712 case KF_ARG_PTR_TO_CTX:
11713 if (reg->type != PTR_TO_CTX) {
11714 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11715 return -EINVAL;
11716 }
fd264ca0
YS
11717
11718 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11719 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11720 if (ret < 0)
11721 return -EINVAL;
11722 meta->ret_btf_id = ret;
11723 }
00b85860 11724 break;
ac9f0605 11725 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
36d8bdf7
YS
11726 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11727 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11728 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11729 return -EINVAL;
11730 }
11731 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11732 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11733 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11734 return -EINVAL;
11735 }
11736 } else {
ac9f0605
KKD
11737 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11738 return -EINVAL;
11739 }
11740 if (!reg->ref_obj_id) {
11741 verbose(env, "allocated object must be referenced\n");
11742 return -EINVAL;
11743 }
36d8bdf7 11744 if (meta->btf == btf_vmlinux) {
4d585f48
DM
11745 meta->arg_btf = reg->btf;
11746 meta->arg_btf_id = reg->btf_id;
ac9f0605
KKD
11747 }
11748 break;
00b85860 11749 case KF_ARG_PTR_TO_DYNPTR:
d96d937d
JK
11750 {
11751 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
361f129f 11752 int clone_ref_obj_id = 0;
d96d937d 11753
6b75bd3d 11754 if (reg->type != PTR_TO_STACK &&
27060531 11755 reg->type != CONST_PTR_TO_DYNPTR) {
6b75bd3d 11756 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
00b85860
KKD
11757 return -EINVAL;
11758 }
11759
d96d937d
JK
11760 if (reg->type == CONST_PTR_TO_DYNPTR)
11761 dynptr_arg_type |= MEM_RDONLY;
11762
11763 if (is_kfunc_arg_uninit(btf, &args[i]))
11764 dynptr_arg_type |= MEM_UNINIT;
11765
361f129f 11766 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
b5964b96 11767 dynptr_arg_type |= DYNPTR_TYPE_SKB;
361f129f 11768 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
05421aec 11769 dynptr_arg_type |= DYNPTR_TYPE_XDP;
361f129f
JK
11770 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11771 (dynptr_arg_type & MEM_UNINIT)) {
11772 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11773
11774 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11775 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11776 return -EFAULT;
11777 }
11778
11779 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11780 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11781 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11782 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11783 return -EFAULT;
11784 }
11785 }
b5964b96 11786
361f129f 11787 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
6b75bd3d
KKD
11788 if (ret < 0)
11789 return ret;
66e3a13e
JK
11790
11791 if (!(dynptr_arg_type & MEM_UNINIT)) {
11792 int id = dynptr_id(env, reg);
11793
11794 if (id < 0) {
11795 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11796 return id;
11797 }
11798 meta->initialized_dynptr.id = id;
11799 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
361f129f 11800 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
66e3a13e
JK
11801 }
11802
00b85860 11803 break;
d96d937d 11804 }
06accc87 11805 case KF_ARG_PTR_TO_ITER:
9c66dc94
CZ
11806 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11807 if (!check_css_task_iter_allowlist(env)) {
3091b667 11808 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
9c66dc94
CZ
11809 return -EINVAL;
11810 }
11811 }
06accc87
AN
11812 ret = process_iter_arg(env, regno, insn_idx, meta);
11813 if (ret < 0)
11814 return ret;
11815 break;
8cab76ec
KKD
11816 case KF_ARG_PTR_TO_LIST_HEAD:
11817 if (reg->type != PTR_TO_MAP_VALUE &&
11818 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11819 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11820 return -EINVAL;
11821 }
11822 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11823 verbose(env, "allocated object must be referenced\n");
11824 return -EINVAL;
11825 }
11826 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11827 if (ret < 0)
11828 return ret;
11829 break;
cd6791b4
DM
11830 case KF_ARG_PTR_TO_RB_ROOT:
11831 if (reg->type != PTR_TO_MAP_VALUE &&
11832 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11833 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11834 return -EINVAL;
11835 }
11836 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11837 verbose(env, "allocated object must be referenced\n");
11838 return -EINVAL;
11839 }
11840 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11841 if (ret < 0)
11842 return ret;
11843 break;
8cab76ec
KKD
11844 case KF_ARG_PTR_TO_LIST_NODE:
11845 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11846 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11847 return -EINVAL;
11848 }
11849 if (!reg->ref_obj_id) {
11850 verbose(env, "allocated object must be referenced\n");
11851 return -EINVAL;
11852 }
11853 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11854 if (ret < 0)
11855 return ret;
11856 break;
cd6791b4 11857 case KF_ARG_PTR_TO_RB_NODE:
a40d3632
DM
11858 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11859 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11860 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11861 return -EINVAL;
11862 }
11863 if (in_rbtree_lock_required_cb(env)) {
11864 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11865 return -EINVAL;
11866 }
11867 } else {
11868 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11869 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11870 return -EINVAL;
11871 }
11872 if (!reg->ref_obj_id) {
11873 verbose(env, "allocated object must be referenced\n");
11874 return -EINVAL;
11875 }
cd6791b4 11876 }
a40d3632 11877
cd6791b4
DM
11878 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11879 if (ret < 0)
11880 return ret;
11881 break;
00b85860
KKD
11882 case KF_ARG_PTR_TO_BTF_ID:
11883 /* Only base_type is checked, further checks are done here */
3f00c523 11884 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
fca1aa75 11885 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
3f00c523
DV
11886 !reg2btf_ids[base_type(reg->type)]) {
11887 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11888 verbose(env, "expected %s or socket\n",
11889 reg_type_str(env, base_type(reg->type) |
11890 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
00b85860
KKD
11891 return -EINVAL;
11892 }
11893 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11894 if (ret < 0)
11895 return ret;
11896 break;
11897 case KF_ARG_PTR_TO_MEM:
11898 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11899 if (IS_ERR(resolve_ret)) {
11900 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11901 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11902 return -EINVAL;
11903 }
11904 ret = check_mem_reg(env, reg, regno, type_size);
11905 if (ret < 0)
11906 return ret;
11907 break;
11908 case KF_ARG_PTR_TO_MEM_SIZE:
66e3a13e 11909 {
3bda08b6
DR
11910 struct bpf_reg_state *buff_reg = &regs[regno];
11911 const struct btf_param *buff_arg = &args[i];
66e3a13e
JK
11912 struct bpf_reg_state *size_reg = &regs[regno + 1];
11913 const struct btf_param *size_arg = &args[i + 1];
11914
3bda08b6
DR
11915 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11916 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11917 if (ret < 0) {
11918 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11919 return ret;
11920 }
00b85860 11921 }
66e3a13e
JK
11922
11923 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11924 if (meta->arg_constant.found) {
11925 verbose(env, "verifier internal error: only one constant argument permitted\n");
11926 return -EFAULT;
11927 }
11928 if (!tnum_is_const(size_reg->var_off)) {
11929 verbose(env, "R%d must be a known constant\n", regno + 1);
11930 return -EINVAL;
11931 }
11932 meta->arg_constant.found = true;
11933 meta->arg_constant.value = size_reg->var_off.value;
11934 }
11935
11936 /* Skip next '__sz' or '__szk' argument */
00b85860
KKD
11937 i++;
11938 break;
66e3a13e 11939 }
5d92ddc3 11940 case KF_ARG_PTR_TO_CALLBACK:
06d686f7
KKD
11941 if (reg->type != PTR_TO_FUNC) {
11942 verbose(env, "arg%d expected pointer to func\n", i);
11943 return -EINVAL;
11944 }
5d92ddc3
DM
11945 meta->subprogno = reg->subprogno;
11946 break;
7c50b1cb 11947 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
7793fc3b 11948 if (!type_is_ptr_alloc_obj(reg->type)) {
7c50b1cb
DM
11949 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11950 return -EINVAL;
11951 }
7793fc3b
DM
11952 if (!type_is_non_owning_ref(reg->type))
11953 meta->arg_owning_ref = true;
7c50b1cb
DM
11954
11955 rec = reg_btf_record(reg);
11956 if (!rec) {
11957 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11958 return -EFAULT;
11959 }
11960
11961 if (rec->refcount_off < 0) {
11962 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11963 return -EINVAL;
11964 }
ba2464c8 11965
4d585f48
DM
11966 meta->arg_btf = reg->btf;
11967 meta->arg_btf_id = reg->btf_id;
7c50b1cb 11968 break;
00b85860
KKD
11969 }
11970 }
11971
11972 if (is_kfunc_release(meta) && !meta->release_regno) {
11973 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11974 func_name);
11975 return -EINVAL;
11976 }
11977
11978 return 0;
11979}
11980
07236eab
AN
11981static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11982 struct bpf_insn *insn,
11983 struct bpf_kfunc_call_arg_meta *meta,
11984 const char **kfunc_name)
e6ac2450 11985{
07236eab
AN
11986 const struct btf_type *func, *func_proto;
11987 u32 func_id, *kfunc_flags;
11988 const char *func_name;
2357672c 11989 struct btf *desc_btf;
e6ac2450 11990
07236eab
AN
11991 if (kfunc_name)
11992 *kfunc_name = NULL;
11993
a5d82727 11994 if (!insn->imm)
07236eab 11995 return -EINVAL;
a5d82727 11996
43bf0878 11997 desc_btf = find_kfunc_desc_btf(env, insn->off);
2357672c
KKD
11998 if (IS_ERR(desc_btf))
11999 return PTR_ERR(desc_btf);
12000
e6ac2450 12001 func_id = insn->imm;
2357672c
KKD
12002 func = btf_type_by_id(desc_btf, func_id);
12003 func_name = btf_name_by_offset(desc_btf, func->name_off);
07236eab
AN
12004 if (kfunc_name)
12005 *kfunc_name = func_name;
2357672c 12006 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450 12007
e924e80e 12008 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
a4703e31 12009 if (!kfunc_flags) {
e6ac2450
MKL
12010 return -EACCES;
12011 }
00b85860 12012
07236eab
AN
12013 memset(meta, 0, sizeof(*meta));
12014 meta->btf = desc_btf;
12015 meta->func_id = func_id;
12016 meta->kfunc_flags = *kfunc_flags;
12017 meta->func_proto = func_proto;
12018 meta->func_name = func_name;
12019
12020 return 0;
12021}
12022
a923819f
KKD
12023static int check_return_code(struct bpf_verifier_env *env, int regno);
12024
07236eab
AN
12025static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12026 int *insn_idx_p)
12027{
12028 const struct btf_type *t, *ptr_type;
12029 u32 i, nargs, ptr_type_id, release_ref_obj_id;
12030 struct bpf_reg_state *regs = cur_regs(env);
12031 const char *func_name, *ptr_type_name;
12032 bool sleepable, rcu_lock, rcu_unlock;
12033 struct bpf_kfunc_call_arg_meta meta;
12034 struct bpf_insn_aux_data *insn_aux;
12035 int err, insn_idx = *insn_idx_p;
12036 const struct btf_param *args;
12037 const struct btf_type *ret_t;
12038 struct btf *desc_btf;
12039
12040 /* skip for now, but return error when we find this in fixup_kfunc_call */
12041 if (!insn->imm)
12042 return 0;
12043
12044 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12045 if (err == -EACCES && func_name)
12046 verbose(env, "calling kernel function %s is not allowed\n", func_name);
12047 if (err)
12048 return err;
12049 desc_btf = meta.btf;
12050 insn_aux = &env->insn_aux_data[insn_idx];
00b85860 12051
06accc87
AN
12052 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12053
00b85860
KKD
12054 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12055 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
4dd48c6f
AS
12056 return -EACCES;
12057 }
12058
9bb00b28
YS
12059 sleepable = is_kfunc_sleepable(&meta);
12060 if (sleepable && !env->prog->aux->sleepable) {
00b85860
KKD
12061 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12062 return -EACCES;
12063 }
eb1f7f71 12064
ab5cfac1
EZ
12065 /* Check the arguments */
12066 err = check_kfunc_args(env, &meta, insn_idx);
12067 if (err < 0)
12068 return err;
12069
12070 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12071 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12072 set_rbtree_add_callback_state);
12073 if (err) {
12074 verbose(env, "kfunc %s#%d failed callback verification\n",
12075 func_name, meta.func_id);
12076 return err;
12077 }
12078 }
12079
9bb00b28
YS
12080 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12081 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9bb00b28
YS
12082
12083 if (env->cur_state->active_rcu_lock) {
12084 struct bpf_func_state *state;
12085 struct bpf_reg_state *reg;
dfab99df 12086 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
9bb00b28 12087
0816b8c6
DM
12088 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12089 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12090 return -EACCES;
12091 }
12092
9bb00b28
YS
12093 if (rcu_lock) {
12094 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12095 return -EINVAL;
12096 } else if (rcu_unlock) {
dfab99df 12097 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
9bb00b28 12098 if (reg->type & MEM_RCU) {
fca1aa75 12099 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9bb00b28
YS
12100 reg->type |= PTR_UNTRUSTED;
12101 }
12102 }));
12103 env->cur_state->active_rcu_lock = false;
12104 } else if (sleepable) {
12105 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12106 return -EACCES;
12107 }
12108 } else if (rcu_lock) {
12109 env->cur_state->active_rcu_lock = true;
12110 } else if (rcu_unlock) {
12111 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12112 return -EINVAL;
12113 }
12114
5c073f26 12115 /* In case of release function, we get register number of refcounted
00b85860 12116 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
5c073f26 12117 */
00b85860
KKD
12118 if (meta.release_regno) {
12119 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
5c073f26
KKD
12120 if (err) {
12121 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
07236eab 12122 func_name, meta.func_id);
5c073f26
KKD
12123 return err;
12124 }
12125 }
e6ac2450 12126
d2dcc67d
DM
12127 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12128 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12129 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
6a3cd331 12130 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
d2dcc67d 12131 insn_aux->insert_off = regs[BPF_REG_2].off;
2140a6e3 12132 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
6a3cd331
DM
12133 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12134 if (err) {
12135 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
07236eab 12136 func_name, meta.func_id);
6a3cd331
DM
12137 return err;
12138 }
12139
12140 err = release_reference(env, release_ref_obj_id);
12141 if (err) {
12142 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
07236eab 12143 func_name, meta.func_id);
6a3cd331
DM
12144 return err;
12145 }
12146 }
12147
f18b03fa
KKD
12148 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12149 if (!bpf_jit_supports_exceptions()) {
12150 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12151 func_name, meta.func_id);
12152 return -ENOTSUPP;
12153 }
12154 env->seen_exception = true;
a923819f
KKD
12155
12156 /* In the case of the default callback, the cookie value passed
12157 * to bpf_throw becomes the return value of the program.
12158 */
12159 if (!env->exception_callback_subprog) {
12160 err = check_return_code(env, BPF_REG_1);
12161 if (err < 0)
12162 return err;
12163 }
f18b03fa
KKD
12164 }
12165
e6ac2450
MKL
12166 for (i = 0; i < CALLER_SAVED_REGS; i++)
12167 mark_reg_not_init(env, regs, caller_saved[i]);
12168
12169 /* Check return type */
07236eab 12170 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
5c073f26 12171
00b85860 12172 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
958cf2e2 12173 /* Only exception is bpf_obj_new_impl */
7c50b1cb
DM
12174 if (meta.btf != btf_vmlinux ||
12175 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
36d8bdf7 12176 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
7c50b1cb 12177 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
958cf2e2
KKD
12178 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12179 return -EINVAL;
12180 }
5c073f26
KKD
12181 }
12182
e6ac2450
MKL
12183 if (btf_type_is_scalar(t)) {
12184 mark_reg_unknown(env, regs, BPF_REG_0);
12185 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12186 } else if (btf_type_is_ptr(t)) {
958cf2e2
KKD
12187 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12188
12189 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
36d8bdf7
YS
12190 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12191 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12192 struct btf_struct_meta *struct_meta;
958cf2e2
KKD
12193 struct btf *ret_btf;
12194 u32 ret_btf_id;
12195
36d8bdf7
YS
12196 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12197 return -ENOMEM;
12198
1fda5bb6
YS
12199 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12200 if (!bpf_global_percpu_ma_set) {
12201 mutex_lock(&bpf_percpu_ma_lock);
12202 if (!bpf_global_percpu_ma_set) {
12203 err = bpf_mem_alloc_init(&bpf_global_percpu_ma, 0, true);
12204 if (!err)
12205 bpf_global_percpu_ma_set = true;
12206 }
12207 mutex_unlock(&bpf_percpu_ma_lock);
12208 if (err)
12209 return err;
12210 }
12211 }
e181d3f1 12212
958cf2e2
KKD
12213 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12214 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12215 return -EINVAL;
12216 }
12217
12218 ret_btf = env->prog->aux->btf;
12219 ret_btf_id = meta.arg_constant.value;
12220
12221 /* This may be NULL due to user not supplying a BTF */
12222 if (!ret_btf) {
36d8bdf7 12223 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
958cf2e2
KKD
12224 return -EINVAL;
12225 }
12226
12227 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12228 if (!ret_t || !__btf_type_is_struct(ret_t)) {
36d8bdf7 12229 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
958cf2e2
KKD
12230 return -EINVAL;
12231 }
12232
36d8bdf7
YS
12233 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12234 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12235 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12236 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12237 return -EINVAL;
12238 }
12239
12240 if (struct_meta) {
12241 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12242 return -EINVAL;
12243 }
12244 }
12245
958cf2e2
KKD
12246 mark_reg_known_zero(env, regs, BPF_REG_0);
12247 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12248 regs[BPF_REG_0].btf = ret_btf;
12249 regs[BPF_REG_0].btf_id = ret_btf_id;
36d8bdf7
YS
12250 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12251 regs[BPF_REG_0].type |= MEM_PERCPU;
958cf2e2 12252
07236eab 12253 insn_aux->obj_new_size = ret_t->size;
36d8bdf7 12254 insn_aux->kptr_struct_meta = struct_meta;
7c50b1cb
DM
12255 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12256 mark_reg_known_zero(env, regs, BPF_REG_0);
12257 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
4d585f48
DM
12258 regs[BPF_REG_0].btf = meta.arg_btf;
12259 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
7c50b1cb
DM
12260
12261 insn_aux->kptr_struct_meta =
4d585f48
DM
12262 btf_find_struct_meta(meta.arg_btf,
12263 meta.arg_btf_id);
8cab76ec
KKD
12264 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12265 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12266 struct btf_field *field = meta.arg_list_head.field;
12267
a40d3632
DM
12268 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12269 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12270 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12271 struct btf_field *field = meta.arg_rbtree_root.field;
12272
12273 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
fd264ca0
YS
12274 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12275 mark_reg_known_zero(env, regs, BPF_REG_0);
12276 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12277 regs[BPF_REG_0].btf = desc_btf;
12278 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
a35b9af4
YS
12279 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12280 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12281 if (!ret_t || !btf_type_is_struct(ret_t)) {
12282 verbose(env,
12283 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12284 return -EINVAL;
12285 }
12286
12287 mark_reg_known_zero(env, regs, BPF_REG_0);
12288 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12289 regs[BPF_REG_0].btf = desc_btf;
12290 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
66e3a13e
JK
12291 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12292 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12293 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12294
12295 mark_reg_known_zero(env, regs, BPF_REG_0);
12296
12297 if (!meta.arg_constant.found) {
12298 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12299 return -EFAULT;
12300 }
12301
12302 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12303
12304 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12305 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12306
12307 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12308 regs[BPF_REG_0].type |= MEM_RDONLY;
12309 } else {
12310 /* this will set env->seen_direct_write to true */
12311 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12312 verbose(env, "the prog does not allow writes to packet data\n");
12313 return -EINVAL;
12314 }
12315 }
12316
12317 if (!meta.initialized_dynptr.id) {
12318 verbose(env, "verifier internal error: no dynptr id\n");
12319 return -EFAULT;
12320 }
12321 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12322
12323 /* we don't need to set BPF_REG_0's ref obj id
12324 * because packet slices are not refcounted (see
12325 * dynptr_type_refcounted)
12326 */
958cf2e2
KKD
12327 } else {
12328 verbose(env, "kernel function %s unhandled dynamic return type\n",
12329 meta.func_name);
12330 return -EFAULT;
12331 }
12332 } else if (!__btf_type_is_struct(ptr_type)) {
f4b4eee6
AN
12333 if (!meta.r0_size) {
12334 __u32 sz;
12335
12336 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12337 meta.r0_size = sz;
12338 meta.r0_rdonly = true;
12339 }
12340 }
eb1f7f71
BT
12341 if (!meta.r0_size) {
12342 ptr_type_name = btf_name_by_offset(desc_btf,
12343 ptr_type->name_off);
12344 verbose(env,
12345 "kernel function %s returns pointer type %s %s is not supported\n",
12346 func_name,
12347 btf_type_str(ptr_type),
12348 ptr_type_name);
12349 return -EINVAL;
12350 }
12351
12352 mark_reg_known_zero(env, regs, BPF_REG_0);
12353 regs[BPF_REG_0].type = PTR_TO_MEM;
12354 regs[BPF_REG_0].mem_size = meta.r0_size;
12355
12356 if (meta.r0_rdonly)
12357 regs[BPF_REG_0].type |= MEM_RDONLY;
12358
12359 /* Ensures we don't access the memory after a release_reference() */
12360 if (meta.ref_obj_id)
12361 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12362 } else {
12363 mark_reg_known_zero(env, regs, BPF_REG_0);
12364 regs[BPF_REG_0].btf = desc_btf;
12365 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12366 regs[BPF_REG_0].btf_id = ptr_type_id;
e6ac2450 12367 }
958cf2e2 12368
00b85860 12369 if (is_kfunc_ret_null(&meta)) {
5c073f26
KKD
12370 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12371 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12372 regs[BPF_REG_0].id = ++env->id_gen;
12373 }
e6ac2450 12374 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
00b85860 12375 if (is_kfunc_acquire(&meta)) {
5c073f26
KKD
12376 int id = acquire_reference_state(env, insn_idx);
12377
12378 if (id < 0)
12379 return id;
00b85860
KKD
12380 if (is_kfunc_ret_null(&meta))
12381 regs[BPF_REG_0].id = id;
5c073f26 12382 regs[BPF_REG_0].ref_obj_id = id;
a40d3632
DM
12383 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12384 ref_set_non_owning(env, &regs[BPF_REG_0]);
5c073f26 12385 }
a40d3632 12386
00b85860
KKD
12387 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12388 regs[BPF_REG_0].id = ++env->id_gen;
f6a6a5a9
DM
12389 } else if (btf_type_is_void(t)) {
12390 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
36d8bdf7
YS
12391 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12392 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
f6a6a5a9 12393 insn_aux->kptr_struct_meta =
4d585f48
DM
12394 btf_find_struct_meta(meta.arg_btf,
12395 meta.arg_btf_id);
f6a6a5a9
DM
12396 }
12397 }
12398 }
e6ac2450 12399
07236eab
AN
12400 nargs = btf_type_vlen(meta.func_proto);
12401 args = (const struct btf_param *)(meta.func_proto + 1);
e6ac2450
MKL
12402 for (i = 0; i < nargs; i++) {
12403 u32 regno = i + 1;
12404
2357672c 12405 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
e6ac2450
MKL
12406 if (btf_type_is_ptr(t))
12407 mark_btf_func_reg_size(env, regno, sizeof(void *));
12408 else
12409 /* scalar. ensured by btf_check_kfunc_arg_match() */
12410 mark_btf_func_reg_size(env, regno, t->size);
12411 }
12412
06accc87
AN
12413 if (is_iter_next_kfunc(&meta)) {
12414 err = process_iter_next_call(env, insn_idx, &meta);
12415 if (err)
12416 return err;
12417 }
12418
e6ac2450
MKL
12419 return 0;
12420}
12421
b03c9f9f
EC
12422static bool signed_add_overflows(s64 a, s64 b)
12423{
12424 /* Do the add in u64, where overflow is well-defined */
12425 s64 res = (s64)((u64)a + (u64)b);
12426
12427 if (b < 0)
12428 return res > a;
12429 return res < a;
12430}
12431
bc895e8b 12432static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
12433{
12434 /* Do the add in u32, where overflow is well-defined */
12435 s32 res = (s32)((u32)a + (u32)b);
12436
12437 if (b < 0)
12438 return res > a;
12439 return res < a;
12440}
12441
bc895e8b 12442static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
12443{
12444 /* Do the sub in u64, where overflow is well-defined */
12445 s64 res = (s64)((u64)a - (u64)b);
12446
12447 if (b < 0)
12448 return res < a;
12449 return res > a;
969bf05e
AS
12450}
12451
3f50f132
JF
12452static bool signed_sub32_overflows(s32 a, s32 b)
12453{
bc895e8b 12454 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
12455 s32 res = (s32)((u32)a - (u32)b);
12456
12457 if (b < 0)
12458 return res < a;
12459 return res > a;
12460}
12461
bb7f0f98
AS
12462static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12463 const struct bpf_reg_state *reg,
12464 enum bpf_reg_type type)
12465{
12466 bool known = tnum_is_const(reg->var_off);
12467 s64 val = reg->var_off.value;
12468 s64 smin = reg->smin_value;
12469
12470 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12471 verbose(env, "math between %s pointer and %lld is not allowed\n",
c25b2ae1 12472 reg_type_str(env, type), val);
bb7f0f98
AS
12473 return false;
12474 }
12475
12476 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12477 verbose(env, "%s pointer offset %d is not allowed\n",
c25b2ae1 12478 reg_type_str(env, type), reg->off);
bb7f0f98
AS
12479 return false;
12480 }
12481
12482 if (smin == S64_MIN) {
12483 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
c25b2ae1 12484 reg_type_str(env, type));
bb7f0f98
AS
12485 return false;
12486 }
12487
12488 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12489 verbose(env, "value %lld makes %s pointer be out of bounds\n",
c25b2ae1 12490 smin, reg_type_str(env, type));
bb7f0f98
AS
12491 return false;
12492 }
12493
12494 return true;
12495}
12496
a6aaece0
DB
12497enum {
12498 REASON_BOUNDS = -1,
12499 REASON_TYPE = -2,
12500 REASON_PATHS = -3,
12501 REASON_LIMIT = -4,
12502 REASON_STACK = -5,
12503};
12504
979d63d5 12505static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 12506 u32 *alu_limit, bool mask_to_left)
979d63d5 12507{
7fedb63a 12508 u32 max = 0, ptr_limit = 0;
979d63d5
DB
12509
12510 switch (ptr_reg->type) {
12511 case PTR_TO_STACK:
1b1597e6 12512 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
12513 * left direction, see BPF_REG_FP. Also, unknown scalar
12514 * offset where we would need to deal with min/max bounds is
12515 * currently prohibited for unprivileged.
1b1597e6
PK
12516 */
12517 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 12518 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 12519 break;
979d63d5 12520 case PTR_TO_MAP_VALUE:
1b1597e6 12521 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
12522 ptr_limit = (mask_to_left ?
12523 ptr_reg->smin_value :
12524 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 12525 break;
979d63d5 12526 default:
a6aaece0 12527 return REASON_TYPE;
979d63d5 12528 }
b658bbb8
DB
12529
12530 if (ptr_limit >= max)
a6aaece0 12531 return REASON_LIMIT;
b658bbb8
DB
12532 *alu_limit = ptr_limit;
12533 return 0;
979d63d5
DB
12534}
12535
d3bd7413
DB
12536static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12537 const struct bpf_insn *insn)
12538{
2c78ee89 12539 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
12540}
12541
12542static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12543 u32 alu_state, u32 alu_limit)
12544{
12545 /* If we arrived here from different branches with different
12546 * state or limits to sanitize, then this won't work.
12547 */
12548 if (aux->alu_state &&
12549 (aux->alu_state != alu_state ||
12550 aux->alu_limit != alu_limit))
a6aaece0 12551 return REASON_PATHS;
d3bd7413 12552
e6ac5933 12553 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
12554 aux->alu_state = alu_state;
12555 aux->alu_limit = alu_limit;
12556 return 0;
12557}
12558
12559static int sanitize_val_alu(struct bpf_verifier_env *env,
12560 struct bpf_insn *insn)
12561{
12562 struct bpf_insn_aux_data *aux = cur_aux(env);
12563
12564 if (can_skip_alu_sanitation(env, insn))
12565 return 0;
12566
12567 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12568}
12569
f5288193
DB
12570static bool sanitize_needed(u8 opcode)
12571{
12572 return opcode == BPF_ADD || opcode == BPF_SUB;
12573}
12574
3d0220f6
DB
12575struct bpf_sanitize_info {
12576 struct bpf_insn_aux_data aux;
bb01a1bb 12577 bool mask_to_left;
3d0220f6
DB
12578};
12579
9183671a
DB
12580static struct bpf_verifier_state *
12581sanitize_speculative_path(struct bpf_verifier_env *env,
12582 const struct bpf_insn *insn,
12583 u32 next_idx, u32 curr_idx)
12584{
12585 struct bpf_verifier_state *branch;
12586 struct bpf_reg_state *regs;
12587
12588 branch = push_stack(env, next_idx, curr_idx, true);
12589 if (branch && insn) {
12590 regs = branch->frame[branch->curframe]->regs;
12591 if (BPF_SRC(insn->code) == BPF_K) {
12592 mark_reg_unknown(env, regs, insn->dst_reg);
12593 } else if (BPF_SRC(insn->code) == BPF_X) {
12594 mark_reg_unknown(env, regs, insn->dst_reg);
12595 mark_reg_unknown(env, regs, insn->src_reg);
12596 }
12597 }
12598 return branch;
12599}
12600
979d63d5
DB
12601static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12602 struct bpf_insn *insn,
12603 const struct bpf_reg_state *ptr_reg,
6f55b2f2 12604 const struct bpf_reg_state *off_reg,
979d63d5 12605 struct bpf_reg_state *dst_reg,
3d0220f6 12606 struct bpf_sanitize_info *info,
7fedb63a 12607 const bool commit_window)
979d63d5 12608{
3d0220f6 12609 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 12610 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 12611 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 12612 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
12613 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12614 u8 opcode = BPF_OP(insn->code);
12615 u32 alu_state, alu_limit;
12616 struct bpf_reg_state tmp;
12617 bool ret;
f232326f 12618 int err;
979d63d5 12619
d3bd7413 12620 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
12621 return 0;
12622
12623 /* We already marked aux for masking from non-speculative
12624 * paths, thus we got here in the first place. We only care
12625 * to explore bad access from here.
12626 */
12627 if (vstate->speculative)
12628 goto do_sim;
12629
bb01a1bb
DB
12630 if (!commit_window) {
12631 if (!tnum_is_const(off_reg->var_off) &&
12632 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12633 return REASON_BOUNDS;
12634
12635 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12636 (opcode == BPF_SUB && !off_is_neg);
12637 }
12638
12639 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
12640 if (err < 0)
12641 return err;
12642
7fedb63a
DB
12643 if (commit_window) {
12644 /* In commit phase we narrow the masking window based on
12645 * the observed pointer move after the simulated operation.
12646 */
3d0220f6
DB
12647 alu_state = info->aux.alu_state;
12648 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
12649 } else {
12650 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 12651 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
12652 alu_state |= ptr_is_dst_reg ?
12653 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
e042aa53
DB
12654
12655 /* Limit pruning on unknown scalars to enable deep search for
12656 * potential masking differences from other program paths.
12657 */
12658 if (!off_is_imm)
12659 env->explore_alu_limits = true;
7fedb63a
DB
12660 }
12661
f232326f
PK
12662 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12663 if (err < 0)
12664 return err;
979d63d5 12665do_sim:
7fedb63a
DB
12666 /* If we're in commit phase, we're done here given we already
12667 * pushed the truncated dst_reg into the speculative verification
12668 * stack.
a7036191
DB
12669 *
12670 * Also, when register is a known constant, we rewrite register-based
12671 * operation to immediate-based, and thus do not need masking (and as
12672 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 12673 */
a7036191 12674 if (commit_window || off_is_imm)
7fedb63a
DB
12675 return 0;
12676
979d63d5
DB
12677 /* Simulate and find potential out-of-bounds access under
12678 * speculative execution from truncation as a result of
12679 * masking when off was not within expected range. If off
12680 * sits in dst, then we temporarily need to move ptr there
12681 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12682 * for cases where we use K-based arithmetic in one direction
12683 * and truncated reg-based in the other in order to explore
12684 * bad access.
12685 */
12686 if (!ptr_is_dst_reg) {
12687 tmp = *dst_reg;
71f656a5 12688 copy_register_state(dst_reg, ptr_reg);
979d63d5 12689 }
9183671a
DB
12690 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12691 env->insn_idx);
0803278b 12692 if (!ptr_is_dst_reg && ret)
979d63d5 12693 *dst_reg = tmp;
a6aaece0
DB
12694 return !ret ? REASON_STACK : 0;
12695}
12696
fe9a5ca7
DB
12697static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12698{
12699 struct bpf_verifier_state *vstate = env->cur_state;
12700
12701 /* If we simulate paths under speculation, we don't update the
12702 * insn as 'seen' such that when we verify unreachable paths in
12703 * the non-speculative domain, sanitize_dead_code() can still
12704 * rewrite/sanitize them.
12705 */
12706 if (!vstate->speculative)
12707 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12708}
12709
a6aaece0
DB
12710static int sanitize_err(struct bpf_verifier_env *env,
12711 const struct bpf_insn *insn, int reason,
12712 const struct bpf_reg_state *off_reg,
12713 const struct bpf_reg_state *dst_reg)
12714{
12715 static const char *err = "pointer arithmetic with it prohibited for !root";
12716 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12717 u32 dst = insn->dst_reg, src = insn->src_reg;
12718
12719 switch (reason) {
12720 case REASON_BOUNDS:
12721 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12722 off_reg == dst_reg ? dst : src, err);
12723 break;
12724 case REASON_TYPE:
12725 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12726 off_reg == dst_reg ? src : dst, err);
12727 break;
12728 case REASON_PATHS:
12729 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12730 dst, op, err);
12731 break;
12732 case REASON_LIMIT:
12733 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12734 dst, op, err);
12735 break;
12736 case REASON_STACK:
12737 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12738 dst, err);
12739 break;
12740 default:
12741 verbose(env, "verifier internal error: unknown reason (%d)\n",
12742 reason);
12743 break;
12744 }
12745
12746 return -EACCES;
979d63d5
DB
12747}
12748
01f810ac
AM
12749/* check that stack access falls within stack limits and that 'reg' doesn't
12750 * have a variable offset.
12751 *
12752 * Variable offset is prohibited for unprivileged mode for simplicity since it
12753 * requires corresponding support in Spectre masking for stack ALU. See also
12754 * retrieve_ptr_limit().
12755 *
12756 *
12757 * 'off' includes 'reg->off'.
12758 */
12759static int check_stack_access_for_ptr_arithmetic(
12760 struct bpf_verifier_env *env,
12761 int regno,
12762 const struct bpf_reg_state *reg,
12763 int off)
12764{
12765 if (!tnum_is_const(reg->var_off)) {
12766 char tn_buf[48];
12767
12768 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12769 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12770 regno, tn_buf, off);
12771 return -EACCES;
12772 }
12773
12774 if (off >= 0 || off < -MAX_BPF_STACK) {
12775 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12776 "prohibited for !root; off=%d\n", regno, off);
12777 return -EACCES;
12778 }
12779
12780 return 0;
12781}
12782
073815b7
DB
12783static int sanitize_check_bounds(struct bpf_verifier_env *env,
12784 const struct bpf_insn *insn,
12785 const struct bpf_reg_state *dst_reg)
12786{
12787 u32 dst = insn->dst_reg;
12788
12789 /* For unprivileged we require that resulting offset must be in bounds
12790 * in order to be able to sanitize access later on.
12791 */
12792 if (env->bypass_spec_v1)
12793 return 0;
12794
12795 switch (dst_reg->type) {
12796 case PTR_TO_STACK:
12797 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12798 dst_reg->off + dst_reg->var_off.value))
12799 return -EACCES;
12800 break;
12801 case PTR_TO_MAP_VALUE:
61df10c7 12802 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
073815b7
DB
12803 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12804 "prohibited for !root\n", dst);
12805 return -EACCES;
12806 }
12807 break;
12808 default:
12809 break;
12810 }
12811
12812 return 0;
12813}
01f810ac 12814
f1174f77 12815/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
12816 * Caller should also handle BPF_MOV case separately.
12817 * If we return -EACCES, caller may want to try again treating pointer as a
12818 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12819 */
12820static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12821 struct bpf_insn *insn,
12822 const struct bpf_reg_state *ptr_reg,
12823 const struct bpf_reg_state *off_reg)
969bf05e 12824{
f4d7e40a
AS
12825 struct bpf_verifier_state *vstate = env->cur_state;
12826 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12827 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 12828 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
12829 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12830 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12831 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12832 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 12833 struct bpf_sanitize_info info = {};
969bf05e 12834 u8 opcode = BPF_OP(insn->code);
24c109bb 12835 u32 dst = insn->dst_reg;
979d63d5 12836 int ret;
969bf05e 12837
f1174f77 12838 dst_reg = &regs[dst];
969bf05e 12839
6f16101e
DB
12840 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12841 smin_val > smax_val || umin_val > umax_val) {
12842 /* Taint dst register if offset had invalid bounds derived from
12843 * e.g. dead branches.
12844 */
f54c7898 12845 __mark_reg_unknown(env, dst_reg);
6f16101e 12846 return 0;
f1174f77
EC
12847 }
12848
12849 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12850 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
12851 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12852 __mark_reg_unknown(env, dst_reg);
12853 return 0;
12854 }
12855
82abbf8d
AS
12856 verbose(env,
12857 "R%d 32-bit pointer arithmetic prohibited\n",
12858 dst);
f1174f77 12859 return -EACCES;
969bf05e
AS
12860 }
12861
c25b2ae1 12862 if (ptr_reg->type & PTR_MAYBE_NULL) {
aad2eeaf 12863 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
c25b2ae1 12864 dst, reg_type_str(env, ptr_reg->type));
f1174f77 12865 return -EACCES;
c25b2ae1
HL
12866 }
12867
12868 switch (base_type(ptr_reg->type)) {
aad2eeaf 12869 case CONST_PTR_TO_MAP:
7c696732
YS
12870 /* smin_val represents the known value */
12871 if (known && smin_val == 0 && opcode == BPF_ADD)
12872 break;
8731745e 12873 fallthrough;
aad2eeaf 12874 case PTR_TO_PACKET_END:
c64b7983 12875 case PTR_TO_SOCKET:
46f8bc92 12876 case PTR_TO_SOCK_COMMON:
655a51e5 12877 case PTR_TO_TCP_SOCK:
fada7fdc 12878 case PTR_TO_XDP_SOCK:
aad2eeaf 12879 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
c25b2ae1 12880 dst, reg_type_str(env, ptr_reg->type));
f1174f77 12881 return -EACCES;
aad2eeaf
JS
12882 default:
12883 break;
f1174f77
EC
12884 }
12885
12886 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12887 * The id may be overwritten later if we create a new variable offset.
969bf05e 12888 */
f1174f77
EC
12889 dst_reg->type = ptr_reg->type;
12890 dst_reg->id = ptr_reg->id;
969bf05e 12891
bb7f0f98
AS
12892 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12893 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12894 return -EINVAL;
12895
3f50f132
JF
12896 /* pointer types do not carry 32-bit bounds at the moment. */
12897 __mark_reg32_unbounded(dst_reg);
12898
7fedb63a
DB
12899 if (sanitize_needed(opcode)) {
12900 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 12901 &info, false);
a6aaece0
DB
12902 if (ret < 0)
12903 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 12904 }
a6aaece0 12905
f1174f77
EC
12906 switch (opcode) {
12907 case BPF_ADD:
12908 /* We can take a fixed offset as long as it doesn't overflow
12909 * the s32 'off' field
969bf05e 12910 */
b03c9f9f
EC
12911 if (known && (ptr_reg->off + smin_val ==
12912 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 12913 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
12914 dst_reg->smin_value = smin_ptr;
12915 dst_reg->smax_value = smax_ptr;
12916 dst_reg->umin_value = umin_ptr;
12917 dst_reg->umax_value = umax_ptr;
f1174f77 12918 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 12919 dst_reg->off = ptr_reg->off + smin_val;
0962590e 12920 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
12921 break;
12922 }
f1174f77
EC
12923 /* A new variable offset is created. Note that off_reg->off
12924 * == 0, since it's a scalar.
12925 * dst_reg gets the pointer type and since some positive
12926 * integer value was added to the pointer, give it a new 'id'
12927 * if it's a PTR_TO_PACKET.
12928 * this creates a new 'base' pointer, off_reg (variable) gets
12929 * added into the variable offset, and we copy the fixed offset
12930 * from ptr_reg.
969bf05e 12931 */
b03c9f9f
EC
12932 if (signed_add_overflows(smin_ptr, smin_val) ||
12933 signed_add_overflows(smax_ptr, smax_val)) {
12934 dst_reg->smin_value = S64_MIN;
12935 dst_reg->smax_value = S64_MAX;
12936 } else {
12937 dst_reg->smin_value = smin_ptr + smin_val;
12938 dst_reg->smax_value = smax_ptr + smax_val;
12939 }
12940 if (umin_ptr + umin_val < umin_ptr ||
12941 umax_ptr + umax_val < umax_ptr) {
12942 dst_reg->umin_value = 0;
12943 dst_reg->umax_value = U64_MAX;
12944 } else {
12945 dst_reg->umin_value = umin_ptr + umin_val;
12946 dst_reg->umax_value = umax_ptr + umax_val;
12947 }
f1174f77
EC
12948 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12949 dst_reg->off = ptr_reg->off;
0962590e 12950 dst_reg->raw = ptr_reg->raw;
de8f3a83 12951 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
12952 dst_reg->id = ++env->id_gen;
12953 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 12954 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
12955 }
12956 break;
12957 case BPF_SUB:
12958 if (dst_reg == off_reg) {
12959 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
12960 verbose(env, "R%d tried to subtract pointer from scalar\n",
12961 dst);
f1174f77
EC
12962 return -EACCES;
12963 }
12964 /* We don't allow subtraction from FP, because (according to
12965 * test_verifier.c test "invalid fp arithmetic", JITs might not
12966 * be able to deal with it.
969bf05e 12967 */
f1174f77 12968 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
12969 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12970 dst);
f1174f77
EC
12971 return -EACCES;
12972 }
b03c9f9f
EC
12973 if (known && (ptr_reg->off - smin_val ==
12974 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 12975 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
12976 dst_reg->smin_value = smin_ptr;
12977 dst_reg->smax_value = smax_ptr;
12978 dst_reg->umin_value = umin_ptr;
12979 dst_reg->umax_value = umax_ptr;
f1174f77
EC
12980 dst_reg->var_off = ptr_reg->var_off;
12981 dst_reg->id = ptr_reg->id;
b03c9f9f 12982 dst_reg->off = ptr_reg->off - smin_val;
0962590e 12983 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
12984 break;
12985 }
f1174f77
EC
12986 /* A new variable offset is created. If the subtrahend is known
12987 * nonnegative, then any reg->range we had before is still good.
969bf05e 12988 */
b03c9f9f
EC
12989 if (signed_sub_overflows(smin_ptr, smax_val) ||
12990 signed_sub_overflows(smax_ptr, smin_val)) {
12991 /* Overflow possible, we know nothing */
12992 dst_reg->smin_value = S64_MIN;
12993 dst_reg->smax_value = S64_MAX;
12994 } else {
12995 dst_reg->smin_value = smin_ptr - smax_val;
12996 dst_reg->smax_value = smax_ptr - smin_val;
12997 }
12998 if (umin_ptr < umax_val) {
12999 /* Overflow possible, we know nothing */
13000 dst_reg->umin_value = 0;
13001 dst_reg->umax_value = U64_MAX;
13002 } else {
13003 /* Cannot overflow (as long as bounds are consistent) */
13004 dst_reg->umin_value = umin_ptr - umax_val;
13005 dst_reg->umax_value = umax_ptr - umin_val;
13006 }
f1174f77
EC
13007 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13008 dst_reg->off = ptr_reg->off;
0962590e 13009 dst_reg->raw = ptr_reg->raw;
de8f3a83 13010 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
13011 dst_reg->id = ++env->id_gen;
13012 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 13013 if (smin_val < 0)
22dc4a0f 13014 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 13015 }
f1174f77
EC
13016 break;
13017 case BPF_AND:
13018 case BPF_OR:
13019 case BPF_XOR:
82abbf8d
AS
13020 /* bitwise ops on pointers are troublesome, prohibit. */
13021 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13022 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
13023 return -EACCES;
13024 default:
13025 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
13026 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13027 dst, bpf_alu_string[opcode >> 4]);
f1174f77 13028 return -EACCES;
43188702
JF
13029 }
13030
bb7f0f98
AS
13031 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13032 return -EINVAL;
3844d153 13033 reg_bounds_sync(dst_reg);
073815b7
DB
13034 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13035 return -EACCES;
7fedb63a
DB
13036 if (sanitize_needed(opcode)) {
13037 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 13038 &info, true);
7fedb63a
DB
13039 if (ret < 0)
13040 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
13041 }
13042
43188702
JF
13043 return 0;
13044}
13045
3f50f132
JF
13046static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13047 struct bpf_reg_state *src_reg)
13048{
13049 s32 smin_val = src_reg->s32_min_value;
13050 s32 smax_val = src_reg->s32_max_value;
13051 u32 umin_val = src_reg->u32_min_value;
13052 u32 umax_val = src_reg->u32_max_value;
13053
13054 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13055 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13056 dst_reg->s32_min_value = S32_MIN;
13057 dst_reg->s32_max_value = S32_MAX;
13058 } else {
13059 dst_reg->s32_min_value += smin_val;
13060 dst_reg->s32_max_value += smax_val;
13061 }
13062 if (dst_reg->u32_min_value + umin_val < umin_val ||
13063 dst_reg->u32_max_value + umax_val < umax_val) {
13064 dst_reg->u32_min_value = 0;
13065 dst_reg->u32_max_value = U32_MAX;
13066 } else {
13067 dst_reg->u32_min_value += umin_val;
13068 dst_reg->u32_max_value += umax_val;
13069 }
13070}
13071
07cd2631
JF
13072static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13073 struct bpf_reg_state *src_reg)
13074{
13075 s64 smin_val = src_reg->smin_value;
13076 s64 smax_val = src_reg->smax_value;
13077 u64 umin_val = src_reg->umin_value;
13078 u64 umax_val = src_reg->umax_value;
13079
13080 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13081 signed_add_overflows(dst_reg->smax_value, smax_val)) {
13082 dst_reg->smin_value = S64_MIN;
13083 dst_reg->smax_value = S64_MAX;
13084 } else {
13085 dst_reg->smin_value += smin_val;
13086 dst_reg->smax_value += smax_val;
13087 }
13088 if (dst_reg->umin_value + umin_val < umin_val ||
13089 dst_reg->umax_value + umax_val < umax_val) {
13090 dst_reg->umin_value = 0;
13091 dst_reg->umax_value = U64_MAX;
13092 } else {
13093 dst_reg->umin_value += umin_val;
13094 dst_reg->umax_value += umax_val;
13095 }
3f50f132
JF
13096}
13097
13098static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13099 struct bpf_reg_state *src_reg)
13100{
13101 s32 smin_val = src_reg->s32_min_value;
13102 s32 smax_val = src_reg->s32_max_value;
13103 u32 umin_val = src_reg->u32_min_value;
13104 u32 umax_val = src_reg->u32_max_value;
13105
13106 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13107 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13108 /* Overflow possible, we know nothing */
13109 dst_reg->s32_min_value = S32_MIN;
13110 dst_reg->s32_max_value = S32_MAX;
13111 } else {
13112 dst_reg->s32_min_value -= smax_val;
13113 dst_reg->s32_max_value -= smin_val;
13114 }
13115 if (dst_reg->u32_min_value < umax_val) {
13116 /* Overflow possible, we know nothing */
13117 dst_reg->u32_min_value = 0;
13118 dst_reg->u32_max_value = U32_MAX;
13119 } else {
13120 /* Cannot overflow (as long as bounds are consistent) */
13121 dst_reg->u32_min_value -= umax_val;
13122 dst_reg->u32_max_value -= umin_val;
13123 }
07cd2631
JF
13124}
13125
13126static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13127 struct bpf_reg_state *src_reg)
13128{
13129 s64 smin_val = src_reg->smin_value;
13130 s64 smax_val = src_reg->smax_value;
13131 u64 umin_val = src_reg->umin_value;
13132 u64 umax_val = src_reg->umax_value;
13133
13134 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13135 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13136 /* Overflow possible, we know nothing */
13137 dst_reg->smin_value = S64_MIN;
13138 dst_reg->smax_value = S64_MAX;
13139 } else {
13140 dst_reg->smin_value -= smax_val;
13141 dst_reg->smax_value -= smin_val;
13142 }
13143 if (dst_reg->umin_value < umax_val) {
13144 /* Overflow possible, we know nothing */
13145 dst_reg->umin_value = 0;
13146 dst_reg->umax_value = U64_MAX;
13147 } else {
13148 /* Cannot overflow (as long as bounds are consistent) */
13149 dst_reg->umin_value -= umax_val;
13150 dst_reg->umax_value -= umin_val;
13151 }
3f50f132
JF
13152}
13153
13154static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13155 struct bpf_reg_state *src_reg)
13156{
13157 s32 smin_val = src_reg->s32_min_value;
13158 u32 umin_val = src_reg->u32_min_value;
13159 u32 umax_val = src_reg->u32_max_value;
13160
13161 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13162 /* Ain't nobody got time to multiply that sign */
13163 __mark_reg32_unbounded(dst_reg);
13164 return;
13165 }
13166 /* Both values are positive, so we can work with unsigned and
13167 * copy the result to signed (unless it exceeds S32_MAX).
13168 */
13169 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13170 /* Potential overflow, we know nothing */
13171 __mark_reg32_unbounded(dst_reg);
13172 return;
13173 }
13174 dst_reg->u32_min_value *= umin_val;
13175 dst_reg->u32_max_value *= umax_val;
13176 if (dst_reg->u32_max_value > S32_MAX) {
13177 /* Overflow possible, we know nothing */
13178 dst_reg->s32_min_value = S32_MIN;
13179 dst_reg->s32_max_value = S32_MAX;
13180 } else {
13181 dst_reg->s32_min_value = dst_reg->u32_min_value;
13182 dst_reg->s32_max_value = dst_reg->u32_max_value;
13183 }
07cd2631
JF
13184}
13185
13186static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13187 struct bpf_reg_state *src_reg)
13188{
13189 s64 smin_val = src_reg->smin_value;
13190 u64 umin_val = src_reg->umin_value;
13191 u64 umax_val = src_reg->umax_value;
13192
07cd2631
JF
13193 if (smin_val < 0 || dst_reg->smin_value < 0) {
13194 /* Ain't nobody got time to multiply that sign */
3f50f132 13195 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
13196 return;
13197 }
13198 /* Both values are positive, so we can work with unsigned and
13199 * copy the result to signed (unless it exceeds S64_MAX).
13200 */
13201 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13202 /* Potential overflow, we know nothing */
3f50f132 13203 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
13204 return;
13205 }
13206 dst_reg->umin_value *= umin_val;
13207 dst_reg->umax_value *= umax_val;
13208 if (dst_reg->umax_value > S64_MAX) {
13209 /* Overflow possible, we know nothing */
13210 dst_reg->smin_value = S64_MIN;
13211 dst_reg->smax_value = S64_MAX;
13212 } else {
13213 dst_reg->smin_value = dst_reg->umin_value;
13214 dst_reg->smax_value = dst_reg->umax_value;
13215 }
13216}
13217
3f50f132
JF
13218static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13219 struct bpf_reg_state *src_reg)
13220{
13221 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13222 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13223 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13224 s32 smin_val = src_reg->s32_min_value;
13225 u32 umax_val = src_reg->u32_max_value;
13226
049c4e13
DB
13227 if (src_known && dst_known) {
13228 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 13229 return;
049c4e13 13230 }
3f50f132
JF
13231
13232 /* We get our minimum from the var_off, since that's inherently
13233 * bitwise. Our maximum is the minimum of the operands' maxima.
13234 */
13235 dst_reg->u32_min_value = var32_off.value;
13236 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13237 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13238 /* Lose signed bounds when ANDing negative numbers,
13239 * ain't nobody got time for that.
13240 */
13241 dst_reg->s32_min_value = S32_MIN;
13242 dst_reg->s32_max_value = S32_MAX;
13243 } else {
13244 /* ANDing two positives gives a positive, so safe to
13245 * cast result into s64.
13246 */
13247 dst_reg->s32_min_value = dst_reg->u32_min_value;
13248 dst_reg->s32_max_value = dst_reg->u32_max_value;
13249 }
3f50f132
JF
13250}
13251
07cd2631
JF
13252static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13253 struct bpf_reg_state *src_reg)
13254{
3f50f132
JF
13255 bool src_known = tnum_is_const(src_reg->var_off);
13256 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
13257 s64 smin_val = src_reg->smin_value;
13258 u64 umax_val = src_reg->umax_value;
13259
3f50f132 13260 if (src_known && dst_known) {
4fbb38a3 13261 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
13262 return;
13263 }
13264
07cd2631
JF
13265 /* We get our minimum from the var_off, since that's inherently
13266 * bitwise. Our maximum is the minimum of the operands' maxima.
13267 */
07cd2631
JF
13268 dst_reg->umin_value = dst_reg->var_off.value;
13269 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13270 if (dst_reg->smin_value < 0 || smin_val < 0) {
13271 /* Lose signed bounds when ANDing negative numbers,
13272 * ain't nobody got time for that.
13273 */
13274 dst_reg->smin_value = S64_MIN;
13275 dst_reg->smax_value = S64_MAX;
13276 } else {
13277 /* ANDing two positives gives a positive, so safe to
13278 * cast result into s64.
13279 */
13280 dst_reg->smin_value = dst_reg->umin_value;
13281 dst_reg->smax_value = dst_reg->umax_value;
13282 }
13283 /* We may learn something more from the var_off */
13284 __update_reg_bounds(dst_reg);
13285}
13286
3f50f132
JF
13287static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13288 struct bpf_reg_state *src_reg)
13289{
13290 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13291 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13292 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
13293 s32 smin_val = src_reg->s32_min_value;
13294 u32 umin_val = src_reg->u32_min_value;
3f50f132 13295
049c4e13
DB
13296 if (src_known && dst_known) {
13297 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 13298 return;
049c4e13 13299 }
3f50f132
JF
13300
13301 /* We get our maximum from the var_off, and our minimum is the
13302 * maximum of the operands' minima
13303 */
13304 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13305 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13306 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13307 /* Lose signed bounds when ORing negative numbers,
13308 * ain't nobody got time for that.
13309 */
13310 dst_reg->s32_min_value = S32_MIN;
13311 dst_reg->s32_max_value = S32_MAX;
13312 } else {
13313 /* ORing two positives gives a positive, so safe to
13314 * cast result into s64.
13315 */
5b9fbeb7
DB
13316 dst_reg->s32_min_value = dst_reg->u32_min_value;
13317 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
13318 }
13319}
13320
07cd2631
JF
13321static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13322 struct bpf_reg_state *src_reg)
13323{
3f50f132
JF
13324 bool src_known = tnum_is_const(src_reg->var_off);
13325 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
13326 s64 smin_val = src_reg->smin_value;
13327 u64 umin_val = src_reg->umin_value;
13328
3f50f132 13329 if (src_known && dst_known) {
4fbb38a3 13330 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
13331 return;
13332 }
13333
07cd2631
JF
13334 /* We get our maximum from the var_off, and our minimum is the
13335 * maximum of the operands' minima
13336 */
07cd2631
JF
13337 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13338 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13339 if (dst_reg->smin_value < 0 || smin_val < 0) {
13340 /* Lose signed bounds when ORing negative numbers,
13341 * ain't nobody got time for that.
13342 */
13343 dst_reg->smin_value = S64_MIN;
13344 dst_reg->smax_value = S64_MAX;
13345 } else {
13346 /* ORing two positives gives a positive, so safe to
13347 * cast result into s64.
13348 */
13349 dst_reg->smin_value = dst_reg->umin_value;
13350 dst_reg->smax_value = dst_reg->umax_value;
13351 }
13352 /* We may learn something more from the var_off */
13353 __update_reg_bounds(dst_reg);
13354}
13355
2921c90d
YS
13356static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13357 struct bpf_reg_state *src_reg)
13358{
13359 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13360 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13361 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13362 s32 smin_val = src_reg->s32_min_value;
13363
049c4e13
DB
13364 if (src_known && dst_known) {
13365 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 13366 return;
049c4e13 13367 }
2921c90d
YS
13368
13369 /* We get both minimum and maximum from the var32_off. */
13370 dst_reg->u32_min_value = var32_off.value;
13371 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13372
13373 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13374 /* XORing two positive sign numbers gives a positive,
13375 * so safe to cast u32 result into s32.
13376 */
13377 dst_reg->s32_min_value = dst_reg->u32_min_value;
13378 dst_reg->s32_max_value = dst_reg->u32_max_value;
13379 } else {
13380 dst_reg->s32_min_value = S32_MIN;
13381 dst_reg->s32_max_value = S32_MAX;
13382 }
13383}
13384
13385static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13386 struct bpf_reg_state *src_reg)
13387{
13388 bool src_known = tnum_is_const(src_reg->var_off);
13389 bool dst_known = tnum_is_const(dst_reg->var_off);
13390 s64 smin_val = src_reg->smin_value;
13391
13392 if (src_known && dst_known) {
13393 /* dst_reg->var_off.value has been updated earlier */
13394 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13395 return;
13396 }
13397
13398 /* We get both minimum and maximum from the var_off. */
13399 dst_reg->umin_value = dst_reg->var_off.value;
13400 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13401
13402 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13403 /* XORing two positive sign numbers gives a positive,
13404 * so safe to cast u64 result into s64.
13405 */
13406 dst_reg->smin_value = dst_reg->umin_value;
13407 dst_reg->smax_value = dst_reg->umax_value;
13408 } else {
13409 dst_reg->smin_value = S64_MIN;
13410 dst_reg->smax_value = S64_MAX;
13411 }
13412
13413 __update_reg_bounds(dst_reg);
13414}
13415
3f50f132
JF
13416static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13417 u64 umin_val, u64 umax_val)
07cd2631 13418{
07cd2631
JF
13419 /* We lose all sign bit information (except what we can pick
13420 * up from var_off)
13421 */
3f50f132
JF
13422 dst_reg->s32_min_value = S32_MIN;
13423 dst_reg->s32_max_value = S32_MAX;
13424 /* If we might shift our top bit out, then we know nothing */
13425 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13426 dst_reg->u32_min_value = 0;
13427 dst_reg->u32_max_value = U32_MAX;
13428 } else {
13429 dst_reg->u32_min_value <<= umin_val;
13430 dst_reg->u32_max_value <<= umax_val;
13431 }
13432}
13433
13434static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13435 struct bpf_reg_state *src_reg)
13436{
13437 u32 umax_val = src_reg->u32_max_value;
13438 u32 umin_val = src_reg->u32_min_value;
13439 /* u32 alu operation will zext upper bits */
13440 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13441
13442 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13443 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13444 /* Not required but being careful mark reg64 bounds as unknown so
13445 * that we are forced to pick them up from tnum and zext later and
13446 * if some path skips this step we are still safe.
13447 */
13448 __mark_reg64_unbounded(dst_reg);
13449 __update_reg32_bounds(dst_reg);
13450}
13451
13452static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13453 u64 umin_val, u64 umax_val)
13454{
13455 /* Special case <<32 because it is a common compiler pattern to sign
13456 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13457 * positive we know this shift will also be positive so we can track
13458 * bounds correctly. Otherwise we lose all sign bit information except
13459 * what we can pick up from var_off. Perhaps we can generalize this
13460 * later to shifts of any length.
13461 */
13462 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13463 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13464 else
13465 dst_reg->smax_value = S64_MAX;
13466
13467 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13468 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13469 else
13470 dst_reg->smin_value = S64_MIN;
13471
07cd2631
JF
13472 /* If we might shift our top bit out, then we know nothing */
13473 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13474 dst_reg->umin_value = 0;
13475 dst_reg->umax_value = U64_MAX;
13476 } else {
13477 dst_reg->umin_value <<= umin_val;
13478 dst_reg->umax_value <<= umax_val;
13479 }
3f50f132
JF
13480}
13481
13482static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13483 struct bpf_reg_state *src_reg)
13484{
13485 u64 umax_val = src_reg->umax_value;
13486 u64 umin_val = src_reg->umin_value;
13487
13488 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13489 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13490 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13491
07cd2631
JF
13492 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13493 /* We may learn something more from the var_off */
13494 __update_reg_bounds(dst_reg);
13495}
13496
3f50f132
JF
13497static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13498 struct bpf_reg_state *src_reg)
13499{
13500 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13501 u32 umax_val = src_reg->u32_max_value;
13502 u32 umin_val = src_reg->u32_min_value;
13503
13504 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13505 * be negative, then either:
13506 * 1) src_reg might be zero, so the sign bit of the result is
13507 * unknown, so we lose our signed bounds
13508 * 2) it's known negative, thus the unsigned bounds capture the
13509 * signed bounds
13510 * 3) the signed bounds cross zero, so they tell us nothing
13511 * about the result
13512 * If the value in dst_reg is known nonnegative, then again the
18b24d78 13513 * unsigned bounds capture the signed bounds.
3f50f132
JF
13514 * Thus, in all cases it suffices to blow away our signed bounds
13515 * and rely on inferring new ones from the unsigned bounds and
13516 * var_off of the result.
13517 */
13518 dst_reg->s32_min_value = S32_MIN;
13519 dst_reg->s32_max_value = S32_MAX;
13520
13521 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13522 dst_reg->u32_min_value >>= umax_val;
13523 dst_reg->u32_max_value >>= umin_val;
13524
13525 __mark_reg64_unbounded(dst_reg);
13526 __update_reg32_bounds(dst_reg);
13527}
13528
07cd2631
JF
13529static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13530 struct bpf_reg_state *src_reg)
13531{
13532 u64 umax_val = src_reg->umax_value;
13533 u64 umin_val = src_reg->umin_value;
13534
13535 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13536 * be negative, then either:
13537 * 1) src_reg might be zero, so the sign bit of the result is
13538 * unknown, so we lose our signed bounds
13539 * 2) it's known negative, thus the unsigned bounds capture the
13540 * signed bounds
13541 * 3) the signed bounds cross zero, so they tell us nothing
13542 * about the result
13543 * If the value in dst_reg is known nonnegative, then again the
18b24d78 13544 * unsigned bounds capture the signed bounds.
07cd2631
JF
13545 * Thus, in all cases it suffices to blow away our signed bounds
13546 * and rely on inferring new ones from the unsigned bounds and
13547 * var_off of the result.
13548 */
13549 dst_reg->smin_value = S64_MIN;
13550 dst_reg->smax_value = S64_MAX;
13551 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13552 dst_reg->umin_value >>= umax_val;
13553 dst_reg->umax_value >>= umin_val;
3f50f132
JF
13554
13555 /* Its not easy to operate on alu32 bounds here because it depends
13556 * on bits being shifted in. Take easy way out and mark unbounded
13557 * so we can recalculate later from tnum.
13558 */
13559 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
13560 __update_reg_bounds(dst_reg);
13561}
13562
3f50f132
JF
13563static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13564 struct bpf_reg_state *src_reg)
07cd2631 13565{
3f50f132 13566 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
13567
13568 /* Upon reaching here, src_known is true and
13569 * umax_val is equal to umin_val.
13570 */
3f50f132
JF
13571 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13572 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 13573
3f50f132
JF
13574 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13575
13576 /* blow away the dst_reg umin_value/umax_value and rely on
13577 * dst_reg var_off to refine the result.
13578 */
13579 dst_reg->u32_min_value = 0;
13580 dst_reg->u32_max_value = U32_MAX;
13581
13582 __mark_reg64_unbounded(dst_reg);
13583 __update_reg32_bounds(dst_reg);
13584}
13585
13586static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13587 struct bpf_reg_state *src_reg)
13588{
13589 u64 umin_val = src_reg->umin_value;
13590
13591 /* Upon reaching here, src_known is true and umax_val is equal
13592 * to umin_val.
13593 */
13594 dst_reg->smin_value >>= umin_val;
13595 dst_reg->smax_value >>= umin_val;
13596
13597 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
13598
13599 /* blow away the dst_reg umin_value/umax_value and rely on
13600 * dst_reg var_off to refine the result.
13601 */
13602 dst_reg->umin_value = 0;
13603 dst_reg->umax_value = U64_MAX;
3f50f132
JF
13604
13605 /* Its not easy to operate on alu32 bounds here because it depends
13606 * on bits being shifted in from upper 32-bits. Take easy way out
13607 * and mark unbounded so we can recalculate later from tnum.
13608 */
13609 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
13610 __update_reg_bounds(dst_reg);
13611}
13612
468f6eaf
JH
13613/* WARNING: This function does calculations on 64-bit values, but the actual
13614 * execution may occur on 32-bit values. Therefore, things like bitshifts
13615 * need extra checks in the 32-bit case.
13616 */
f1174f77
EC
13617static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13618 struct bpf_insn *insn,
13619 struct bpf_reg_state *dst_reg,
13620 struct bpf_reg_state src_reg)
969bf05e 13621{
638f5b90 13622 struct bpf_reg_state *regs = cur_regs(env);
48461135 13623 u8 opcode = BPF_OP(insn->code);
b0b3fb67 13624 bool src_known;
b03c9f9f
EC
13625 s64 smin_val, smax_val;
13626 u64 umin_val, umax_val;
3f50f132
JF
13627 s32 s32_min_val, s32_max_val;
13628 u32 u32_min_val, u32_max_val;
468f6eaf 13629 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 13630 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 13631 int ret;
b799207e 13632
b03c9f9f
EC
13633 smin_val = src_reg.smin_value;
13634 smax_val = src_reg.smax_value;
13635 umin_val = src_reg.umin_value;
13636 umax_val = src_reg.umax_value;
f23cc643 13637
3f50f132
JF
13638 s32_min_val = src_reg.s32_min_value;
13639 s32_max_val = src_reg.s32_max_value;
13640 u32_min_val = src_reg.u32_min_value;
13641 u32_max_val = src_reg.u32_max_value;
13642
13643 if (alu32) {
13644 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
13645 if ((src_known &&
13646 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13647 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13648 /* Taint dst register if offset had invalid bounds
13649 * derived from e.g. dead branches.
13650 */
13651 __mark_reg_unknown(env, dst_reg);
13652 return 0;
13653 }
13654 } else {
13655 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
13656 if ((src_known &&
13657 (smin_val != smax_val || umin_val != umax_val)) ||
13658 smin_val > smax_val || umin_val > umax_val) {
13659 /* Taint dst register if offset had invalid bounds
13660 * derived from e.g. dead branches.
13661 */
13662 __mark_reg_unknown(env, dst_reg);
13663 return 0;
13664 }
6f16101e
DB
13665 }
13666
bb7f0f98
AS
13667 if (!src_known &&
13668 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 13669 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
13670 return 0;
13671 }
13672
f5288193
DB
13673 if (sanitize_needed(opcode)) {
13674 ret = sanitize_val_alu(env, insn);
13675 if (ret < 0)
13676 return sanitize_err(env, insn, ret, NULL, NULL);
13677 }
13678
3f50f132
JF
13679 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13680 * There are two classes of instructions: The first class we track both
13681 * alu32 and alu64 sign/unsigned bounds independently this provides the
13682 * greatest amount of precision when alu operations are mixed with jmp32
13683 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13684 * and BPF_OR. This is possible because these ops have fairly easy to
13685 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13686 * See alu32 verifier tests for examples. The second class of
13687 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13688 * with regards to tracking sign/unsigned bounds because the bits may
13689 * cross subreg boundaries in the alu64 case. When this happens we mark
13690 * the reg unbounded in the subreg bound space and use the resulting
13691 * tnum to calculate an approximation of the sign/unsigned bounds.
13692 */
48461135
JB
13693 switch (opcode) {
13694 case BPF_ADD:
3f50f132 13695 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 13696 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 13697 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
13698 break;
13699 case BPF_SUB:
3f50f132 13700 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 13701 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 13702 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
13703 break;
13704 case BPF_MUL:
3f50f132
JF
13705 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13706 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 13707 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
13708 break;
13709 case BPF_AND:
3f50f132
JF
13710 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13711 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 13712 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
13713 break;
13714 case BPF_OR:
3f50f132
JF
13715 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13716 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 13717 scalar_min_max_or(dst_reg, &src_reg);
48461135 13718 break;
2921c90d
YS
13719 case BPF_XOR:
13720 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13721 scalar32_min_max_xor(dst_reg, &src_reg);
13722 scalar_min_max_xor(dst_reg, &src_reg);
13723 break;
48461135 13724 case BPF_LSH:
468f6eaf
JH
13725 if (umax_val >= insn_bitness) {
13726 /* Shifts greater than 31 or 63 are undefined.
13727 * This includes shifts by a negative number.
b03c9f9f 13728 */
61bd5218 13729 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
13730 break;
13731 }
3f50f132
JF
13732 if (alu32)
13733 scalar32_min_max_lsh(dst_reg, &src_reg);
13734 else
13735 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
13736 break;
13737 case BPF_RSH:
468f6eaf
JH
13738 if (umax_val >= insn_bitness) {
13739 /* Shifts greater than 31 or 63 are undefined.
13740 * This includes shifts by a negative number.
b03c9f9f 13741 */
61bd5218 13742 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
13743 break;
13744 }
3f50f132
JF
13745 if (alu32)
13746 scalar32_min_max_rsh(dst_reg, &src_reg);
13747 else
13748 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 13749 break;
9cbe1f5a
YS
13750 case BPF_ARSH:
13751 if (umax_val >= insn_bitness) {
13752 /* Shifts greater than 31 or 63 are undefined.
13753 * This includes shifts by a negative number.
13754 */
13755 mark_reg_unknown(env, regs, insn->dst_reg);
13756 break;
13757 }
3f50f132
JF
13758 if (alu32)
13759 scalar32_min_max_arsh(dst_reg, &src_reg);
13760 else
13761 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 13762 break;
48461135 13763 default:
61bd5218 13764 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
13765 break;
13766 }
13767
3f50f132
JF
13768 /* ALU32 ops are zero extended into 64bit register */
13769 if (alu32)
13770 zext_32_to_64(dst_reg);
3844d153 13771 reg_bounds_sync(dst_reg);
f1174f77
EC
13772 return 0;
13773}
13774
13775/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13776 * and var_off.
13777 */
13778static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13779 struct bpf_insn *insn)
13780{
f4d7e40a
AS
13781 struct bpf_verifier_state *vstate = env->cur_state;
13782 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13783 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
13784 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13785 u8 opcode = BPF_OP(insn->code);
b5dc0163 13786 int err;
f1174f77
EC
13787
13788 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
13789 src_reg = NULL;
13790 if (dst_reg->type != SCALAR_VALUE)
13791 ptr_reg = dst_reg;
75748837
AS
13792 else
13793 /* Make sure ID is cleared otherwise dst_reg min/max could be
13794 * incorrectly propagated into other registers by find_equal_scalars()
13795 */
13796 dst_reg->id = 0;
f1174f77
EC
13797 if (BPF_SRC(insn->code) == BPF_X) {
13798 src_reg = &regs[insn->src_reg];
f1174f77
EC
13799 if (src_reg->type != SCALAR_VALUE) {
13800 if (dst_reg->type != SCALAR_VALUE) {
13801 /* Combining two pointers by any ALU op yields
82abbf8d
AS
13802 * an arbitrary scalar. Disallow all math except
13803 * pointer subtraction
f1174f77 13804 */
dd066823 13805 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
13806 mark_reg_unknown(env, regs, insn->dst_reg);
13807 return 0;
f1174f77 13808 }
82abbf8d
AS
13809 verbose(env, "R%d pointer %s pointer prohibited\n",
13810 insn->dst_reg,
13811 bpf_alu_string[opcode >> 4]);
13812 return -EACCES;
f1174f77
EC
13813 } else {
13814 /* scalar += pointer
13815 * This is legal, but we have to reverse our
13816 * src/dest handling in computing the range
13817 */
b5dc0163
AS
13818 err = mark_chain_precision(env, insn->dst_reg);
13819 if (err)
13820 return err;
82abbf8d
AS
13821 return adjust_ptr_min_max_vals(env, insn,
13822 src_reg, dst_reg);
f1174f77
EC
13823 }
13824 } else if (ptr_reg) {
13825 /* pointer += scalar */
b5dc0163
AS
13826 err = mark_chain_precision(env, insn->src_reg);
13827 if (err)
13828 return err;
82abbf8d
AS
13829 return adjust_ptr_min_max_vals(env, insn,
13830 dst_reg, src_reg);
a3b666bf
AN
13831 } else if (dst_reg->precise) {
13832 /* if dst_reg is precise, src_reg should be precise as well */
13833 err = mark_chain_precision(env, insn->src_reg);
13834 if (err)
13835 return err;
f1174f77
EC
13836 }
13837 } else {
13838 /* Pretend the src is a reg with a known value, since we only
13839 * need to be able to read from this state.
13840 */
13841 off_reg.type = SCALAR_VALUE;
b03c9f9f 13842 __mark_reg_known(&off_reg, insn->imm);
f1174f77 13843 src_reg = &off_reg;
82abbf8d
AS
13844 if (ptr_reg) /* pointer += K */
13845 return adjust_ptr_min_max_vals(env, insn,
13846 ptr_reg, src_reg);
f1174f77
EC
13847 }
13848
13849 /* Got here implies adding two SCALAR_VALUEs */
13850 if (WARN_ON_ONCE(ptr_reg)) {
0f55f9ed 13851 print_verifier_state(env, state, true);
61bd5218 13852 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
13853 return -EINVAL;
13854 }
13855 if (WARN_ON(!src_reg)) {
0f55f9ed 13856 print_verifier_state(env, state, true);
61bd5218 13857 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
13858 return -EINVAL;
13859 }
13860 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
13861}
13862
17a52670 13863/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 13864static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 13865{
638f5b90 13866 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
13867 u8 opcode = BPF_OP(insn->code);
13868 int err;
13869
13870 if (opcode == BPF_END || opcode == BPF_NEG) {
13871 if (opcode == BPF_NEG) {
395e942d 13872 if (BPF_SRC(insn->code) != BPF_K ||
17a52670
AS
13873 insn->src_reg != BPF_REG_0 ||
13874 insn->off != 0 || insn->imm != 0) {
61bd5218 13875 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
13876 return -EINVAL;
13877 }
13878 } else {
13879 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68 13880 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
0845c3db
YS
13881 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13882 BPF_SRC(insn->code) != BPF_TO_LE)) {
61bd5218 13883 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
13884 return -EINVAL;
13885 }
13886 }
13887
13888 /* check src operand */
dc503a8a 13889 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13890 if (err)
13891 return err;
13892
1be7f75d 13893 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 13894 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
13895 insn->dst_reg);
13896 return -EACCES;
13897 }
13898
17a52670 13899 /* check dest operand */
dc503a8a 13900 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
13901 if (err)
13902 return err;
13903
13904 } else if (opcode == BPF_MOV) {
13905
13906 if (BPF_SRC(insn->code) == BPF_X) {
8100928c 13907 if (insn->imm != 0) {
61bd5218 13908 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
13909 return -EINVAL;
13910 }
13911
8100928c
YS
13912 if (BPF_CLASS(insn->code) == BPF_ALU) {
13913 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13914 verbose(env, "BPF_MOV uses reserved fields\n");
13915 return -EINVAL;
13916 }
13917 } else {
13918 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13919 insn->off != 32) {
13920 verbose(env, "BPF_MOV uses reserved fields\n");
13921 return -EINVAL;
13922 }
13923 }
13924
17a52670 13925 /* check src operand */
dc503a8a 13926 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13927 if (err)
13928 return err;
13929 } else {
13930 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 13931 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
13932 return -EINVAL;
13933 }
13934 }
13935
fbeb1603
AF
13936 /* check dest operand, mark as required later */
13937 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
13938 if (err)
13939 return err;
13940
13941 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
13942 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13943 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
1ffc85d9
EZ
13944 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13945 !tnum_is_const(src_reg->var_off);
e434b8cd 13946
17a52670 13947 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8100928c
YS
13948 if (insn->off == 0) {
13949 /* case: R1 = R2
13950 * copy register state to dest reg
75748837 13951 */
8100928c
YS
13952 if (need_id)
13953 /* Assign src and dst registers the same ID
13954 * that will be used by find_equal_scalars()
13955 * to propagate min/max range.
13956 */
13957 src_reg->id = ++env->id_gen;
13958 copy_register_state(dst_reg, src_reg);
13959 dst_reg->live |= REG_LIVE_WRITTEN;
13960 dst_reg->subreg_def = DEF_NOT_SUBREG;
13961 } else {
13962 /* case: R1 = (s8, s16 s32)R2 */
db2baf82
YS
13963 if (is_pointer_value(env, insn->src_reg)) {
13964 verbose(env,
13965 "R%d sign-extension part of pointer\n",
13966 insn->src_reg);
13967 return -EACCES;
13968 } else if (src_reg->type == SCALAR_VALUE) {
13969 bool no_sext;
13970
13971 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13972 if (no_sext && need_id)
13973 src_reg->id = ++env->id_gen;
13974 copy_register_state(dst_reg, src_reg);
13975 if (!no_sext)
13976 dst_reg->id = 0;
13977 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13978 dst_reg->live |= REG_LIVE_WRITTEN;
13979 dst_reg->subreg_def = DEF_NOT_SUBREG;
13980 } else {
13981 mark_reg_unknown(env, regs, insn->dst_reg);
13982 }
8100928c 13983 }
17a52670 13984 } else {
f1174f77 13985 /* R1 = (u32) R2 */
1be7f75d 13986 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
13987 verbose(env,
13988 "R%d partial copy of pointer\n",
1be7f75d
AS
13989 insn->src_reg);
13990 return -EACCES;
e434b8cd 13991 } else if (src_reg->type == SCALAR_VALUE) {
8100928c
YS
13992 if (insn->off == 0) {
13993 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13994
13995 if (is_src_reg_u32 && need_id)
13996 src_reg->id = ++env->id_gen;
13997 copy_register_state(dst_reg, src_reg);
13998 /* Make sure ID is cleared if src_reg is not in u32
13999 * range otherwise dst_reg min/max could be incorrectly
14000 * propagated into src_reg by find_equal_scalars()
14001 */
14002 if (!is_src_reg_u32)
14003 dst_reg->id = 0;
14004 dst_reg->live |= REG_LIVE_WRITTEN;
14005 dst_reg->subreg_def = env->insn_idx + 1;
14006 } else {
14007 /* case: W1 = (s8, s16)W2 */
14008 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14009
14010 if (no_sext && need_id)
14011 src_reg->id = ++env->id_gen;
14012 copy_register_state(dst_reg, src_reg);
14013 if (!no_sext)
14014 dst_reg->id = 0;
14015 dst_reg->live |= REG_LIVE_WRITTEN;
14016 dst_reg->subreg_def = env->insn_idx + 1;
14017 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14018 }
e434b8cd
JW
14019 } else {
14020 mark_reg_unknown(env, regs,
14021 insn->dst_reg);
1be7f75d 14022 }
3f50f132 14023 zext_32_to_64(dst_reg);
3844d153 14024 reg_bounds_sync(dst_reg);
17a52670
AS
14025 }
14026 } else {
14027 /* case: R = imm
14028 * remember the value we stored into this reg
14029 */
fbeb1603
AF
14030 /* clear any state __mark_reg_known doesn't set */
14031 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 14032 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
14033 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14034 __mark_reg_known(regs + insn->dst_reg,
14035 insn->imm);
14036 } else {
14037 __mark_reg_known(regs + insn->dst_reg,
14038 (u32)insn->imm);
14039 }
17a52670
AS
14040 }
14041
14042 } else if (opcode > BPF_END) {
61bd5218 14043 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
14044 return -EINVAL;
14045
14046 } else { /* all other ALU ops: and, sub, xor, add, ... */
14047
17a52670 14048 if (BPF_SRC(insn->code) == BPF_X) {
ec0e2da9
YS
14049 if (insn->imm != 0 || insn->off > 1 ||
14050 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
61bd5218 14051 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
14052 return -EINVAL;
14053 }
14054 /* check src1 operand */
dc503a8a 14055 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
14056 if (err)
14057 return err;
14058 } else {
ec0e2da9
YS
14059 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14060 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
61bd5218 14061 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
14062 return -EINVAL;
14063 }
14064 }
14065
14066 /* check src2 operand */
dc503a8a 14067 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
14068 if (err)
14069 return err;
14070
14071 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14072 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 14073 verbose(env, "div by zero\n");
17a52670
AS
14074 return -EINVAL;
14075 }
14076
229394e8
RV
14077 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14078 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14079 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14080
14081 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 14082 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
14083 return -EINVAL;
14084 }
14085 }
14086
1a0dc1ac 14087 /* check dest operand */
dc503a8a 14088 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
14089 if (err)
14090 return err;
14091
f1174f77 14092 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
14093 }
14094
14095 return 0;
14096}
14097
f4d7e40a 14098static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 14099 struct bpf_reg_state *dst_reg,
f8ddadc4 14100 enum bpf_reg_type type,
fb2a311a 14101 bool range_right_open)
969bf05e 14102{
b239da34
KKD
14103 struct bpf_func_state *state;
14104 struct bpf_reg_state *reg;
14105 int new_range;
2d2be8ca 14106
fb2a311a
DB
14107 if (dst_reg->off < 0 ||
14108 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
14109 /* This doesn't give us any range */
14110 return;
14111
b03c9f9f
EC
14112 if (dst_reg->umax_value > MAX_PACKET_OFF ||
14113 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
14114 /* Risk of overflow. For instance, ptr + (1<<63) may be less
14115 * than pkt_end, but that's because it's also less than pkt.
14116 */
14117 return;
14118
fb2a311a
DB
14119 new_range = dst_reg->off;
14120 if (range_right_open)
2fa7d94a 14121 new_range++;
fb2a311a
DB
14122
14123 /* Examples for register markings:
2d2be8ca 14124 *
fb2a311a 14125 * pkt_data in dst register:
2d2be8ca
DB
14126 *
14127 * r2 = r3;
14128 * r2 += 8;
14129 * if (r2 > pkt_end) goto <handle exception>
14130 * <access okay>
14131 *
b4e432f1
DB
14132 * r2 = r3;
14133 * r2 += 8;
14134 * if (r2 < pkt_end) goto <access okay>
14135 * <handle exception>
14136 *
2d2be8ca
DB
14137 * Where:
14138 * r2 == dst_reg, pkt_end == src_reg
14139 * r2=pkt(id=n,off=8,r=0)
14140 * r3=pkt(id=n,off=0,r=0)
14141 *
fb2a311a 14142 * pkt_data in src register:
2d2be8ca
DB
14143 *
14144 * r2 = r3;
14145 * r2 += 8;
14146 * if (pkt_end >= r2) goto <access okay>
14147 * <handle exception>
14148 *
b4e432f1
DB
14149 * r2 = r3;
14150 * r2 += 8;
14151 * if (pkt_end <= r2) goto <handle exception>
14152 * <access okay>
14153 *
2d2be8ca
DB
14154 * Where:
14155 * pkt_end == dst_reg, r2 == src_reg
14156 * r2=pkt(id=n,off=8,r=0)
14157 * r3=pkt(id=n,off=0,r=0)
14158 *
14159 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
14160 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14161 * and [r3, r3 + 8-1) respectively is safe to access depending on
14162 * the check.
969bf05e 14163 */
2d2be8ca 14164
f1174f77
EC
14165 /* If our ids match, then we must have the same max_value. And we
14166 * don't care about the other reg's fixed offset, since if it's too big
14167 * the range won't allow anything.
14168 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14169 */
b239da34
KKD
14170 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14171 if (reg->type == type && reg->id == dst_reg->id)
14172 /* keep the maximum range already checked */
14173 reg->range = max(reg->range, new_range);
14174 }));
969bf05e
AS
14175}
14176
3f50f132 14177static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 14178{
3f50f132
JF
14179 struct tnum subreg = tnum_subreg(reg->var_off);
14180 s32 sval = (s32)val;
a72dafaf 14181
3f50f132
JF
14182 switch (opcode) {
14183 case BPF_JEQ:
14184 if (tnum_is_const(subreg))
14185 return !!tnum_equals_const(subreg, val);
13fbcee5
YS
14186 else if (val < reg->u32_min_value || val > reg->u32_max_value)
14187 return 0;
42d31dd6
AN
14188 else if (sval < reg->s32_min_value || sval > reg->s32_max_value)
14189 return 0;
3f50f132
JF
14190 break;
14191 case BPF_JNE:
14192 if (tnum_is_const(subreg))
14193 return !tnum_equals_const(subreg, val);
13fbcee5
YS
14194 else if (val < reg->u32_min_value || val > reg->u32_max_value)
14195 return 1;
42d31dd6
AN
14196 else if (sval < reg->s32_min_value || sval > reg->s32_max_value)
14197 return 1;
3f50f132
JF
14198 break;
14199 case BPF_JSET:
14200 if ((~subreg.mask & subreg.value) & val)
14201 return 1;
14202 if (!((subreg.mask | subreg.value) & val))
14203 return 0;
14204 break;
14205 case BPF_JGT:
14206 if (reg->u32_min_value > val)
14207 return 1;
14208 else if (reg->u32_max_value <= val)
14209 return 0;
14210 break;
14211 case BPF_JSGT:
14212 if (reg->s32_min_value > sval)
14213 return 1;
ee114dd6 14214 else if (reg->s32_max_value <= sval)
3f50f132
JF
14215 return 0;
14216 break;
14217 case BPF_JLT:
14218 if (reg->u32_max_value < val)
14219 return 1;
14220 else if (reg->u32_min_value >= val)
14221 return 0;
14222 break;
14223 case BPF_JSLT:
14224 if (reg->s32_max_value < sval)
14225 return 1;
14226 else if (reg->s32_min_value >= sval)
14227 return 0;
14228 break;
14229 case BPF_JGE:
14230 if (reg->u32_min_value >= val)
14231 return 1;
14232 else if (reg->u32_max_value < val)
14233 return 0;
14234 break;
14235 case BPF_JSGE:
14236 if (reg->s32_min_value >= sval)
14237 return 1;
14238 else if (reg->s32_max_value < sval)
14239 return 0;
14240 break;
14241 case BPF_JLE:
14242 if (reg->u32_max_value <= val)
14243 return 1;
14244 else if (reg->u32_min_value > val)
14245 return 0;
14246 break;
14247 case BPF_JSLE:
14248 if (reg->s32_max_value <= sval)
14249 return 1;
14250 else if (reg->s32_min_value > sval)
14251 return 0;
14252 break;
14253 }
4f7b3e82 14254
3f50f132
JF
14255 return -1;
14256}
092ed096 14257
3f50f132
JF
14258
14259static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
14260{
14261 s64 sval = (s64)val;
a72dafaf 14262
4f7b3e82
AS
14263 switch (opcode) {
14264 case BPF_JEQ:
14265 if (tnum_is_const(reg->var_off))
14266 return !!tnum_equals_const(reg->var_off, val);
13fbcee5
YS
14267 else if (val < reg->umin_value || val > reg->umax_value)
14268 return 0;
42d31dd6
AN
14269 else if (sval < reg->smin_value || sval > reg->smax_value)
14270 return 0;
4f7b3e82
AS
14271 break;
14272 case BPF_JNE:
14273 if (tnum_is_const(reg->var_off))
14274 return !tnum_equals_const(reg->var_off, val);
13fbcee5
YS
14275 else if (val < reg->umin_value || val > reg->umax_value)
14276 return 1;
42d31dd6
AN
14277 else if (sval < reg->smin_value || sval > reg->smax_value)
14278 return 1;
4f7b3e82 14279 break;
960ea056
JK
14280 case BPF_JSET:
14281 if ((~reg->var_off.mask & reg->var_off.value) & val)
14282 return 1;
14283 if (!((reg->var_off.mask | reg->var_off.value) & val))
14284 return 0;
14285 break;
4f7b3e82
AS
14286 case BPF_JGT:
14287 if (reg->umin_value > val)
14288 return 1;
14289 else if (reg->umax_value <= val)
14290 return 0;
14291 break;
14292 case BPF_JSGT:
a72dafaf 14293 if (reg->smin_value > sval)
4f7b3e82 14294 return 1;
ee114dd6 14295 else if (reg->smax_value <= sval)
4f7b3e82
AS
14296 return 0;
14297 break;
14298 case BPF_JLT:
14299 if (reg->umax_value < val)
14300 return 1;
14301 else if (reg->umin_value >= val)
14302 return 0;
14303 break;
14304 case BPF_JSLT:
a72dafaf 14305 if (reg->smax_value < sval)
4f7b3e82 14306 return 1;
a72dafaf 14307 else if (reg->smin_value >= sval)
4f7b3e82
AS
14308 return 0;
14309 break;
14310 case BPF_JGE:
14311 if (reg->umin_value >= val)
14312 return 1;
14313 else if (reg->umax_value < val)
14314 return 0;
14315 break;
14316 case BPF_JSGE:
a72dafaf 14317 if (reg->smin_value >= sval)
4f7b3e82 14318 return 1;
a72dafaf 14319 else if (reg->smax_value < sval)
4f7b3e82
AS
14320 return 0;
14321 break;
14322 case BPF_JLE:
14323 if (reg->umax_value <= val)
14324 return 1;
14325 else if (reg->umin_value > val)
14326 return 0;
14327 break;
14328 case BPF_JSLE:
a72dafaf 14329 if (reg->smax_value <= sval)
4f7b3e82 14330 return 1;
a72dafaf 14331 else if (reg->smin_value > sval)
4f7b3e82
AS
14332 return 0;
14333 break;
14334 }
14335
14336 return -1;
14337}
14338
3f50f132
JF
14339/* compute branch direction of the expression "if (reg opcode val) goto target;"
14340 * and return:
14341 * 1 - branch will be taken and "goto target" will be executed
14342 * 0 - branch will not be taken and fall-through to next insn
14343 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
14344 * range [0,10]
604dca5e 14345 */
3f50f132
JF
14346static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
14347 bool is_jmp32)
604dca5e 14348{
cac616db 14349 if (__is_pointer_value(false, reg)) {
51302c95 14350 if (!reg_not_null(reg))
cac616db
JF
14351 return -1;
14352
14353 /* If pointer is valid tests against zero will fail so we can
14354 * use this to direct branch taken.
14355 */
14356 if (val != 0)
14357 return -1;
14358
14359 switch (opcode) {
14360 case BPF_JEQ:
14361 return 0;
14362 case BPF_JNE:
14363 return 1;
14364 default:
14365 return -1;
14366 }
14367 }
604dca5e 14368
3f50f132
JF
14369 if (is_jmp32)
14370 return is_branch32_taken(reg, val, opcode);
14371 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
14372}
14373
6d94e741
AS
14374static int flip_opcode(u32 opcode)
14375{
14376 /* How can we transform "a <op> b" into "b <op> a"? */
14377 static const u8 opcode_flip[16] = {
14378 /* these stay the same */
14379 [BPF_JEQ >> 4] = BPF_JEQ,
14380 [BPF_JNE >> 4] = BPF_JNE,
14381 [BPF_JSET >> 4] = BPF_JSET,
14382 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14383 [BPF_JGE >> 4] = BPF_JLE,
14384 [BPF_JGT >> 4] = BPF_JLT,
14385 [BPF_JLE >> 4] = BPF_JGE,
14386 [BPF_JLT >> 4] = BPF_JGT,
14387 [BPF_JSGE >> 4] = BPF_JSLE,
14388 [BPF_JSGT >> 4] = BPF_JSLT,
14389 [BPF_JSLE >> 4] = BPF_JSGE,
14390 [BPF_JSLT >> 4] = BPF_JSGT
14391 };
14392 return opcode_flip[opcode >> 4];
14393}
14394
14395static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14396 struct bpf_reg_state *src_reg,
14397 u8 opcode)
14398{
14399 struct bpf_reg_state *pkt;
14400
14401 if (src_reg->type == PTR_TO_PACKET_END) {
14402 pkt = dst_reg;
14403 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14404 pkt = src_reg;
14405 opcode = flip_opcode(opcode);
14406 } else {
14407 return -1;
14408 }
14409
14410 if (pkt->range >= 0)
14411 return -1;
14412
14413 switch (opcode) {
14414 case BPF_JLE:
14415 /* pkt <= pkt_end */
14416 fallthrough;
14417 case BPF_JGT:
14418 /* pkt > pkt_end */
14419 if (pkt->range == BEYOND_PKT_END)
14420 /* pkt has at last one extra byte beyond pkt_end */
14421 return opcode == BPF_JGT;
14422 break;
14423 case BPF_JLT:
14424 /* pkt < pkt_end */
14425 fallthrough;
14426 case BPF_JGE:
14427 /* pkt >= pkt_end */
14428 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14429 return opcode == BPF_JGE;
14430 break;
14431 }
14432 return -1;
14433}
14434
48461135
JB
14435/* Adjusts the register min/max values in the case that the dst_reg is the
14436 * variable register that we are working on, and src_reg is a constant or we're
14437 * simply doing a BPF_K check.
f1174f77 14438 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
14439 */
14440static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
14441 struct bpf_reg_state *false_reg,
14442 u64 val, u32 val32,
092ed096 14443 u8 opcode, bool is_jmp32)
48461135 14444{
3f50f132
JF
14445 struct tnum false_32off = tnum_subreg(false_reg->var_off);
14446 struct tnum false_64off = false_reg->var_off;
14447 struct tnum true_32off = tnum_subreg(true_reg->var_off);
14448 struct tnum true_64off = true_reg->var_off;
14449 s64 sval = (s64)val;
14450 s32 sval32 = (s32)val32;
a72dafaf 14451
f1174f77
EC
14452 /* If the dst_reg is a pointer, we can't learn anything about its
14453 * variable offset from the compare (unless src_reg were a pointer into
14454 * the same object, but we don't bother with that.
14455 * Since false_reg and true_reg have the same type by construction, we
14456 * only need to check one of them for pointerness.
14457 */
14458 if (__is_pointer_value(false, false_reg))
14459 return;
4cabc5b1 14460
48461135 14461 switch (opcode) {
a12ca627
DB
14462 /* JEQ/JNE comparison doesn't change the register equivalence.
14463 *
14464 * r1 = r2;
14465 * if (r1 == 42) goto label;
14466 * ...
14467 * label: // here both r1 and r2 are known to be 42.
14468 *
14469 * Hence when marking register as known preserve it's ID.
14470 */
48461135 14471 case BPF_JEQ:
a12ca627
DB
14472 if (is_jmp32) {
14473 __mark_reg32_known(true_reg, val32);
14474 true_32off = tnum_subreg(true_reg->var_off);
14475 } else {
14476 ___mark_reg_known(true_reg, val);
14477 true_64off = true_reg->var_off;
14478 }
14479 break;
48461135 14480 case BPF_JNE:
a12ca627
DB
14481 if (is_jmp32) {
14482 __mark_reg32_known(false_reg, val32);
14483 false_32off = tnum_subreg(false_reg->var_off);
14484 } else {
14485 ___mark_reg_known(false_reg, val);
14486 false_64off = false_reg->var_off;
14487 }
48461135 14488 break;
960ea056 14489 case BPF_JSET:
3f50f132
JF
14490 if (is_jmp32) {
14491 false_32off = tnum_and(false_32off, tnum_const(~val32));
14492 if (is_power_of_2(val32))
14493 true_32off = tnum_or(true_32off,
14494 tnum_const(val32));
14495 } else {
14496 false_64off = tnum_and(false_64off, tnum_const(~val));
14497 if (is_power_of_2(val))
14498 true_64off = tnum_or(true_64off,
14499 tnum_const(val));
14500 }
960ea056 14501 break;
48461135 14502 case BPF_JGE:
a72dafaf
JW
14503 case BPF_JGT:
14504 {
3f50f132
JF
14505 if (is_jmp32) {
14506 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
14507 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14508
14509 false_reg->u32_max_value = min(false_reg->u32_max_value,
14510 false_umax);
14511 true_reg->u32_min_value = max(true_reg->u32_min_value,
14512 true_umin);
14513 } else {
14514 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
14515 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14516
14517 false_reg->umax_value = min(false_reg->umax_value, false_umax);
14518 true_reg->umin_value = max(true_reg->umin_value, true_umin);
14519 }
b03c9f9f 14520 break;
a72dafaf 14521 }
48461135 14522 case BPF_JSGE:
a72dafaf
JW
14523 case BPF_JSGT:
14524 {
3f50f132
JF
14525 if (is_jmp32) {
14526 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
14527 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 14528
3f50f132
JF
14529 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14530 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14531 } else {
14532 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
14533 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14534
14535 false_reg->smax_value = min(false_reg->smax_value, false_smax);
14536 true_reg->smin_value = max(true_reg->smin_value, true_smin);
14537 }
48461135 14538 break;
a72dafaf 14539 }
b4e432f1 14540 case BPF_JLE:
a72dafaf
JW
14541 case BPF_JLT:
14542 {
3f50f132
JF
14543 if (is_jmp32) {
14544 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
14545 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14546
14547 false_reg->u32_min_value = max(false_reg->u32_min_value,
14548 false_umin);
14549 true_reg->u32_max_value = min(true_reg->u32_max_value,
14550 true_umax);
14551 } else {
14552 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
14553 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14554
14555 false_reg->umin_value = max(false_reg->umin_value, false_umin);
14556 true_reg->umax_value = min(true_reg->umax_value, true_umax);
14557 }
b4e432f1 14558 break;
a72dafaf 14559 }
b4e432f1 14560 case BPF_JSLE:
a72dafaf
JW
14561 case BPF_JSLT:
14562 {
3f50f132
JF
14563 if (is_jmp32) {
14564 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
14565 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 14566
3f50f132
JF
14567 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14568 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14569 } else {
14570 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
14571 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14572
14573 false_reg->smin_value = max(false_reg->smin_value, false_smin);
14574 true_reg->smax_value = min(true_reg->smax_value, true_smax);
14575 }
b4e432f1 14576 break;
a72dafaf 14577 }
48461135 14578 default:
0fc31b10 14579 return;
48461135
JB
14580 }
14581
3f50f132
JF
14582 if (is_jmp32) {
14583 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14584 tnum_subreg(false_32off));
14585 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14586 tnum_subreg(true_32off));
14587 __reg_combine_32_into_64(false_reg);
14588 __reg_combine_32_into_64(true_reg);
14589 } else {
14590 false_reg->var_off = false_64off;
14591 true_reg->var_off = true_64off;
14592 __reg_combine_64_into_32(false_reg);
14593 __reg_combine_64_into_32(true_reg);
14594 }
48461135
JB
14595}
14596
f1174f77
EC
14597/* Same as above, but for the case that dst_reg holds a constant and src_reg is
14598 * the variable reg.
48461135
JB
14599 */
14600static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
14601 struct bpf_reg_state *false_reg,
14602 u64 val, u32 val32,
092ed096 14603 u8 opcode, bool is_jmp32)
48461135 14604{
6d94e741 14605 opcode = flip_opcode(opcode);
0fc31b10
JH
14606 /* This uses zero as "not present in table"; luckily the zero opcode,
14607 * BPF_JA, can't get here.
b03c9f9f 14608 */
0fc31b10 14609 if (opcode)
3f50f132 14610 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
14611}
14612
14613/* Regs are known to be equal, so intersect their min/max/var_off */
14614static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14615 struct bpf_reg_state *dst_reg)
14616{
b03c9f9f
EC
14617 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14618 dst_reg->umin_value);
14619 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14620 dst_reg->umax_value);
14621 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14622 dst_reg->smin_value);
14623 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14624 dst_reg->smax_value);
f1174f77
EC
14625 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14626 dst_reg->var_off);
3844d153
DB
14627 reg_bounds_sync(src_reg);
14628 reg_bounds_sync(dst_reg);
f1174f77
EC
14629}
14630
14631static void reg_combine_min_max(struct bpf_reg_state *true_src,
14632 struct bpf_reg_state *true_dst,
14633 struct bpf_reg_state *false_src,
14634 struct bpf_reg_state *false_dst,
14635 u8 opcode)
14636{
14637 switch (opcode) {
14638 case BPF_JEQ:
14639 __reg_combine_min_max(true_src, true_dst);
14640 break;
14641 case BPF_JNE:
14642 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 14643 break;
4cabc5b1 14644 }
48461135
JB
14645}
14646
fd978bf7
JS
14647static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14648 struct bpf_reg_state *reg, u32 id,
840b9615 14649 bool is_null)
57a09bf0 14650{
c25b2ae1 14651 if (type_may_be_null(reg->type) && reg->id == id &&
fca1aa75 14652 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
df57f38a
KKD
14653 /* Old offset (both fixed and variable parts) should have been
14654 * known-zero, because we don't allow pointer arithmetic on
14655 * pointers that might be NULL. If we see this happening, don't
14656 * convert the register.
14657 *
14658 * But in some cases, some helpers that return local kptrs
14659 * advance offset for the returned pointer. In those cases, it
14660 * is fine to expect to see reg->off.
14661 */
14662 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14663 return;
6a3cd331
DM
14664 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14665 WARN_ON_ONCE(reg->off))
e60b0d12 14666 return;
6a3cd331 14667
f1174f77
EC
14668 if (is_null) {
14669 reg->type = SCALAR_VALUE;
1b986589
MKL
14670 /* We don't need id and ref_obj_id from this point
14671 * onwards anymore, thus we should better reset it,
14672 * so that state pruning has chances to take effect.
14673 */
14674 reg->id = 0;
14675 reg->ref_obj_id = 0;
4ddb7416
DB
14676
14677 return;
14678 }
14679
14680 mark_ptr_not_null_reg(reg);
14681
14682 if (!reg_may_point_to_spin_lock(reg)) {
1b986589 14683 /* For not-NULL ptr, reg->ref_obj_id will be reset
b239da34 14684 * in release_reference().
1b986589
MKL
14685 *
14686 * reg->id is still used by spin_lock ptr. Other
14687 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
14688 */
14689 reg->id = 0;
56f668df 14690 }
57a09bf0
TG
14691 }
14692}
14693
14694/* The logic is similar to find_good_pkt_pointers(), both could eventually
14695 * be folded together at some point.
14696 */
840b9615
JS
14697static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14698 bool is_null)
57a09bf0 14699{
f4d7e40a 14700 struct bpf_func_state *state = vstate->frame[vstate->curframe];
b239da34 14701 struct bpf_reg_state *regs = state->regs, *reg;
1b986589 14702 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 14703 u32 id = regs[regno].id;
57a09bf0 14704
1b986589
MKL
14705 if (ref_obj_id && ref_obj_id == id && is_null)
14706 /* regs[regno] is in the " == NULL" branch.
14707 * No one could have freed the reference state before
14708 * doing the NULL check.
14709 */
14710 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 14711
b239da34
KKD
14712 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14713 mark_ptr_or_null_reg(state, reg, id, is_null);
14714 }));
57a09bf0
TG
14715}
14716
5beca081
DB
14717static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14718 struct bpf_reg_state *dst_reg,
14719 struct bpf_reg_state *src_reg,
14720 struct bpf_verifier_state *this_branch,
14721 struct bpf_verifier_state *other_branch)
14722{
14723 if (BPF_SRC(insn->code) != BPF_X)
14724 return false;
14725
092ed096
JW
14726 /* Pointers are always 64-bit. */
14727 if (BPF_CLASS(insn->code) == BPF_JMP32)
14728 return false;
14729
5beca081
DB
14730 switch (BPF_OP(insn->code)) {
14731 case BPF_JGT:
14732 if ((dst_reg->type == PTR_TO_PACKET &&
14733 src_reg->type == PTR_TO_PACKET_END) ||
14734 (dst_reg->type == PTR_TO_PACKET_META &&
14735 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14736 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14737 find_good_pkt_pointers(this_branch, dst_reg,
14738 dst_reg->type, false);
6d94e741 14739 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
14740 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14741 src_reg->type == PTR_TO_PACKET) ||
14742 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14743 src_reg->type == PTR_TO_PACKET_META)) {
14744 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14745 find_good_pkt_pointers(other_branch, src_reg,
14746 src_reg->type, true);
6d94e741 14747 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
14748 } else {
14749 return false;
14750 }
14751 break;
14752 case BPF_JLT:
14753 if ((dst_reg->type == PTR_TO_PACKET &&
14754 src_reg->type == PTR_TO_PACKET_END) ||
14755 (dst_reg->type == PTR_TO_PACKET_META &&
14756 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14757 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14758 find_good_pkt_pointers(other_branch, dst_reg,
14759 dst_reg->type, true);
6d94e741 14760 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
14761 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14762 src_reg->type == PTR_TO_PACKET) ||
14763 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14764 src_reg->type == PTR_TO_PACKET_META)) {
14765 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14766 find_good_pkt_pointers(this_branch, src_reg,
14767 src_reg->type, false);
6d94e741 14768 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
14769 } else {
14770 return false;
14771 }
14772 break;
14773 case BPF_JGE:
14774 if ((dst_reg->type == PTR_TO_PACKET &&
14775 src_reg->type == PTR_TO_PACKET_END) ||
14776 (dst_reg->type == PTR_TO_PACKET_META &&
14777 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14778 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14779 find_good_pkt_pointers(this_branch, dst_reg,
14780 dst_reg->type, true);
6d94e741 14781 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
14782 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14783 src_reg->type == PTR_TO_PACKET) ||
14784 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14785 src_reg->type == PTR_TO_PACKET_META)) {
14786 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14787 find_good_pkt_pointers(other_branch, src_reg,
14788 src_reg->type, false);
6d94e741 14789 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
14790 } else {
14791 return false;
14792 }
14793 break;
14794 case BPF_JLE:
14795 if ((dst_reg->type == PTR_TO_PACKET &&
14796 src_reg->type == PTR_TO_PACKET_END) ||
14797 (dst_reg->type == PTR_TO_PACKET_META &&
14798 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14799 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14800 find_good_pkt_pointers(other_branch, dst_reg,
14801 dst_reg->type, false);
6d94e741 14802 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
14803 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14804 src_reg->type == PTR_TO_PACKET) ||
14805 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14806 src_reg->type == PTR_TO_PACKET_META)) {
14807 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14808 find_good_pkt_pointers(this_branch, src_reg,
14809 src_reg->type, true);
6d94e741 14810 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
14811 } else {
14812 return false;
14813 }
14814 break;
14815 default:
14816 return false;
14817 }
14818
14819 return true;
14820}
14821
75748837
AS
14822static void find_equal_scalars(struct bpf_verifier_state *vstate,
14823 struct bpf_reg_state *known_reg)
14824{
14825 struct bpf_func_state *state;
14826 struct bpf_reg_state *reg;
75748837 14827
b239da34
KKD
14828 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14829 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
71f656a5 14830 copy_register_state(reg, known_reg);
b239da34 14831 }));
75748837
AS
14832}
14833
58e2af8b 14834static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
14835 struct bpf_insn *insn, int *insn_idx)
14836{
f4d7e40a
AS
14837 struct bpf_verifier_state *this_branch = env->cur_state;
14838 struct bpf_verifier_state *other_branch;
14839 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 14840 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
befae758 14841 struct bpf_reg_state *eq_branch_regs;
17a52670 14842 u8 opcode = BPF_OP(insn->code);
092ed096 14843 bool is_jmp32;
fb8d251e 14844 int pred = -1;
17a52670
AS
14845 int err;
14846
092ed096
JW
14847 /* Only conditional jumps are expected to reach here. */
14848 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14849 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
14850 return -EINVAL;
14851 }
14852
d75e30dd
YS
14853 /* check src2 operand */
14854 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14855 if (err)
14856 return err;
14857
14858 dst_reg = &regs[insn->dst_reg];
17a52670
AS
14859 if (BPF_SRC(insn->code) == BPF_X) {
14860 if (insn->imm != 0) {
092ed096 14861 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
14862 return -EINVAL;
14863 }
14864
14865 /* check src1 operand */
dc503a8a 14866 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
14867 if (err)
14868 return err;
1be7f75d 14869
d75e30dd
YS
14870 src_reg = &regs[insn->src_reg];
14871 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14872 is_pointer_value(env, insn->src_reg)) {
61bd5218 14873 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
14874 insn->src_reg);
14875 return -EACCES;
14876 }
17a52670
AS
14877 } else {
14878 if (insn->src_reg != BPF_REG_0) {
092ed096 14879 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
14880 return -EINVAL;
14881 }
14882 }
14883
092ed096 14884 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 14885
3f50f132
JF
14886 if (BPF_SRC(insn->code) == BPF_K) {
14887 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14888 } else if (src_reg->type == SCALAR_VALUE &&
14889 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14890 pred = is_branch_taken(dst_reg,
14891 tnum_subreg(src_reg->var_off).value,
14892 opcode,
14893 is_jmp32);
14894 } else if (src_reg->type == SCALAR_VALUE &&
14895 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14896 pred = is_branch_taken(dst_reg,
14897 src_reg->var_off.value,
14898 opcode,
14899 is_jmp32);
953d9f5b
YS
14900 } else if (dst_reg->type == SCALAR_VALUE &&
14901 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14902 pred = is_branch_taken(src_reg,
14903 tnum_subreg(dst_reg->var_off).value,
14904 flip_opcode(opcode),
14905 is_jmp32);
14906 } else if (dst_reg->type == SCALAR_VALUE &&
14907 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14908 pred = is_branch_taken(src_reg,
14909 dst_reg->var_off.value,
14910 flip_opcode(opcode),
14911 is_jmp32);
6d94e741
AS
14912 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14913 reg_is_pkt_pointer_any(src_reg) &&
14914 !is_jmp32) {
14915 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
14916 }
14917
b5dc0163 14918 if (pred >= 0) {
cac616db
JF
14919 /* If we get here with a dst_reg pointer type it is because
14920 * above is_branch_taken() special cased the 0 comparison.
14921 */
14922 if (!__is_pointer_value(false, dst_reg))
14923 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
14924 if (BPF_SRC(insn->code) == BPF_X && !err &&
14925 !__is_pointer_value(false, src_reg))
b5dc0163
AS
14926 err = mark_chain_precision(env, insn->src_reg);
14927 if (err)
14928 return err;
14929 }
9183671a 14930
fb8d251e 14931 if (pred == 1) {
9183671a
DB
14932 /* Only follow the goto, ignore fall-through. If needed, push
14933 * the fall-through branch for simulation under speculative
14934 * execution.
14935 */
14936 if (!env->bypass_spec_v1 &&
14937 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14938 *insn_idx))
14939 return -EFAULT;
1a8a315f
AN
14940 if (env->log.level & BPF_LOG_LEVEL)
14941 print_insn_state(env, this_branch->frame[this_branch->curframe]);
fb8d251e
AS
14942 *insn_idx += insn->off;
14943 return 0;
14944 } else if (pred == 0) {
9183671a
DB
14945 /* Only follow the fall-through branch, since that's where the
14946 * program will go. If needed, push the goto branch for
14947 * simulation under speculative execution.
fb8d251e 14948 */
9183671a
DB
14949 if (!env->bypass_spec_v1 &&
14950 !sanitize_speculative_path(env, insn,
14951 *insn_idx + insn->off + 1,
14952 *insn_idx))
14953 return -EFAULT;
1a8a315f
AN
14954 if (env->log.level & BPF_LOG_LEVEL)
14955 print_insn_state(env, this_branch->frame[this_branch->curframe]);
fb8d251e 14956 return 0;
17a52670
AS
14957 }
14958
979d63d5
DB
14959 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14960 false);
17a52670
AS
14961 if (!other_branch)
14962 return -EFAULT;
f4d7e40a 14963 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 14964
48461135
JB
14965 /* detect if we are comparing against a constant value so we can adjust
14966 * our min/max values for our dst register.
f1174f77 14967 * this is only legit if both are scalars (or pointers to the same
befae758
EZ
14968 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14969 * because otherwise the different base pointers mean the offsets aren't
f1174f77 14970 * comparable.
48461135
JB
14971 */
14972 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 14973 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 14974
f1174f77 14975 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
14976 src_reg->type == SCALAR_VALUE) {
14977 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
14978 (is_jmp32 &&
14979 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 14980 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 14981 dst_reg,
3f50f132
JF
14982 src_reg->var_off.value,
14983 tnum_subreg(src_reg->var_off).value,
092ed096
JW
14984 opcode, is_jmp32);
14985 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
14986 (is_jmp32 &&
14987 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 14988 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 14989 src_reg,
3f50f132
JF
14990 dst_reg->var_off.value,
14991 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
14992 opcode, is_jmp32);
14993 else if (!is_jmp32 &&
14994 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 14995 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
14996 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14997 &other_branch_regs[insn->dst_reg],
092ed096 14998 src_reg, dst_reg, opcode);
e688c3db
AS
14999 if (src_reg->id &&
15000 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
15001 find_equal_scalars(this_branch, src_reg);
15002 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15003 }
15004
f1174f77
EC
15005 }
15006 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 15007 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
15008 dst_reg, insn->imm, (u32)insn->imm,
15009 opcode, is_jmp32);
48461135
JB
15010 }
15011
e688c3db
AS
15012 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15013 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
15014 find_equal_scalars(this_branch, dst_reg);
15015 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15016 }
15017
befae758
EZ
15018 /* if one pointer register is compared to another pointer
15019 * register check if PTR_MAYBE_NULL could be lifted.
15020 * E.g. register A - maybe null
15021 * register B - not null
15022 * for JNE A, B, ... - A is not null in the false branch;
15023 * for JEQ A, B, ... - A is not null in the true branch.
8374bfd5
HS
15024 *
15025 * Since PTR_TO_BTF_ID points to a kernel struct that does
15026 * not need to be null checked by the BPF program, i.e.,
15027 * could be null even without PTR_MAYBE_NULL marking, so
15028 * only propagate nullness when neither reg is that type.
befae758
EZ
15029 */
15030 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15031 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
8374bfd5
HS
15032 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15033 base_type(src_reg->type) != PTR_TO_BTF_ID &&
15034 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
befae758
EZ
15035 eq_branch_regs = NULL;
15036 switch (opcode) {
15037 case BPF_JEQ:
15038 eq_branch_regs = other_branch_regs;
15039 break;
15040 case BPF_JNE:
15041 eq_branch_regs = regs;
15042 break;
15043 default:
15044 /* do nothing */
15045 break;
15046 }
15047 if (eq_branch_regs) {
15048 if (type_may_be_null(src_reg->type))
15049 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15050 else
15051 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15052 }
15053 }
15054
092ed096
JW
15055 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15056 * NOTE: these optimizations below are related with pointer comparison
15057 * which will never be JMP32.
15058 */
15059 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 15060 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
c25b2ae1 15061 type_may_be_null(dst_reg->type)) {
840b9615 15062 /* Mark all identical registers in each branch as either
57a09bf0
TG
15063 * safe or unknown depending R == 0 or R != 0 conditional.
15064 */
840b9615
JS
15065 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15066 opcode == BPF_JNE);
15067 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15068 opcode == BPF_JEQ);
5beca081
DB
15069 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15070 this_branch, other_branch) &&
15071 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
15072 verbose(env, "R%d pointer comparison prohibited\n",
15073 insn->dst_reg);
1be7f75d 15074 return -EACCES;
17a52670 15075 }
06ee7115 15076 if (env->log.level & BPF_LOG_LEVEL)
2e576648 15077 print_insn_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
15078 return 0;
15079}
15080
17a52670 15081/* verify BPF_LD_IMM64 instruction */
58e2af8b 15082static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 15083{
d8eca5bb 15084 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 15085 struct bpf_reg_state *regs = cur_regs(env);
4976b718 15086 struct bpf_reg_state *dst_reg;
d8eca5bb 15087 struct bpf_map *map;
17a52670
AS
15088 int err;
15089
15090 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 15091 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
15092 return -EINVAL;
15093 }
15094 if (insn->off != 0) {
61bd5218 15095 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
15096 return -EINVAL;
15097 }
15098
dc503a8a 15099 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
15100 if (err)
15101 return err;
15102
4976b718 15103 dst_reg = &regs[insn->dst_reg];
6b173873 15104 if (insn->src_reg == 0) {
6b173873
JK
15105 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15106
4976b718 15107 dst_reg->type = SCALAR_VALUE;
b03c9f9f 15108 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 15109 return 0;
6b173873 15110 }
17a52670 15111
d400a6cf
DB
15112 /* All special src_reg cases are listed below. From this point onwards
15113 * we either succeed and assign a corresponding dst_reg->type after
15114 * zeroing the offset, or fail and reject the program.
15115 */
15116 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 15117
d400a6cf 15118 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
4976b718 15119 dst_reg->type = aux->btf_var.reg_type;
34d3a78c 15120 switch (base_type(dst_reg->type)) {
4976b718
HL
15121 case PTR_TO_MEM:
15122 dst_reg->mem_size = aux->btf_var.mem_size;
15123 break;
15124 case PTR_TO_BTF_ID:
22dc4a0f 15125 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
15126 dst_reg->btf_id = aux->btf_var.btf_id;
15127 break;
15128 default:
15129 verbose(env, "bpf verifier is misconfigured\n");
15130 return -EFAULT;
15131 }
15132 return 0;
15133 }
15134
69c087ba
YS
15135 if (insn->src_reg == BPF_PSEUDO_FUNC) {
15136 struct bpf_prog_aux *aux = env->prog->aux;
3990ed4c
MKL
15137 u32 subprogno = find_subprog(env,
15138 env->insn_idx + insn->imm + 1);
69c087ba
YS
15139
15140 if (!aux->func_info) {
15141 verbose(env, "missing btf func_info\n");
15142 return -EINVAL;
15143 }
15144 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15145 verbose(env, "callback function not static\n");
15146 return -EINVAL;
15147 }
15148
15149 dst_reg->type = PTR_TO_FUNC;
15150 dst_reg->subprogno = subprogno;
15151 return 0;
15152 }
15153
d8eca5bb 15154 map = env->used_maps[aux->map_index];
4976b718 15155 dst_reg->map_ptr = map;
d8eca5bb 15156
387544bf
AS
15157 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15158 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
4976b718
HL
15159 dst_reg->type = PTR_TO_MAP_VALUE;
15160 dst_reg->off = aux->map_off;
d0d78c1d
KKD
15161 WARN_ON_ONCE(map->max_entries != 1);
15162 /* We want reg->id to be same (0) as map_value is not distinct */
387544bf
AS
15163 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15164 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
4976b718 15165 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
15166 } else {
15167 verbose(env, "bpf verifier is misconfigured\n");
15168 return -EINVAL;
15169 }
17a52670 15170
17a52670
AS
15171 return 0;
15172}
15173
96be4325
DB
15174static bool may_access_skb(enum bpf_prog_type type)
15175{
15176 switch (type) {
15177 case BPF_PROG_TYPE_SOCKET_FILTER:
15178 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 15179 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
15180 return true;
15181 default:
15182 return false;
15183 }
15184}
15185
ddd872bc
AS
15186/* verify safety of LD_ABS|LD_IND instructions:
15187 * - they can only appear in the programs where ctx == skb
15188 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15189 * preserve R6-R9, and store return value into R0
15190 *
15191 * Implicit input:
15192 * ctx == skb == R6 == CTX
15193 *
15194 * Explicit input:
15195 * SRC == any register
15196 * IMM == 32-bit immediate
15197 *
15198 * Output:
15199 * R0 - 8/16/32-bit skb data converted to cpu endianness
15200 */
58e2af8b 15201static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 15202{
638f5b90 15203 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 15204 static const int ctx_reg = BPF_REG_6;
ddd872bc 15205 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
15206 int i, err;
15207
7e40781c 15208 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 15209 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
15210 return -EINVAL;
15211 }
15212
e0cea7ce
DB
15213 if (!env->ops->gen_ld_abs) {
15214 verbose(env, "bpf verifier is misconfigured\n");
15215 return -EINVAL;
15216 }
15217
ddd872bc 15218 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 15219 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 15220 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 15221 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
15222 return -EINVAL;
15223 }
15224
15225 /* check whether implicit source operand (register R6) is readable */
6d4f151a 15226 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
15227 if (err)
15228 return err;
15229
fd978bf7
JS
15230 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15231 * gen_ld_abs() may terminate the program at runtime, leading to
15232 * reference leak.
15233 */
f18b03fa 15234 err = check_reference_leak(env, false);
fd978bf7
JS
15235 if (err) {
15236 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15237 return err;
15238 }
15239
d0d78c1d 15240 if (env->cur_state->active_lock.ptr) {
d83525ca
AS
15241 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15242 return -EINVAL;
15243 }
15244
9bb00b28
YS
15245 if (env->cur_state->active_rcu_lock) {
15246 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15247 return -EINVAL;
15248 }
15249
6d4f151a 15250 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
15251 verbose(env,
15252 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
15253 return -EINVAL;
15254 }
15255
15256 if (mode == BPF_IND) {
15257 /* check explicit source operand */
dc503a8a 15258 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
15259 if (err)
15260 return err;
15261 }
15262
be80a1d3 15263 err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
6d4f151a
DB
15264 if (err < 0)
15265 return err;
15266
ddd872bc 15267 /* reset caller saved regs to unreadable */
dc503a8a 15268 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 15269 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
15270 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15271 }
ddd872bc
AS
15272
15273 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
15274 * the value fetched from the packet.
15275 * Already marked as written above.
ddd872bc 15276 */
61bd5218 15277 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
15278 /* ld_abs load up to 32-bit skb data. */
15279 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
15280 return 0;
15281}
15282
a923819f 15283static int check_return_code(struct bpf_verifier_env *env, int regno)
390ee7e2 15284{
5cf1e914 15285 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 15286 const struct bpf_prog *prog = env->prog;
390ee7e2 15287 struct bpf_reg_state *reg;
82995598 15288 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
7e40781c 15289 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 15290 int err;
bfc6bb74
AS
15291 struct bpf_func_state *frame = env->cur_state->frame[0];
15292 const bool is_subprog = frame->subprogno;
27ae7997 15293
9e4e01df 15294 /* LSM and struct_ops func-ptr's return type could be "void" */
b9ae0c9d 15295 if (!is_subprog || frame->in_exception_callback_fn) {
d1a6edec
SF
15296 switch (prog_type) {
15297 case BPF_PROG_TYPE_LSM:
15298 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15299 /* See below, can be 0 or 0-1 depending on hook. */
15300 break;
15301 fallthrough;
15302 case BPF_PROG_TYPE_STRUCT_OPS:
15303 if (!prog->aux->attach_func_proto->type)
15304 return 0;
15305 break;
15306 default:
15307 break;
15308 }
15309 }
27ae7997 15310
8fb33b60 15311 /* eBPF calling convention is such that R0 is used
27ae7997
MKL
15312 * to return the value from eBPF program.
15313 * Make sure that it's readable at this time
15314 * of bpf_exit, which means that program wrote
15315 * something into it earlier
15316 */
a923819f 15317 err = check_reg_arg(env, regno, SRC_OP);
27ae7997
MKL
15318 if (err)
15319 return err;
15320
a923819f
KKD
15321 if (is_pointer_value(env, regno)) {
15322 verbose(env, "R%d leaks addr as return value\n", regno);
27ae7997
MKL
15323 return -EACCES;
15324 }
390ee7e2 15325
a923819f 15326 reg = cur_regs(env) + regno;
bfc6bb74
AS
15327
15328 if (frame->in_async_callback_fn) {
15329 /* enforce return zero from async callbacks like timer */
15330 if (reg->type != SCALAR_VALUE) {
a923819f
KKD
15331 verbose(env, "In async callback the register R%d is not a known value (%s)\n",
15332 regno, reg_type_str(env, reg->type));
bfc6bb74
AS
15333 return -EINVAL;
15334 }
15335
82995598
DV
15336 if (!tnum_in(const_0, reg->var_off)) {
15337 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
bfc6bb74
AS
15338 return -EINVAL;
15339 }
15340 return 0;
15341 }
15342
b9ae0c9d 15343 if (is_subprog && !frame->in_exception_callback_fn) {
f782e2c3 15344 if (reg->type != SCALAR_VALUE) {
a923819f
KKD
15345 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15346 regno, reg_type_str(env, reg->type));
f782e2c3
DB
15347 return -EINVAL;
15348 }
15349 return 0;
15350 }
15351
7e40781c 15352 switch (prog_type) {
983695fa
DB
15353 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15354 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253 15355 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
859051dd 15356 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
1b66d253
DB
15357 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15358 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
859051dd 15359 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
1b66d253 15360 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
859051dd
DDM
15361 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15362 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
983695fa 15363 range = tnum_range(1, 1);
77241217
SF
15364 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15365 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15366 range = tnum_range(0, 3);
ed4ed404 15367 break;
390ee7e2 15368 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 15369 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15370 range = tnum_range(0, 3);
15371 enforce_attach_type_range = tnum_range(2, 3);
15372 }
ed4ed404 15373 break;
390ee7e2
AS
15374 case BPF_PROG_TYPE_CGROUP_SOCK:
15375 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 15376 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 15377 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 15378 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 15379 break;
15ab09bd
AS
15380 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15381 if (!env->prog->aux->attach_btf_id)
15382 return 0;
15383 range = tnum_const(0);
15384 break;
15d83c4d 15385 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
15386 switch (env->prog->expected_attach_type) {
15387 case BPF_TRACE_FENTRY:
15388 case BPF_TRACE_FEXIT:
15389 range = tnum_const(0);
15390 break;
15391 case BPF_TRACE_RAW_TP:
15392 case BPF_MODIFY_RETURN:
15d83c4d 15393 return 0;
2ec0616e
DB
15394 case BPF_TRACE_ITER:
15395 break;
e92888c7
YS
15396 default:
15397 return -ENOTSUPP;
15398 }
15d83c4d 15399 break;
e9ddbb77
JS
15400 case BPF_PROG_TYPE_SK_LOOKUP:
15401 range = tnum_range(SK_DROP, SK_PASS);
15402 break;
69fd337a
SF
15403
15404 case BPF_PROG_TYPE_LSM:
15405 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15406 /* Regular BPF_PROG_TYPE_LSM programs can return
15407 * any value.
15408 */
15409 return 0;
15410 }
15411 if (!env->prog->aux->attach_func_proto->type) {
15412 /* Make sure programs that attach to void
15413 * hooks don't try to modify return value.
15414 */
15415 range = tnum_range(1, 1);
15416 }
15417 break;
15418
fd9c663b
FW
15419 case BPF_PROG_TYPE_NETFILTER:
15420 range = tnum_range(NF_DROP, NF_ACCEPT);
15421 break;
e92888c7
YS
15422 case BPF_PROG_TYPE_EXT:
15423 /* freplace program can return anything as its return value
15424 * depends on the to-be-replaced kernel func or bpf program.
15425 */
390ee7e2
AS
15426 default:
15427 return 0;
15428 }
15429
390ee7e2 15430 if (reg->type != SCALAR_VALUE) {
a923819f
KKD
15431 verbose(env, "At program exit the register R%d is not a known value (%s)\n",
15432 regno, reg_type_str(env, reg->type));
390ee7e2
AS
15433 return -EINVAL;
15434 }
15435
15436 if (!tnum_in(range, reg->var_off)) {
bc2591d6 15437 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
69fd337a 15438 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
d1a6edec 15439 prog_type == BPF_PROG_TYPE_LSM &&
69fd337a
SF
15440 !prog->aux->attach_func_proto->type)
15441 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
390ee7e2
AS
15442 return -EINVAL;
15443 }
5cf1e914 15444
15445 if (!tnum_is_unknown(enforce_attach_type_range) &&
15446 tnum_in(enforce_attach_type_range, reg->var_off))
15447 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
15448 return 0;
15449}
15450
475fb78f
AS
15451/* non-recursive DFS pseudo code
15452 * 1 procedure DFS-iterative(G,v):
15453 * 2 label v as discovered
15454 * 3 let S be a stack
15455 * 4 S.push(v)
15456 * 5 while S is not empty
b6d20799 15457 * 6 t <- S.peek()
475fb78f
AS
15458 * 7 if t is what we're looking for:
15459 * 8 return t
15460 * 9 for all edges e in G.adjacentEdges(t) do
15461 * 10 if edge e is already labelled
15462 * 11 continue with the next edge
15463 * 12 w <- G.adjacentVertex(t,e)
15464 * 13 if vertex w is not discovered and not explored
15465 * 14 label e as tree-edge
15466 * 15 label w as discovered
15467 * 16 S.push(w)
15468 * 17 continue at 5
15469 * 18 else if vertex w is discovered
15470 * 19 label e as back-edge
15471 * 20 else
15472 * 21 // vertex w is explored
15473 * 22 label e as forward- or cross-edge
15474 * 23 label t as explored
15475 * 24 S.pop()
15476 *
15477 * convention:
15478 * 0x10 - discovered
15479 * 0x11 - discovered and fall-through edge labelled
15480 * 0x12 - discovered and fall-through and branch edges labelled
15481 * 0x20 - explored
15482 */
15483
15484enum {
15485 DISCOVERED = 0x10,
15486 EXPLORED = 0x20,
15487 FALLTHROUGH = 1,
15488 BRANCH = 2,
15489};
15490
bffdeaa8 15491static void mark_prune_point(struct bpf_verifier_env *env, int idx)
5d839021 15492{
a8f500af 15493 env->insn_aux_data[idx].prune_point = true;
5d839021 15494}
f1bca824 15495
bffdeaa8
AN
15496static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15497{
15498 return env->insn_aux_data[insn_idx].prune_point;
15499}
15500
4b5ce570
AN
15501static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15502{
15503 env->insn_aux_data[idx].force_checkpoint = true;
15504}
15505
15506static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15507{
15508 return env->insn_aux_data[insn_idx].force_checkpoint;
15509}
15510
ab5cfac1
EZ
15511static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15512{
15513 env->insn_aux_data[idx].calls_callback = true;
15514}
15515
15516static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15517{
15518 return env->insn_aux_data[insn_idx].calls_callback;
15519}
4b5ce570 15520
59e2e27d
WAF
15521enum {
15522 DONE_EXPLORING = 0,
15523 KEEP_EXPLORING = 1,
15524};
15525
475fb78f
AS
15526/* t, w, e - match pseudo-code above:
15527 * t - index of current instruction
15528 * w - next instruction
15529 * e - edge
15530 */
10e14e96 15531static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f 15532{
7df737e9
AS
15533 int *insn_stack = env->cfg.insn_stack;
15534 int *insn_state = env->cfg.insn_state;
15535
475fb78f 15536 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 15537 return DONE_EXPLORING;
475fb78f
AS
15538
15539 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 15540 return DONE_EXPLORING;
475fb78f
AS
15541
15542 if (w < 0 || w >= env->prog->len) {
d9762e84 15543 verbose_linfo(env, t, "%d: ", t);
61bd5218 15544 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
15545 return -EINVAL;
15546 }
15547
bffdeaa8 15548 if (e == BRANCH) {
f1bca824 15549 /* mark branch target for state pruning */
bffdeaa8
AN
15550 mark_prune_point(env, w);
15551 mark_jmp_point(env, w);
15552 }
f1bca824 15553
475fb78f
AS
15554 if (insn_state[w] == 0) {
15555 /* tree-edge */
15556 insn_state[t] = DISCOVERED | e;
15557 insn_state[w] = DISCOVERED;
7df737e9 15558 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 15559 return -E2BIG;
7df737e9 15560 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 15561 return KEEP_EXPLORING;
475fb78f 15562 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10e14e96 15563 if (env->bpf_capable)
59e2e27d 15564 return DONE_EXPLORING;
d9762e84
MKL
15565 verbose_linfo(env, t, "%d: ", t);
15566 verbose_linfo(env, w, "%d: ", w);
61bd5218 15567 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
15568 return -EINVAL;
15569 } else if (insn_state[w] == EXPLORED) {
15570 /* forward- or cross-edge */
15571 insn_state[t] = DISCOVERED | e;
15572 } else {
61bd5218 15573 verbose(env, "insn state internal bug\n");
475fb78f
AS
15574 return -EFAULT;
15575 }
59e2e27d
WAF
15576 return DONE_EXPLORING;
15577}
15578
dcb2288b 15579static int visit_func_call_insn(int t, struct bpf_insn *insns,
efdb22de
YS
15580 struct bpf_verifier_env *env,
15581 bool visit_callee)
15582{
3feb263b 15583 int ret, insn_sz;
efdb22de 15584
3feb263b 15585 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
10e14e96 15586 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
efdb22de
YS
15587 if (ret)
15588 return ret;
15589
3feb263b 15590 mark_prune_point(env, t + insn_sz);
618945fb 15591 /* when we exit from subprog, we need to record non-linear history */
3feb263b 15592 mark_jmp_point(env, t + insn_sz);
618945fb 15593
efdb22de 15594 if (visit_callee) {
bffdeaa8 15595 mark_prune_point(env, t);
10e14e96 15596 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
efdb22de
YS
15597 }
15598 return ret;
15599}
15600
59e2e27d
WAF
15601/* Visits the instruction at index t and returns one of the following:
15602 * < 0 - an error occurred
15603 * DONE_EXPLORING - the instruction was fully explored
15604 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15605 */
dcb2288b 15606static int visit_insn(int t, struct bpf_verifier_env *env)
59e2e27d 15607{
653ae3a8 15608 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
3feb263b 15609 int ret, off, insn_sz;
59e2e27d 15610
653ae3a8 15611 if (bpf_pseudo_func(insn))
dcb2288b 15612 return visit_func_call_insn(t, insns, env, true);
69c087ba 15613
59e2e27d 15614 /* All non-branch instructions have a single fall-through edge. */
653ae3a8 15615 if (BPF_CLASS(insn->code) != BPF_JMP &&
3feb263b
AN
15616 BPF_CLASS(insn->code) != BPF_JMP32) {
15617 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
10e14e96 15618 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
3feb263b 15619 }
59e2e27d 15620
653ae3a8 15621 switch (BPF_OP(insn->code)) {
59e2e27d
WAF
15622 case BPF_EXIT:
15623 return DONE_EXPLORING;
15624
15625 case BPF_CALL:
c1ee85a9 15626 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
618945fb
AN
15627 /* Mark this call insn as a prune point to trigger
15628 * is_state_visited() check before call itself is
15629 * processed by __check_func_call(). Otherwise new
15630 * async state will be pushed for further exploration.
bfc6bb74 15631 */
bffdeaa8 15632 mark_prune_point(env, t);
ab5cfac1
EZ
15633 /* For functions that invoke callbacks it is not known how many times
15634 * callback would be called. Verifier models callback calling functions
15635 * by repeatedly visiting callback bodies and returning to origin call
15636 * instruction.
15637 * In order to stop such iteration verifier needs to identify when a
15638 * state identical some state from a previous iteration is reached.
15639 * Check below forces creation of checkpoint before callback calling
15640 * instruction to allow search for such identical states.
15641 */
15642 if (is_sync_callback_calling_insn(insn)) {
15643 mark_calls_callback(env, t);
15644 mark_force_checkpoint(env, t);
15645 mark_prune_point(env, t);
15646 mark_jmp_point(env, t);
15647 }
06accc87
AN
15648 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15649 struct bpf_kfunc_call_arg_meta meta;
15650
15651 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
4b5ce570 15652 if (ret == 0 && is_iter_next_kfunc(&meta)) {
06accc87 15653 mark_prune_point(env, t);
4b5ce570
AN
15654 /* Checking and saving state checkpoints at iter_next() call
15655 * is crucial for fast convergence of open-coded iterator loop
15656 * logic, so we need to force it. If we don't do that,
15657 * is_state_visited() might skip saving a checkpoint, causing
15658 * unnecessarily long sequence of not checkpointed
15659 * instructions and jumps, leading to exhaustion of jump
15660 * history buffer, and potentially other undesired outcomes.
15661 * It is expected that with correct open-coded iterators
15662 * convergence will happen quickly, so we don't run a risk of
15663 * exhausting memory.
15664 */
15665 mark_force_checkpoint(env, t);
15666 }
06accc87 15667 }
653ae3a8 15668 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
15669
15670 case BPF_JA:
653ae3a8 15671 if (BPF_SRC(insn->code) != BPF_K)
59e2e27d
WAF
15672 return -EINVAL;
15673
4cd58e9a
YS
15674 if (BPF_CLASS(insn->code) == BPF_JMP)
15675 off = insn->off;
15676 else
15677 off = insn->imm;
15678
59e2e27d 15679 /* unconditional jump with single edge */
10e14e96 15680 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
59e2e27d
WAF
15681 if (ret)
15682 return ret;
15683
4cd58e9a
YS
15684 mark_prune_point(env, t + off + 1);
15685 mark_jmp_point(env, t + off + 1);
59e2e27d
WAF
15686
15687 return ret;
15688
15689 default:
15690 /* conditional jump with two edges */
bffdeaa8 15691 mark_prune_point(env, t);
618945fb 15692
10e14e96 15693 ret = push_insn(t, t + 1, FALLTHROUGH, env);
59e2e27d
WAF
15694 if (ret)
15695 return ret;
15696
10e14e96 15697 return push_insn(t, t + insn->off + 1, BRANCH, env);
59e2e27d 15698 }
475fb78f
AS
15699}
15700
15701/* non-recursive depth-first-search to detect loops in BPF program
15702 * loop == back-edge in directed graph
15703 */
58e2af8b 15704static int check_cfg(struct bpf_verifier_env *env)
475fb78f 15705{
475fb78f 15706 int insn_cnt = env->prog->len;
7df737e9 15707 int *insn_stack, *insn_state;
b62bf8a5
KKD
15708 int ex_insn_beg, i, ret = 0;
15709 bool ex_done = false;
475fb78f 15710
7df737e9 15711 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
15712 if (!insn_state)
15713 return -ENOMEM;
15714
7df737e9 15715 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 15716 if (!insn_stack) {
71dde681 15717 kvfree(insn_state);
475fb78f
AS
15718 return -ENOMEM;
15719 }
15720
15721 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15722 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 15723 env->cfg.cur_stack = 1;
475fb78f 15724
b62bf8a5 15725walk_cfg:
59e2e27d
WAF
15726 while (env->cfg.cur_stack > 0) {
15727 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 15728
dcb2288b 15729 ret = visit_insn(t, env);
59e2e27d
WAF
15730 switch (ret) {
15731 case DONE_EXPLORING:
15732 insn_state[t] = EXPLORED;
15733 env->cfg.cur_stack--;
15734 break;
15735 case KEEP_EXPLORING:
15736 break;
15737 default:
15738 if (ret > 0) {
15739 verbose(env, "visit_insn internal bug\n");
15740 ret = -EFAULT;
475fb78f 15741 }
475fb78f 15742 goto err_free;
59e2e27d 15743 }
475fb78f
AS
15744 }
15745
59e2e27d 15746 if (env->cfg.cur_stack < 0) {
61bd5218 15747 verbose(env, "pop stack internal bug\n");
475fb78f
AS
15748 ret = -EFAULT;
15749 goto err_free;
15750 }
475fb78f 15751
b62bf8a5
KKD
15752 if (env->exception_callback_subprog && !ex_done) {
15753 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15754
15755 insn_state[ex_insn_beg] = DISCOVERED;
15756 insn_stack[0] = ex_insn_beg;
15757 env->cfg.cur_stack = 1;
15758 ex_done = true;
15759 goto walk_cfg;
15760 }
15761
475fb78f 15762 for (i = 0; i < insn_cnt; i++) {
3feb263b
AN
15763 struct bpf_insn *insn = &env->prog->insnsi[i];
15764
475fb78f 15765 if (insn_state[i] != EXPLORED) {
61bd5218 15766 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
15767 ret = -EINVAL;
15768 goto err_free;
15769 }
3feb263b
AN
15770 if (bpf_is_ldimm64(insn)) {
15771 if (insn_state[i + 1] != 0) {
15772 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15773 ret = -EINVAL;
15774 goto err_free;
15775 }
15776 i++; /* skip second half of ldimm64 */
15777 }
475fb78f
AS
15778 }
15779 ret = 0; /* cfg looks good */
15780
15781err_free:
71dde681
AS
15782 kvfree(insn_state);
15783 kvfree(insn_stack);
7df737e9 15784 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
15785 return ret;
15786}
15787
09b28d76
AS
15788static int check_abnormal_return(struct bpf_verifier_env *env)
15789{
15790 int i;
15791
15792 for (i = 1; i < env->subprog_cnt; i++) {
15793 if (env->subprog_info[i].has_ld_abs) {
15794 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15795 return -EINVAL;
15796 }
15797 if (env->subprog_info[i].has_tail_call) {
15798 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15799 return -EINVAL;
15800 }
15801 }
15802 return 0;
15803}
15804
838e9690
YS
15805/* The minimum supported BTF func info size */
15806#define MIN_BPF_FUNCINFO_SIZE 8
15807#define MAX_FUNCINFO_REC_SIZE 252
15808
aaa619eb
KKD
15809static int check_btf_func_early(struct bpf_verifier_env *env,
15810 const union bpf_attr *attr,
15811 bpfptr_t uattr)
838e9690 15812{
838e9690 15813 u32 krec_size = sizeof(struct bpf_func_info);
aaa619eb
KKD
15814 const struct btf_type *type, *func_proto;
15815 u32 i, nfuncs, urec_size, min_size;
c454a46b 15816 struct bpf_func_info *krecord;
c454a46b
MKL
15817 struct bpf_prog *prog;
15818 const struct btf *btf;
d0b2818e 15819 u32 prev_offset = 0;
aaa619eb 15820 bpfptr_t urecord;
e7ed83d6 15821 int ret = -ENOMEM;
838e9690
YS
15822
15823 nfuncs = attr->func_info_cnt;
09b28d76
AS
15824 if (!nfuncs) {
15825 if (check_abnormal_return(env))
15826 return -EINVAL;
838e9690 15827 return 0;
09b28d76 15828 }
838e9690 15829
838e9690
YS
15830 urec_size = attr->func_info_rec_size;
15831 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15832 urec_size > MAX_FUNCINFO_REC_SIZE ||
15833 urec_size % sizeof(u32)) {
15834 verbose(env, "invalid func info rec size %u\n", urec_size);
15835 return -EINVAL;
15836 }
15837
c454a46b
MKL
15838 prog = env->prog;
15839 btf = prog->aux->btf;
838e9690 15840
af2ac3e1 15841 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
838e9690
YS
15842 min_size = min_t(u32, krec_size, urec_size);
15843
ba64e7d8 15844 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
15845 if (!krecord)
15846 return -ENOMEM;
ba64e7d8 15847
838e9690
YS
15848 for (i = 0; i < nfuncs; i++) {
15849 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15850 if (ret) {
15851 if (ret == -E2BIG) {
15852 verbose(env, "nonzero tailing record in func info");
15853 /* set the size kernel expects so loader can zero
15854 * out the rest of the record.
15855 */
af2ac3e1
AS
15856 if (copy_to_bpfptr_offset(uattr,
15857 offsetof(union bpf_attr, func_info_rec_size),
15858 &min_size, sizeof(min_size)))
838e9690
YS
15859 ret = -EFAULT;
15860 }
c454a46b 15861 goto err_free;
838e9690
YS
15862 }
15863
af2ac3e1 15864 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
838e9690 15865 ret = -EFAULT;
c454a46b 15866 goto err_free;
838e9690
YS
15867 }
15868
d30d42e0 15869 /* check insn_off */
09b28d76 15870 ret = -EINVAL;
838e9690 15871 if (i == 0) {
d30d42e0 15872 if (krecord[i].insn_off) {
838e9690 15873 verbose(env,
d30d42e0
MKL
15874 "nonzero insn_off %u for the first func info record",
15875 krecord[i].insn_off);
c454a46b 15876 goto err_free;
838e9690 15877 }
d30d42e0 15878 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
15879 verbose(env,
15880 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 15881 krecord[i].insn_off, prev_offset);
c454a46b 15882 goto err_free;
838e9690
YS
15883 }
15884
838e9690 15885 /* check type_id */
ba64e7d8 15886 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 15887 if (!type || !btf_type_is_func(type)) {
838e9690 15888 verbose(env, "invalid type id %d in func info",
ba64e7d8 15889 krecord[i].type_id);
c454a46b 15890 goto err_free;
838e9690 15891 }
09b28d76
AS
15892
15893 func_proto = btf_type_by_id(btf, type->type);
15894 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15895 /* btf_func_check() already verified it during BTF load */
15896 goto err_free;
aaa619eb
KKD
15897
15898 prev_offset = krecord[i].insn_off;
15899 bpfptr_add(&urecord, urec_size);
15900 }
15901
15902 prog->aux->func_info = krecord;
15903 prog->aux->func_info_cnt = nfuncs;
15904 return 0;
15905
15906err_free:
15907 kvfree(krecord);
15908 return ret;
15909}
15910
15911static int check_btf_func(struct bpf_verifier_env *env,
15912 const union bpf_attr *attr,
15913 bpfptr_t uattr)
15914{
15915 const struct btf_type *type, *func_proto, *ret_type;
aec42f36 15916 u32 i, nfuncs, urec_size;
aaa619eb
KKD
15917 struct bpf_func_info *krecord;
15918 struct bpf_func_info_aux *info_aux = NULL;
15919 struct bpf_prog *prog;
15920 const struct btf *btf;
15921 bpfptr_t urecord;
aaa619eb
KKD
15922 bool scalar_return;
15923 int ret = -ENOMEM;
15924
15925 nfuncs = attr->func_info_cnt;
15926 if (!nfuncs) {
15927 if (check_abnormal_return(env))
15928 return -EINVAL;
15929 return 0;
15930 }
15931 if (nfuncs != env->subprog_cnt) {
15932 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15933 return -EINVAL;
15934 }
15935
15936 urec_size = attr->func_info_rec_size;
15937
15938 prog = env->prog;
15939 btf = prog->aux->btf;
15940
15941 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
aaa619eb
KKD
15942
15943 krecord = prog->aux->func_info;
15944 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15945 if (!info_aux)
15946 return -ENOMEM;
15947
15948 for (i = 0; i < nfuncs; i++) {
15949 /* check insn_off */
15950 ret = -EINVAL;
15951
15952 if (env->subprog_info[i].start != krecord[i].insn_off) {
15953 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15954 goto err_free;
15955 }
15956
15957 /* Already checked type_id */
15958 type = btf_type_by_id(btf, krecord[i].type_id);
15959 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15960 /* Already checked func_proto */
15961 func_proto = btf_type_by_id(btf, type->type);
15962
09b28d76
AS
15963 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15964 scalar_return =
6089fb32 15965 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
09b28d76
AS
15966 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15967 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15968 goto err_free;
15969 }
15970 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15971 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15972 goto err_free;
15973 }
15974
af2ac3e1 15975 bpfptr_add(&urecord, urec_size);
838e9690
YS
15976 }
15977
8c1b6e69 15978 prog->aux->func_info_aux = info_aux;
838e9690
YS
15979 return 0;
15980
c454a46b 15981err_free:
8c1b6e69 15982 kfree(info_aux);
838e9690
YS
15983 return ret;
15984}
15985
ba64e7d8
YS
15986static void adjust_btf_func(struct bpf_verifier_env *env)
15987{
8c1b6e69 15988 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
15989 int i;
15990
8c1b6e69 15991 if (!aux->func_info)
ba64e7d8
YS
15992 return;
15993
335d1c5b
KKD
15994 /* func_info is not available for hidden subprogs */
15995 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
8c1b6e69 15996 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
15997}
15998
1b773d00 15999#define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
c454a46b
MKL
16000#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
16001
16002static int check_btf_line(struct bpf_verifier_env *env,
16003 const union bpf_attr *attr,
af2ac3e1 16004 bpfptr_t uattr)
c454a46b
MKL
16005{
16006 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16007 struct bpf_subprog_info *sub;
16008 struct bpf_line_info *linfo;
16009 struct bpf_prog *prog;
16010 const struct btf *btf;
af2ac3e1 16011 bpfptr_t ulinfo;
c454a46b
MKL
16012 int err;
16013
16014 nr_linfo = attr->line_info_cnt;
16015 if (!nr_linfo)
16016 return 0;
0e6491b5
BC
16017 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16018 return -EINVAL;
c454a46b
MKL
16019
16020 rec_size = attr->line_info_rec_size;
16021 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16022 rec_size > MAX_LINEINFO_REC_SIZE ||
16023 rec_size & (sizeof(u32) - 1))
16024 return -EINVAL;
16025
16026 /* Need to zero it in case the userspace may
16027 * pass in a smaller bpf_line_info object.
16028 */
16029 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16030 GFP_KERNEL | __GFP_NOWARN);
16031 if (!linfo)
16032 return -ENOMEM;
16033
16034 prog = env->prog;
16035 btf = prog->aux->btf;
16036
16037 s = 0;
16038 sub = env->subprog_info;
af2ac3e1 16039 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
c454a46b
MKL
16040 expected_size = sizeof(struct bpf_line_info);
16041 ncopy = min_t(u32, expected_size, rec_size);
16042 for (i = 0; i < nr_linfo; i++) {
16043 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16044 if (err) {
16045 if (err == -E2BIG) {
16046 verbose(env, "nonzero tailing record in line_info");
af2ac3e1
AS
16047 if (copy_to_bpfptr_offset(uattr,
16048 offsetof(union bpf_attr, line_info_rec_size),
16049 &expected_size, sizeof(expected_size)))
c454a46b
MKL
16050 err = -EFAULT;
16051 }
16052 goto err_free;
16053 }
16054
af2ac3e1 16055 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
c454a46b
MKL
16056 err = -EFAULT;
16057 goto err_free;
16058 }
16059
16060 /*
16061 * Check insn_off to ensure
16062 * 1) strictly increasing AND
16063 * 2) bounded by prog->len
16064 *
16065 * The linfo[0].insn_off == 0 check logically falls into
16066 * the later "missing bpf_line_info for func..." case
16067 * because the first linfo[0].insn_off must be the
16068 * first sub also and the first sub must have
16069 * subprog_info[0].start == 0.
16070 */
16071 if ((i && linfo[i].insn_off <= prev_offset) ||
16072 linfo[i].insn_off >= prog->len) {
16073 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16074 i, linfo[i].insn_off, prev_offset,
16075 prog->len);
16076 err = -EINVAL;
16077 goto err_free;
16078 }
16079
fdbaa0be
MKL
16080 if (!prog->insnsi[linfo[i].insn_off].code) {
16081 verbose(env,
16082 "Invalid insn code at line_info[%u].insn_off\n",
16083 i);
16084 err = -EINVAL;
16085 goto err_free;
16086 }
16087
23127b33
MKL
16088 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16089 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
16090 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16091 err = -EINVAL;
16092 goto err_free;
16093 }
16094
16095 if (s != env->subprog_cnt) {
16096 if (linfo[i].insn_off == sub[s].start) {
16097 sub[s].linfo_idx = i;
16098 s++;
16099 } else if (sub[s].start < linfo[i].insn_off) {
16100 verbose(env, "missing bpf_line_info for func#%u\n", s);
16101 err = -EINVAL;
16102 goto err_free;
16103 }
16104 }
16105
16106 prev_offset = linfo[i].insn_off;
af2ac3e1 16107 bpfptr_add(&ulinfo, rec_size);
c454a46b
MKL
16108 }
16109
16110 if (s != env->subprog_cnt) {
16111 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16112 env->subprog_cnt - s, s);
16113 err = -EINVAL;
16114 goto err_free;
16115 }
16116
16117 prog->aux->linfo = linfo;
16118 prog->aux->nr_linfo = nr_linfo;
16119
16120 return 0;
16121
16122err_free:
16123 kvfree(linfo);
16124 return err;
16125}
16126
fbd94c7a
AS
16127#define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
16128#define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
16129
16130static int check_core_relo(struct bpf_verifier_env *env,
16131 const union bpf_attr *attr,
16132 bpfptr_t uattr)
16133{
16134 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16135 struct bpf_core_relo core_relo = {};
16136 struct bpf_prog *prog = env->prog;
16137 const struct btf *btf = prog->aux->btf;
16138 struct bpf_core_ctx ctx = {
16139 .log = &env->log,
16140 .btf = btf,
16141 };
16142 bpfptr_t u_core_relo;
16143 int err;
16144
16145 nr_core_relo = attr->core_relo_cnt;
16146 if (!nr_core_relo)
16147 return 0;
16148 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16149 return -EINVAL;
16150
16151 rec_size = attr->core_relo_rec_size;
16152 if (rec_size < MIN_CORE_RELO_SIZE ||
16153 rec_size > MAX_CORE_RELO_SIZE ||
16154 rec_size % sizeof(u32))
16155 return -EINVAL;
16156
16157 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16158 expected_size = sizeof(struct bpf_core_relo);
16159 ncopy = min_t(u32, expected_size, rec_size);
16160
16161 /* Unlike func_info and line_info, copy and apply each CO-RE
16162 * relocation record one at a time.
16163 */
16164 for (i = 0; i < nr_core_relo; i++) {
16165 /* future proofing when sizeof(bpf_core_relo) changes */
16166 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16167 if (err) {
16168 if (err == -E2BIG) {
16169 verbose(env, "nonzero tailing record in core_relo");
16170 if (copy_to_bpfptr_offset(uattr,
16171 offsetof(union bpf_attr, core_relo_rec_size),
16172 &expected_size, sizeof(expected_size)))
16173 err = -EFAULT;
16174 }
16175 break;
16176 }
16177
16178 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16179 err = -EFAULT;
16180 break;
16181 }
16182
16183 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16184 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16185 i, core_relo.insn_off, prog->len);
16186 err = -EINVAL;
16187 break;
16188 }
16189
16190 err = bpf_core_apply(&ctx, &core_relo, i,
16191 &prog->insnsi[core_relo.insn_off / 8]);
16192 if (err)
16193 break;
16194 bpfptr_add(&u_core_relo, rec_size);
16195 }
16196 return err;
16197}
16198
aaa619eb
KKD
16199static int check_btf_info_early(struct bpf_verifier_env *env,
16200 const union bpf_attr *attr,
16201 bpfptr_t uattr)
c454a46b
MKL
16202{
16203 struct btf *btf;
16204 int err;
16205
09b28d76
AS
16206 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16207 if (check_abnormal_return(env))
16208 return -EINVAL;
c454a46b 16209 return 0;
09b28d76 16210 }
c454a46b
MKL
16211
16212 btf = btf_get_by_fd(attr->prog_btf_fd);
16213 if (IS_ERR(btf))
16214 return PTR_ERR(btf);
350a5c4d
AS
16215 if (btf_is_kernel(btf)) {
16216 btf_put(btf);
16217 return -EACCES;
16218 }
c454a46b
MKL
16219 env->prog->aux->btf = btf;
16220
aaa619eb
KKD
16221 err = check_btf_func_early(env, attr, uattr);
16222 if (err)
16223 return err;
16224 return 0;
16225}
16226
16227static int check_btf_info(struct bpf_verifier_env *env,
16228 const union bpf_attr *attr,
16229 bpfptr_t uattr)
16230{
16231 int err;
16232
16233 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16234 if (check_abnormal_return(env))
16235 return -EINVAL;
16236 return 0;
16237 }
16238
c454a46b
MKL
16239 err = check_btf_func(env, attr, uattr);
16240 if (err)
16241 return err;
16242
16243 err = check_btf_line(env, attr, uattr);
16244 if (err)
16245 return err;
16246
fbd94c7a
AS
16247 err = check_core_relo(env, attr, uattr);
16248 if (err)
16249 return err;
16250
c454a46b 16251 return 0;
ba64e7d8
YS
16252}
16253
f1174f77
EC
16254/* check %cur's range satisfies %old's */
16255static bool range_within(struct bpf_reg_state *old,
16256 struct bpf_reg_state *cur)
16257{
b03c9f9f
EC
16258 return old->umin_value <= cur->umin_value &&
16259 old->umax_value >= cur->umax_value &&
16260 old->smin_value <= cur->smin_value &&
fd675184
DB
16261 old->smax_value >= cur->smax_value &&
16262 old->u32_min_value <= cur->u32_min_value &&
16263 old->u32_max_value >= cur->u32_max_value &&
16264 old->s32_min_value <= cur->s32_min_value &&
16265 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
16266}
16267
f1174f77
EC
16268/* If in the old state two registers had the same id, then they need to have
16269 * the same id in the new state as well. But that id could be different from
16270 * the old state, so we need to track the mapping from old to new ids.
16271 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16272 * regs with old id 5 must also have new id 9 for the new state to be safe. But
16273 * regs with a different old id could still have new id 9, we don't care about
16274 * that.
16275 * So we look through our idmap to see if this old id has been seen before. If
16276 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 16277 */
1ffc85d9 16278static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
969bf05e 16279{
1ffc85d9 16280 struct bpf_id_pair *map = idmap->map;
f1174f77 16281 unsigned int i;
969bf05e 16282
4633a006
AN
16283 /* either both IDs should be set or both should be zero */
16284 if (!!old_id != !!cur_id)
16285 return false;
16286
16287 if (old_id == 0) /* cur_id == 0 as well */
16288 return true;
16289
c9e73e3d 16290 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
1ffc85d9 16291 if (!map[i].old) {
f1174f77 16292 /* Reached an empty slot; haven't seen this id before */
1ffc85d9
EZ
16293 map[i].old = old_id;
16294 map[i].cur = cur_id;
f1174f77
EC
16295 return true;
16296 }
1ffc85d9
EZ
16297 if (map[i].old == old_id)
16298 return map[i].cur == cur_id;
16299 if (map[i].cur == cur_id)
16300 return false;
f1174f77
EC
16301 }
16302 /* We ran out of idmap slots, which should be impossible */
16303 WARN_ON_ONCE(1);
16304 return false;
16305}
16306
1ffc85d9
EZ
16307/* Similar to check_ids(), but allocate a unique temporary ID
16308 * for 'old_id' or 'cur_id' of zero.
16309 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16310 */
16311static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16312{
16313 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16314 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16315
16316 return check_ids(old_id, cur_id, idmap);
16317}
16318
9242b5f5
AS
16319static void clean_func_state(struct bpf_verifier_env *env,
16320 struct bpf_func_state *st)
16321{
16322 enum bpf_reg_liveness live;
16323 int i, j;
16324
16325 for (i = 0; i < BPF_REG_FP; i++) {
16326 live = st->regs[i].live;
16327 /* liveness must not touch this register anymore */
16328 st->regs[i].live |= REG_LIVE_DONE;
16329 if (!(live & REG_LIVE_READ))
16330 /* since the register is unused, clear its state
16331 * to make further comparison simpler
16332 */
f54c7898 16333 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
16334 }
16335
16336 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16337 live = st->stack[i].spilled_ptr.live;
16338 /* liveness must not touch this stack slot anymore */
16339 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16340 if (!(live & REG_LIVE_READ)) {
f54c7898 16341 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
16342 for (j = 0; j < BPF_REG_SIZE; j++)
16343 st->stack[i].slot_type[j] = STACK_INVALID;
16344 }
16345 }
16346}
16347
16348static void clean_verifier_state(struct bpf_verifier_env *env,
16349 struct bpf_verifier_state *st)
16350{
16351 int i;
16352
16353 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16354 /* all regs in this state in all frames were already marked */
16355 return;
16356
16357 for (i = 0; i <= st->curframe; i++)
16358 clean_func_state(env, st->frame[i]);
16359}
16360
16361/* the parentage chains form a tree.
16362 * the verifier states are added to state lists at given insn and
16363 * pushed into state stack for future exploration.
16364 * when the verifier reaches bpf_exit insn some of the verifer states
16365 * stored in the state lists have their final liveness state already,
16366 * but a lot of states will get revised from liveness point of view when
16367 * the verifier explores other branches.
16368 * Example:
16369 * 1: r0 = 1
16370 * 2: if r1 == 100 goto pc+1
16371 * 3: r0 = 2
16372 * 4: exit
16373 * when the verifier reaches exit insn the register r0 in the state list of
16374 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16375 * of insn 2 and goes exploring further. At the insn 4 it will walk the
16376 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16377 *
16378 * Since the verifier pushes the branch states as it sees them while exploring
16379 * the program the condition of walking the branch instruction for the second
16380 * time means that all states below this branch were already explored and
8fb33b60 16381 * their final liveness marks are already propagated.
9242b5f5
AS
16382 * Hence when the verifier completes the search of state list in is_state_visited()
16383 * we can call this clean_live_states() function to mark all liveness states
16384 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16385 * will not be used.
16386 * This function also clears the registers and stack for states that !READ
16387 * to simplify state merging.
16388 *
16389 * Important note here that walking the same branch instruction in the callee
16390 * doesn't meant that the states are DONE. The verifier has to compare
16391 * the callsites
16392 */
16393static void clean_live_states(struct bpf_verifier_env *env, int insn,
16394 struct bpf_verifier_state *cur)
16395{
16396 struct bpf_verifier_state_list *sl;
9242b5f5 16397
5d839021 16398 sl = *explored_state(env, insn);
a8f500af 16399 while (sl) {
2589726d
AS
16400 if (sl->state.branches)
16401 goto next;
dc2a4ebc 16402 if (sl->state.insn_idx != insn ||
4c97259a 16403 !same_callsites(&sl->state, cur))
9242b5f5 16404 goto next;
9242b5f5
AS
16405 clean_verifier_state(env, &sl->state);
16406next:
16407 sl = sl->next;
16408 }
16409}
16410
4a95c85c 16411static bool regs_exact(const struct bpf_reg_state *rold,
4633a006 16412 const struct bpf_reg_state *rcur,
1ffc85d9 16413 struct bpf_idmap *idmap)
4a95c85c 16414{
d2dcc67d 16415 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4633a006
AN
16416 check_ids(rold->id, rcur->id, idmap) &&
16417 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
4a95c85c
AN
16418}
16419
f1174f77 16420/* Returns true if (rold safe implies rcur safe) */
e042aa53 16421static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
2793a8b0 16422 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
f1174f77 16423{
2793a8b0
EZ
16424 if (exact)
16425 return regs_exact(rold, rcur, idmap);
16426
dc503a8a
EC
16427 if (!(rold->live & REG_LIVE_READ))
16428 /* explored state didn't use this */
16429 return true;
f1174f77
EC
16430 if (rold->type == NOT_INIT)
16431 /* explored state can't have used this */
969bf05e 16432 return true;
f1174f77
EC
16433 if (rcur->type == NOT_INIT)
16434 return false;
7f4ce97c 16435
910f6999
AN
16436 /* Enforce that register types have to match exactly, including their
16437 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16438 * rule.
16439 *
16440 * One can make a point that using a pointer register as unbounded
16441 * SCALAR would be technically acceptable, but this could lead to
16442 * pointer leaks because scalars are allowed to leak while pointers
16443 * are not. We could make this safe in special cases if root is
16444 * calling us, but it's probably not worth the hassle.
16445 *
16446 * Also, register types that are *not* MAYBE_NULL could technically be
16447 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16448 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16449 * to the same map).
7f4ce97c
AN
16450 * However, if the old MAYBE_NULL register then got NULL checked,
16451 * doing so could have affected others with the same id, and we can't
16452 * check for that because we lost the id when we converted to
16453 * a non-MAYBE_NULL variant.
16454 * So, as a general rule we don't allow mixing MAYBE_NULL and
910f6999 16455 * non-MAYBE_NULL registers as well.
7f4ce97c 16456 */
910f6999 16457 if (rold->type != rcur->type)
7f4ce97c
AN
16458 return false;
16459
c25b2ae1 16460 switch (base_type(rold->type)) {
f1174f77 16461 case SCALAR_VALUE:
1ffc85d9
EZ
16462 if (env->explore_alu_limits) {
16463 /* explore_alu_limits disables tnum_in() and range_within()
16464 * logic and requires everything to be strict
16465 */
16466 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16467 check_scalar_ids(rold->id, rcur->id, idmap);
16468 }
910f6999
AN
16469 if (!rold->precise)
16470 return true;
1ffc85d9
EZ
16471 /* Why check_ids() for scalar registers?
16472 *
16473 * Consider the following BPF code:
16474 * 1: r6 = ... unbound scalar, ID=a ...
16475 * 2: r7 = ... unbound scalar, ID=b ...
16476 * 3: if (r6 > r7) goto +1
16477 * 4: r6 = r7
16478 * 5: if (r6 > X) goto ...
16479 * 6: ... memory operation using r7 ...
16480 *
16481 * First verification path is [1-6]:
16482 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16483 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16484 * r7 <= X, because r6 and r7 share same id.
16485 * Next verification path is [1-4, 6].
16486 *
16487 * Instruction (6) would be reached in two states:
16488 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16489 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16490 *
16491 * Use check_ids() to distinguish these states.
16492 * ---
16493 * Also verify that new value satisfies old value range knowledge.
16494 */
910f6999 16495 return range_within(rold, rcur) &&
1ffc85d9
EZ
16496 tnum_in(rold->var_off, rcur->var_off) &&
16497 check_scalar_ids(rold->id, rcur->id, idmap);
69c087ba 16498 case PTR_TO_MAP_KEY:
f1174f77 16499 case PTR_TO_MAP_VALUE:
567da5d2
AN
16500 case PTR_TO_MEM:
16501 case PTR_TO_BUF:
16502 case PTR_TO_TP_BUFFER:
1b688a19
EC
16503 /* If the new min/max/var_off satisfy the old ones and
16504 * everything else matches, we are OK.
1b688a19 16505 */
a73bf9f2 16506 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
1b688a19 16507 range_within(rold, rcur) &&
4ea2bb15 16508 tnum_in(rold->var_off, rcur->var_off) &&
567da5d2
AN
16509 check_ids(rold->id, rcur->id, idmap) &&
16510 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
de8f3a83 16511 case PTR_TO_PACKET_META:
f1174f77 16512 case PTR_TO_PACKET:
f1174f77
EC
16513 /* We must have at least as much range as the old ptr
16514 * did, so that any accesses which were safe before are
16515 * still safe. This is true even if old range < old off,
16516 * since someone could have accessed through (ptr - k), or
16517 * even done ptr -= k in a register, to get a safe access.
16518 */
16519 if (rold->range > rcur->range)
16520 return false;
16521 /* If the offsets don't match, we can't trust our alignment;
16522 * nor can we be sure that we won't fall out of range.
16523 */
16524 if (rold->off != rcur->off)
16525 return false;
16526 /* id relations must be preserved */
4633a006 16527 if (!check_ids(rold->id, rcur->id, idmap))
f1174f77
EC
16528 return false;
16529 /* new val must satisfy old val knowledge */
16530 return range_within(rold, rcur) &&
16531 tnum_in(rold->var_off, rcur->var_off);
7c884339
EZ
16532 case PTR_TO_STACK:
16533 /* two stack pointers are equal only if they're pointing to
16534 * the same stack frame, since fp-8 in foo != fp-8 in bar
f1174f77 16535 */
4633a006 16536 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
f1174f77 16537 default:
4633a006 16538 return regs_exact(rold, rcur, idmap);
f1174f77 16539 }
969bf05e
AS
16540}
16541
e042aa53 16542static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
2793a8b0 16543 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
638f5b90
AS
16544{
16545 int i, spi;
16546
638f5b90
AS
16547 /* walk slots of the explored stack and ignore any additional
16548 * slots in the current stack, since explored(safe) state
16549 * didn't use them
16550 */
16551 for (i = 0; i < old->allocated_stack; i++) {
06accc87
AN
16552 struct bpf_reg_state *old_reg, *cur_reg;
16553
638f5b90
AS
16554 spi = i / BPF_REG_SIZE;
16555
2793a8b0
EZ
16556 if (exact &&
16557 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16558 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16559 return false;
16560
16561 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
b233920c 16562 i += BPF_REG_SIZE - 1;
cc2b14d5 16563 /* explored state didn't use this */
fd05e57b 16564 continue;
b233920c 16565 }
cc2b14d5 16566
638f5b90
AS
16567 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16568 continue;
19e2dbb7 16569
6715df8d
EZ
16570 if (env->allow_uninit_stack &&
16571 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16572 continue;
16573
19e2dbb7
AS
16574 /* explored stack has more populated slots than current stack
16575 * and these slots were used
16576 */
16577 if (i >= cur->allocated_stack)
16578 return false;
16579
cc2b14d5
AS
16580 /* if old state was safe with misc data in the stack
16581 * it will be safe with zero-initialized stack.
16582 * The opposite is not true
16583 */
16584 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16585 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16586 continue;
638f5b90
AS
16587 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16588 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16589 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 16590 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
16591 * this verifier states are not equivalent,
16592 * return false to continue verification of this path
16593 */
16594 return false;
27113c59 16595 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
638f5b90 16596 continue;
d6fefa11
KKD
16597 /* Both old and cur are having same slot_type */
16598 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16599 case STACK_SPILL:
638f5b90
AS
16600 /* when explored and current stack slot are both storing
16601 * spilled registers, check that stored pointers types
16602 * are the same as well.
16603 * Ex: explored safe path could have stored
16604 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16605 * but current path has stored:
16606 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16607 * such verifier states are not equivalent.
16608 * return false to continue verification of this path
16609 */
d6fefa11 16610 if (!regsafe(env, &old->stack[spi].spilled_ptr,
2793a8b0 16611 &cur->stack[spi].spilled_ptr, idmap, exact))
d6fefa11
KKD
16612 return false;
16613 break;
16614 case STACK_DYNPTR:
d6fefa11
KKD
16615 old_reg = &old->stack[spi].spilled_ptr;
16616 cur_reg = &cur->stack[spi].spilled_ptr;
16617 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16618 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16619 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16620 return false;
16621 break;
06accc87
AN
16622 case STACK_ITER:
16623 old_reg = &old->stack[spi].spilled_ptr;
16624 cur_reg = &cur->stack[spi].spilled_ptr;
16625 /* iter.depth is not compared between states as it
16626 * doesn't matter for correctness and would otherwise
16627 * prevent convergence; we maintain it only to prevent
16628 * infinite loop check triggering, see
16629 * iter_active_depths_differ()
16630 */
16631 if (old_reg->iter.btf != cur_reg->iter.btf ||
16632 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16633 old_reg->iter.state != cur_reg->iter.state ||
16634 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16635 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16636 return false;
16637 break;
d6fefa11
KKD
16638 case STACK_MISC:
16639 case STACK_ZERO:
16640 case STACK_INVALID:
16641 continue;
16642 /* Ensure that new unhandled slot types return false by default */
16643 default:
638f5b90 16644 return false;
d6fefa11 16645 }
638f5b90
AS
16646 }
16647 return true;
16648}
16649
e8f55fcf 16650static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
1ffc85d9 16651 struct bpf_idmap *idmap)
fd978bf7 16652{
e8f55fcf
AN
16653 int i;
16654
fd978bf7
JS
16655 if (old->acquired_refs != cur->acquired_refs)
16656 return false;
e8f55fcf
AN
16657
16658 for (i = 0; i < old->acquired_refs; i++) {
16659 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16660 return false;
16661 }
16662
16663 return true;
fd978bf7
JS
16664}
16665
f1bca824
AS
16666/* compare two verifier states
16667 *
16668 * all states stored in state_list are known to be valid, since
16669 * verifier reached 'bpf_exit' instruction through them
16670 *
16671 * this function is called when verifier exploring different branches of
16672 * execution popped from the state stack. If it sees an old state that has
16673 * more strict register state and more strict stack state then this execution
16674 * branch doesn't need to be explored further, since verifier already
16675 * concluded that more strict state leads to valid finish.
16676 *
16677 * Therefore two states are equivalent if register state is more conservative
16678 * and explored stack state is more conservative than the current one.
16679 * Example:
16680 * explored current
16681 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16682 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16683 *
16684 * In other words if current stack state (one being explored) has more
16685 * valid slots than old one that already passed validation, it means
16686 * the verifier can stop exploring and conclude that current state is valid too
16687 *
16688 * Similarly with registers. If explored state has register type as invalid
16689 * whereas register type in current state is meaningful, it means that
16690 * the current state will reach 'bpf_exit' instruction safely
16691 */
c9e73e3d 16692static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
2793a8b0 16693 struct bpf_func_state *cur, bool exact)
f1bca824
AS
16694{
16695 int i;
16696
c9e73e3d 16697 for (i = 0; i < MAX_BPF_REG; i++)
e042aa53 16698 if (!regsafe(env, &old->regs[i], &cur->regs[i],
2793a8b0 16699 &env->idmap_scratch, exact))
c9e73e3d 16700 return false;
f1bca824 16701
2793a8b0 16702 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
c9e73e3d 16703 return false;
fd978bf7 16704
1ffc85d9 16705 if (!refsafe(old, cur, &env->idmap_scratch))
c9e73e3d
LB
16706 return false;
16707
16708 return true;
f1bca824
AS
16709}
16710
2793a8b0
EZ
16711static void reset_idmap_scratch(struct bpf_verifier_env *env)
16712{
16713 env->idmap_scratch.tmp_id_gen = env->id_gen;
16714 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16715}
16716
f4d7e40a
AS
16717static bool states_equal(struct bpf_verifier_env *env,
16718 struct bpf_verifier_state *old,
2793a8b0
EZ
16719 struct bpf_verifier_state *cur,
16720 bool exact)
f4d7e40a
AS
16721{
16722 int i;
16723
16724 if (old->curframe != cur->curframe)
16725 return false;
16726
2793a8b0 16727 reset_idmap_scratch(env);
5dd9cdbc 16728
979d63d5
DB
16729 /* Verification state from speculative execution simulation
16730 * must never prune a non-speculative execution one.
16731 */
16732 if (old->speculative && !cur->speculative)
16733 return false;
16734
4ea2bb15
EZ
16735 if (old->active_lock.ptr != cur->active_lock.ptr)
16736 return false;
16737
16738 /* Old and cur active_lock's have to be either both present
16739 * or both absent.
16740 */
16741 if (!!old->active_lock.id != !!cur->active_lock.id)
16742 return false;
16743
16744 if (old->active_lock.id &&
1ffc85d9 16745 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
d83525ca
AS
16746 return false;
16747
9bb00b28 16748 if (old->active_rcu_lock != cur->active_rcu_lock)
d83525ca
AS
16749 return false;
16750
f4d7e40a
AS
16751 /* for states to be equal callsites have to be the same
16752 * and all frame states need to be equivalent
16753 */
16754 for (i = 0; i <= old->curframe; i++) {
16755 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16756 return false;
2793a8b0 16757 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
f4d7e40a
AS
16758 return false;
16759 }
16760 return true;
16761}
16762
5327ed3d
JW
16763/* Return 0 if no propagation happened. Return negative error code if error
16764 * happened. Otherwise, return the propagated bit.
16765 */
55e7f3b5
JW
16766static int propagate_liveness_reg(struct bpf_verifier_env *env,
16767 struct bpf_reg_state *reg,
16768 struct bpf_reg_state *parent_reg)
16769{
5327ed3d
JW
16770 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16771 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
16772 int err;
16773
5327ed3d
JW
16774 /* When comes here, read flags of PARENT_REG or REG could be any of
16775 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16776 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16777 */
16778 if (parent_flag == REG_LIVE_READ64 ||
16779 /* Or if there is no read flag from REG. */
16780 !flag ||
16781 /* Or if the read flag from REG is the same as PARENT_REG. */
16782 parent_flag == flag)
55e7f3b5
JW
16783 return 0;
16784
5327ed3d 16785 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
16786 if (err)
16787 return err;
16788
5327ed3d 16789 return flag;
55e7f3b5
JW
16790}
16791
8e9cd9ce 16792/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
16793 * straight-line code between a state and its parent. When we arrive at an
16794 * equivalent state (jump target or such) we didn't arrive by the straight-line
16795 * code, so read marks in the state must propagate to the parent regardless
16796 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 16797 * in mark_reg_read() is for.
8e9cd9ce 16798 */
f4d7e40a
AS
16799static int propagate_liveness(struct bpf_verifier_env *env,
16800 const struct bpf_verifier_state *vstate,
16801 struct bpf_verifier_state *vparent)
dc503a8a 16802{
3f8cafa4 16803 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 16804 struct bpf_func_state *state, *parent;
3f8cafa4 16805 int i, frame, err = 0;
dc503a8a 16806
f4d7e40a
AS
16807 if (vparent->curframe != vstate->curframe) {
16808 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16809 vparent->curframe, vstate->curframe);
16810 return -EFAULT;
16811 }
dc503a8a
EC
16812 /* Propagate read liveness of registers... */
16813 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 16814 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
16815 parent = vparent->frame[frame];
16816 state = vstate->frame[frame];
16817 parent_reg = parent->regs;
16818 state_reg = state->regs;
83d16312
JK
16819 /* We don't need to worry about FP liveness, it's read-only */
16820 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
16821 err = propagate_liveness_reg(env, &state_reg[i],
16822 &parent_reg[i]);
5327ed3d 16823 if (err < 0)
3f8cafa4 16824 return err;
5327ed3d
JW
16825 if (err == REG_LIVE_READ64)
16826 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 16827 }
f4d7e40a 16828
1b04aee7 16829 /* Propagate stack slots. */
f4d7e40a
AS
16830 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16831 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
16832 parent_reg = &parent->stack[i].spilled_ptr;
16833 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
16834 err = propagate_liveness_reg(env, state_reg,
16835 parent_reg);
5327ed3d 16836 if (err < 0)
3f8cafa4 16837 return err;
dc503a8a
EC
16838 }
16839 }
5327ed3d 16840 return 0;
dc503a8a
EC
16841}
16842
a3ce685d
AS
16843/* find precise scalars in the previous equivalent state and
16844 * propagate them into the current state
16845 */
16846static int propagate_precision(struct bpf_verifier_env *env,
16847 const struct bpf_verifier_state *old)
16848{
16849 struct bpf_reg_state *state_reg;
16850 struct bpf_func_state *state;
529409ea 16851 int i, err = 0, fr;
f655badf 16852 bool first;
a3ce685d 16853
529409ea
AN
16854 for (fr = old->curframe; fr >= 0; fr--) {
16855 state = old->frame[fr];
16856 state_reg = state->regs;
f655badf 16857 first = true;
529409ea
AN
16858 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16859 if (state_reg->type != SCALAR_VALUE ||
52c2b005
AN
16860 !state_reg->precise ||
16861 !(state_reg->live & REG_LIVE_READ))
529409ea 16862 continue;
f655badf
AN
16863 if (env->log.level & BPF_LOG_LEVEL2) {
16864 if (first)
16865 verbose(env, "frame %d: propagating r%d", fr, i);
16866 else
16867 verbose(env, ",r%d", i);
16868 }
16869 bt_set_frame_reg(&env->bt, fr, i);
16870 first = false;
529409ea 16871 }
a3ce685d 16872
529409ea
AN
16873 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16874 if (!is_spilled_reg(&state->stack[i]))
16875 continue;
16876 state_reg = &state->stack[i].spilled_ptr;
16877 if (state_reg->type != SCALAR_VALUE ||
52c2b005
AN
16878 !state_reg->precise ||
16879 !(state_reg->live & REG_LIVE_READ))
529409ea 16880 continue;
f655badf
AN
16881 if (env->log.level & BPF_LOG_LEVEL2) {
16882 if (first)
16883 verbose(env, "frame %d: propagating fp%d",
16884 fr, (-i - 1) * BPF_REG_SIZE);
16885 else
16886 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16887 }
16888 bt_set_frame_slot(&env->bt, fr, i);
16889 first = false;
529409ea 16890 }
f655badf
AN
16891 if (!first)
16892 verbose(env, "\n");
a3ce685d 16893 }
f655badf
AN
16894
16895 err = mark_chain_precision_batch(env);
16896 if (err < 0)
16897 return err;
16898
a3ce685d
AS
16899 return 0;
16900}
16901
2589726d
AS
16902static bool states_maybe_looping(struct bpf_verifier_state *old,
16903 struct bpf_verifier_state *cur)
16904{
16905 struct bpf_func_state *fold, *fcur;
16906 int i, fr = cur->curframe;
16907
16908 if (old->curframe != fr)
16909 return false;
16910
16911 fold = old->frame[fr];
16912 fcur = cur->frame[fr];
16913 for (i = 0; i < MAX_BPF_REG; i++)
16914 if (memcmp(&fold->regs[i], &fcur->regs[i],
16915 offsetof(struct bpf_reg_state, parent)))
16916 return false;
16917 return true;
16918}
16919
06accc87
AN
16920static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16921{
16922 return env->insn_aux_data[insn_idx].is_iter_next;
16923}
16924
16925/* is_state_visited() handles iter_next() (see process_iter_next_call() for
16926 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16927 * states to match, which otherwise would look like an infinite loop. So while
16928 * iter_next() calls are taken care of, we still need to be careful and
16929 * prevent erroneous and too eager declaration of "ininite loop", when
16930 * iterators are involved.
16931 *
16932 * Here's a situation in pseudo-BPF assembly form:
16933 *
16934 * 0: again: ; set up iter_next() call args
16935 * 1: r1 = &it ; <CHECKPOINT HERE>
16936 * 2: call bpf_iter_num_next ; this is iter_next() call
16937 * 3: if r0 == 0 goto done
16938 * 4: ... something useful here ...
16939 * 5: goto again ; another iteration
16940 * 6: done:
16941 * 7: r1 = &it
16942 * 8: call bpf_iter_num_destroy ; clean up iter state
16943 * 9: exit
16944 *
16945 * This is a typical loop. Let's assume that we have a prune point at 1:,
16946 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16947 * again`, assuming other heuristics don't get in a way).
16948 *
16949 * When we first time come to 1:, let's say we have some state X. We proceed
16950 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16951 * Now we come back to validate that forked ACTIVE state. We proceed through
16952 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16953 * are converging. But the problem is that we don't know that yet, as this
16954 * convergence has to happen at iter_next() call site only. So if nothing is
16955 * done, at 1: verifier will use bounded loop logic and declare infinite
16956 * looping (and would be *technically* correct, if not for iterator's
16957 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16958 * don't want that. So what we do in process_iter_next_call() when we go on
16959 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16960 * a different iteration. So when we suspect an infinite loop, we additionally
16961 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16962 * pretend we are not looping and wait for next iter_next() call.
16963 *
16964 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16965 * loop, because that would actually mean infinite loop, as DRAINED state is
16966 * "sticky", and so we'll keep returning into the same instruction with the
16967 * same state (at least in one of possible code paths).
16968 *
16969 * This approach allows to keep infinite loop heuristic even in the face of
16970 * active iterator. E.g., C snippet below is and will be detected as
16971 * inifintely looping:
16972 *
16973 * struct bpf_iter_num it;
16974 * int *p, x;
16975 *
16976 * bpf_iter_num_new(&it, 0, 10);
16977 * while ((p = bpf_iter_num_next(&t))) {
16978 * x = p;
16979 * while (x--) {} // <<-- infinite loop here
16980 * }
16981 *
16982 */
16983static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16984{
16985 struct bpf_reg_state *slot, *cur_slot;
16986 struct bpf_func_state *state;
16987 int i, fr;
16988
16989 for (fr = old->curframe; fr >= 0; fr--) {
16990 state = old->frame[fr];
16991 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16992 if (state->stack[i].slot_type[0] != STACK_ITER)
16993 continue;
16994
16995 slot = &state->stack[i].spilled_ptr;
16996 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16997 continue;
16998
16999 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17000 if (cur_slot->iter.depth != slot->iter.depth)
17001 return true;
17002 }
17003 }
17004 return false;
17005}
2589726d 17006
58e2af8b 17007static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 17008{
58e2af8b 17009 struct bpf_verifier_state_list *new_sl;
9f4686c4 17010 struct bpf_verifier_state_list *sl, **pprev;
2a099282 17011 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
2793a8b0 17012 int i, j, n, err, states_cnt = 0;
4b5ce570
AN
17013 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17014 bool add_new_state = force_new_state;
2a099282 17015 bool force_exact;
f1bca824 17016
2589726d
AS
17017 /* bpf progs typically have pruning point every 4 instructions
17018 * http://vger.kernel.org/bpfconf2019.html#session-1
17019 * Do not add new state for future pruning if the verifier hasn't seen
17020 * at least 2 jumps and at least 8 instructions.
17021 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17022 * In tests that amounts to up to 50% reduction into total verifier
17023 * memory consumption and 20% verifier time speedup.
17024 */
17025 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17026 env->insn_processed - env->prev_insn_processed >= 8)
17027 add_new_state = true;
17028
a8f500af
AS
17029 pprev = explored_state(env, insn_idx);
17030 sl = *pprev;
17031
9242b5f5
AS
17032 clean_live_states(env, insn_idx, cur);
17033
a8f500af 17034 while (sl) {
dc2a4ebc
AS
17035 states_cnt++;
17036 if (sl->state.insn_idx != insn_idx)
17037 goto next;
bfc6bb74 17038
2589726d 17039 if (sl->state.branches) {
bfc6bb74
AS
17040 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17041
17042 if (frame->in_async_callback_fn &&
17043 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17044 /* Different async_entry_cnt means that the verifier is
17045 * processing another entry into async callback.
17046 * Seeing the same state is not an indication of infinite
17047 * loop or infinite recursion.
17048 * But finding the same state doesn't mean that it's safe
17049 * to stop processing the current state. The previous state
17050 * hasn't yet reached bpf_exit, since state.branches > 0.
17051 * Checking in_async_callback_fn alone is not enough either.
17052 * Since the verifier still needs to catch infinite loops
17053 * inside async callbacks.
17054 */
06accc87
AN
17055 goto skip_inf_loop_check;
17056 }
17057 /* BPF open-coded iterators loop detection is special.
17058 * states_maybe_looping() logic is too simplistic in detecting
17059 * states that *might* be equivalent, because it doesn't know
17060 * about ID remapping, so don't even perform it.
17061 * See process_iter_next_call() and iter_active_depths_differ()
17062 * for overview of the logic. When current and one of parent
17063 * states are detected as equivalent, it's a good thing: we prove
17064 * convergence and can stop simulating further iterations.
17065 * It's safe to assume that iterator loop will finish, taking into
17066 * account iter_next() contract of eventually returning
17067 * sticky NULL result.
2793a8b0
EZ
17068 *
17069 * Note, that states have to be compared exactly in this case because
17070 * read and precision marks might not be finalized inside the loop.
17071 * E.g. as in the program below:
17072 *
17073 * 1. r7 = -16
17074 * 2. r6 = bpf_get_prandom_u32()
17075 * 3. while (bpf_iter_num_next(&fp[-8])) {
17076 * 4. if (r6 != 42) {
17077 * 5. r7 = -32
17078 * 6. r6 = bpf_get_prandom_u32()
17079 * 7. continue
17080 * 8. }
17081 * 9. r0 = r10
17082 * 10. r0 += r7
17083 * 11. r8 = *(u64 *)(r0 + 0)
17084 * 12. r6 = bpf_get_prandom_u32()
17085 * 13. }
17086 *
17087 * Here verifier would first visit path 1-3, create a checkpoint at 3
17088 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17089 * not have read or precision mark for r7 yet, thus inexact states
17090 * comparison would discard current state with r7=-32
17091 * => unsafe memory access at 11 would not be caught.
06accc87
AN
17092 */
17093 if (is_iter_next_insn(env, insn_idx)) {
2793a8b0 17094 if (states_equal(env, &sl->state, cur, true)) {
06accc87
AN
17095 struct bpf_func_state *cur_frame;
17096 struct bpf_reg_state *iter_state, *iter_reg;
17097 int spi;
17098
17099 cur_frame = cur->frame[cur->curframe];
17100 /* btf_check_iter_kfuncs() enforces that
17101 * iter state pointer is always the first arg
17102 */
17103 iter_reg = &cur_frame->regs[BPF_REG_1];
17104 /* current state is valid due to states_equal(),
17105 * so we can assume valid iter and reg state,
17106 * no need for extra (re-)validations
17107 */
17108 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17109 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
2a099282
EZ
17110 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17111 update_loop_entry(cur, &sl->state);
06accc87 17112 goto hit;
2a099282 17113 }
06accc87
AN
17114 }
17115 goto skip_inf_loop_check;
17116 }
ab5cfac1
EZ
17117 if (calls_callback(env, insn_idx)) {
17118 if (states_equal(env, &sl->state, cur, true))
17119 goto hit;
17120 goto skip_inf_loop_check;
17121 }
06accc87
AN
17122 /* attempt to detect infinite loop to avoid unnecessary doomed work */
17123 if (states_maybe_looping(&sl->state, cur) &&
2793a8b0 17124 states_equal(env, &sl->state, cur, false) &&
ab5cfac1
EZ
17125 !iter_active_depths_differ(&sl->state, cur) &&
17126 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
2589726d
AS
17127 verbose_linfo(env, insn_idx, "; ");
17128 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
b4d82395
EZ
17129 verbose(env, "cur state:");
17130 print_verifier_state(env, cur->frame[cur->curframe], true);
17131 verbose(env, "old state:");
17132 print_verifier_state(env, sl->state.frame[cur->curframe], true);
2589726d
AS
17133 return -EINVAL;
17134 }
17135 /* if the verifier is processing a loop, avoid adding new state
17136 * too often, since different loop iterations have distinct
17137 * states and may not help future pruning.
17138 * This threshold shouldn't be too low to make sure that
17139 * a loop with large bound will be rejected quickly.
17140 * The most abusive loop will be:
17141 * r1 += 1
17142 * if r1 < 1000000 goto pc-2
17143 * 1M insn_procssed limit / 100 == 10k peak states.
17144 * This threshold shouldn't be too high either, since states
17145 * at the end of the loop are likely to be useful in pruning.
17146 */
06accc87 17147skip_inf_loop_check:
4b5ce570 17148 if (!force_new_state &&
98ddcf38 17149 env->jmps_processed - env->prev_jmps_processed < 20 &&
2589726d
AS
17150 env->insn_processed - env->prev_insn_processed < 100)
17151 add_new_state = false;
17152 goto miss;
17153 }
2a099282
EZ
17154 /* If sl->state is a part of a loop and this loop's entry is a part of
17155 * current verification path then states have to be compared exactly.
17156 * 'force_exact' is needed to catch the following case:
17157 *
17158 * initial Here state 'succ' was processed first,
17159 * | it was eventually tracked to produce a
17160 * V state identical to 'hdr'.
17161 * .---------> hdr All branches from 'succ' had been explored
17162 * | | and thus 'succ' has its .branches == 0.
17163 * | V
17164 * | .------... Suppose states 'cur' and 'succ' correspond
17165 * | | | to the same instruction + callsites.
17166 * | V V In such case it is necessary to check
17167 * | ... ... if 'succ' and 'cur' are states_equal().
17168 * | | | If 'succ' and 'cur' are a part of the
17169 * | V V same loop exact flag has to be set.
17170 * | succ <- cur To check if that is the case, verify
17171 * | | if loop entry of 'succ' is in current
17172 * | V DFS path.
17173 * | ...
17174 * | |
17175 * '----'
17176 *
17177 * Additional details are in the comment before get_loop_entry().
17178 */
17179 loop_entry = get_loop_entry(&sl->state);
17180 force_exact = loop_entry && loop_entry->branches > 0;
17181 if (states_equal(env, &sl->state, cur, force_exact)) {
17182 if (force_exact)
17183 update_loop_entry(cur, loop_entry);
06accc87 17184hit:
9f4686c4 17185 sl->hit_cnt++;
f1bca824 17186 /* reached equivalent register/stack state,
dc503a8a
EC
17187 * prune the search.
17188 * Registers read by the continuation are read by us.
8e9cd9ce
EC
17189 * If we have any write marks in env->cur_state, they
17190 * will prevent corresponding reads in the continuation
17191 * from reaching our parent (an explored_state). Our
17192 * own state will get the read marks recorded, but
17193 * they'll be immediately forgotten as we're pruning
17194 * this state and will pop a new one.
f1bca824 17195 */
f4d7e40a 17196 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
17197
17198 /* if previous state reached the exit with precision and
17199 * current state is equivalent to it (except precsion marks)
17200 * the precision needs to be propagated back in
17201 * the current state.
17202 */
17203 err = err ? : push_jmp_history(env, cur);
17204 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
17205 if (err)
17206 return err;
f1bca824 17207 return 1;
dc503a8a 17208 }
2589726d
AS
17209miss:
17210 /* when new state is not going to be added do not increase miss count.
17211 * Otherwise several loop iterations will remove the state
17212 * recorded earlier. The goal of these heuristics is to have
17213 * states from some iterations of the loop (some in the beginning
17214 * and some at the end) to help pruning.
17215 */
17216 if (add_new_state)
17217 sl->miss_cnt++;
9f4686c4
AS
17218 /* heuristic to determine whether this state is beneficial
17219 * to keep checking from state equivalence point of view.
17220 * Higher numbers increase max_states_per_insn and verification time,
17221 * but do not meaningfully decrease insn_processed.
2793a8b0
EZ
17222 * 'n' controls how many times state could miss before eviction.
17223 * Use bigger 'n' for checkpoints because evicting checkpoint states
17224 * too early would hinder iterator convergence.
9f4686c4 17225 */
2793a8b0
EZ
17226 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17227 if (sl->miss_cnt > sl->hit_cnt * n + n) {
9f4686c4
AS
17228 /* the state is unlikely to be useful. Remove it to
17229 * speed up verification
17230 */
17231 *pprev = sl->next;
2a099282
EZ
17232 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17233 !sl->state.used_as_loop_entry) {
2589726d
AS
17234 u32 br = sl->state.branches;
17235
17236 WARN_ONCE(br,
17237 "BUG live_done but branches_to_explore %d\n",
17238 br);
9f4686c4
AS
17239 free_verifier_state(&sl->state, false);
17240 kfree(sl);
17241 env->peak_states--;
17242 } else {
17243 /* cannot free this state, since parentage chain may
17244 * walk it later. Add it for free_list instead to
17245 * be freed at the end of verification
17246 */
17247 sl->next = env->free_list;
17248 env->free_list = sl;
17249 }
17250 sl = *pprev;
17251 continue;
17252 }
dc2a4ebc 17253next:
9f4686c4
AS
17254 pprev = &sl->next;
17255 sl = *pprev;
f1bca824
AS
17256 }
17257
06ee7115
AS
17258 if (env->max_states_per_insn < states_cnt)
17259 env->max_states_per_insn = states_cnt;
17260
2c78ee89 17261 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
a095f421 17262 return 0;
ceefbc96 17263
2589726d 17264 if (!add_new_state)
a095f421 17265 return 0;
ceefbc96 17266
2589726d
AS
17267 /* There were no equivalent states, remember the current one.
17268 * Technically the current state is not proven to be safe yet,
f4d7e40a 17269 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 17270 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 17271 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
17272 * again on the way to bpf_exit.
17273 * When looping the sl->state.branches will be > 0 and this state
17274 * will not be considered for equivalence until branches == 0.
f1bca824 17275 */
638f5b90 17276 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
17277 if (!new_sl)
17278 return -ENOMEM;
06ee7115
AS
17279 env->total_states++;
17280 env->peak_states++;
2589726d
AS
17281 env->prev_jmps_processed = env->jmps_processed;
17282 env->prev_insn_processed = env->insn_processed;
f1bca824 17283
7a830b53
AN
17284 /* forget precise markings we inherited, see __mark_chain_precision */
17285 if (env->bpf_capable)
17286 mark_all_scalars_imprecise(env, cur);
17287
f1bca824 17288 /* add new state to the head of linked list */
679c782d
EC
17289 new = &new_sl->state;
17290 err = copy_verifier_state(new, cur);
1969db47 17291 if (err) {
679c782d 17292 free_verifier_state(new, false);
1969db47
AS
17293 kfree(new_sl);
17294 return err;
17295 }
dc2a4ebc 17296 new->insn_idx = insn_idx;
2589726d
AS
17297 WARN_ONCE(new->branches != 1,
17298 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 17299
2589726d 17300 cur->parent = new;
b5dc0163 17301 cur->first_insn_idx = insn_idx;
2793a8b0 17302 cur->dfs_depth = new->dfs_depth + 1;
b5dc0163 17303 clear_jmp_history(cur);
5d839021
AS
17304 new_sl->next = *explored_state(env, insn_idx);
17305 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
17306 /* connect new state to parentage chain. Current frame needs all
17307 * registers connected. Only r6 - r9 of the callers are alive (pushed
17308 * to the stack implicitly by JITs) so in callers' frames connect just
17309 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17310 * the state of the call instruction (with WRITTEN set), and r0 comes
17311 * from callee with its full parentage chain, anyway.
17312 */
8e9cd9ce
EC
17313 /* clear write marks in current state: the writes we did are not writes
17314 * our child did, so they don't screen off its reads from us.
17315 * (There are no read marks in current state, because reads always mark
17316 * their parent and current state never has children yet. Only
17317 * explored_states can get read marks.)
17318 */
eea1c227
AS
17319 for (j = 0; j <= cur->curframe; j++) {
17320 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17321 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17322 for (i = 0; i < BPF_REG_FP; i++)
17323 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17324 }
f4d7e40a
AS
17325
17326 /* all stack frames are accessible from callee, clear them all */
17327 for (j = 0; j <= cur->curframe; j++) {
17328 struct bpf_func_state *frame = cur->frame[j];
679c782d 17329 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 17330
679c782d 17331 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 17332 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
17333 frame->stack[i].spilled_ptr.parent =
17334 &newframe->stack[i].spilled_ptr;
17335 }
f4d7e40a 17336 }
f1bca824
AS
17337 return 0;
17338}
17339
c64b7983
JS
17340/* Return true if it's OK to have the same insn return a different type. */
17341static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17342{
c25b2ae1 17343 switch (base_type(type)) {
c64b7983
JS
17344 case PTR_TO_CTX:
17345 case PTR_TO_SOCKET:
46f8bc92 17346 case PTR_TO_SOCK_COMMON:
655a51e5 17347 case PTR_TO_TCP_SOCK:
fada7fdc 17348 case PTR_TO_XDP_SOCK:
2a02759e 17349 case PTR_TO_BTF_ID:
c64b7983
JS
17350 return false;
17351 default:
17352 return true;
17353 }
17354}
17355
17356/* If an instruction was previously used with particular pointer types, then we
17357 * need to be careful to avoid cases such as the below, where it may be ok
17358 * for one branch accessing the pointer, but not ok for the other branch:
17359 *
17360 * R1 = sock_ptr
17361 * goto X;
17362 * ...
17363 * R1 = some_other_valid_ptr;
17364 * goto X;
17365 * ...
17366 * R2 = *(u32 *)(R1 + 0);
17367 */
17368static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17369{
17370 return src != prev && (!reg_type_mismatch_ok(src) ||
17371 !reg_type_mismatch_ok(prev));
17372}
17373
0d80a619
EZ
17374static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17375 bool allow_trust_missmatch)
17376{
17377 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17378
17379 if (*prev_type == NOT_INIT) {
17380 /* Saw a valid insn
17381 * dst_reg = *(u32 *)(src_reg + off)
17382 * save type to validate intersecting paths
17383 */
17384 *prev_type = type;
17385 } else if (reg_type_mismatch(type, *prev_type)) {
17386 /* Abuser program is trying to use the same insn
17387 * dst_reg = *(u32*) (src_reg + off)
17388 * with different pointer types:
17389 * src_reg == ctx in one branch and
17390 * src_reg == stack|map in some other branch.
17391 * Reject it.
17392 */
17393 if (allow_trust_missmatch &&
17394 base_type(type) == PTR_TO_BTF_ID &&
17395 base_type(*prev_type) == PTR_TO_BTF_ID) {
17396 /*
17397 * Have to support a use case when one path through
17398 * the program yields TRUSTED pointer while another
17399 * is UNTRUSTED. Fallback to UNTRUSTED to generate
1f9a1ea8 17400 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
0d80a619
EZ
17401 */
17402 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17403 } else {
17404 verbose(env, "same insn cannot be used with different pointers\n");
17405 return -EINVAL;
17406 }
17407 }
17408
17409 return 0;
17410}
17411
58e2af8b 17412static int do_check(struct bpf_verifier_env *env)
17a52670 17413{
6f8a57cc 17414 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 17415 struct bpf_verifier_state *state = env->cur_state;
17a52670 17416 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 17417 struct bpf_reg_state *regs;
06ee7115 17418 int insn_cnt = env->prog->len;
17a52670 17419 bool do_print_state = false;
b5dc0163 17420 int prev_insn_idx = -1;
17a52670 17421
17a52670 17422 for (;;) {
f18b03fa 17423 bool exception_exit = false;
17a52670
AS
17424 struct bpf_insn *insn;
17425 u8 class;
17426 int err;
17427
b5dc0163 17428 env->prev_insn_idx = prev_insn_idx;
c08435ec 17429 if (env->insn_idx >= insn_cnt) {
61bd5218 17430 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 17431 env->insn_idx, insn_cnt);
17a52670
AS
17432 return -EFAULT;
17433 }
17434
c08435ec 17435 insn = &insns[env->insn_idx];
17a52670
AS
17436 class = BPF_CLASS(insn->code);
17437
06ee7115 17438 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
17439 verbose(env,
17440 "BPF program is too large. Processed %d insn\n",
06ee7115 17441 env->insn_processed);
17a52670
AS
17442 return -E2BIG;
17443 }
17444
a095f421
AN
17445 state->last_insn_idx = env->prev_insn_idx;
17446
17447 if (is_prune_point(env, env->insn_idx)) {
17448 err = is_state_visited(env, env->insn_idx);
17449 if (err < 0)
17450 return err;
17451 if (err == 1) {
17452 /* found equivalent state, can prune the search */
17453 if (env->log.level & BPF_LOG_LEVEL) {
17454 if (do_print_state)
17455 verbose(env, "\nfrom %d to %d%s: safe\n",
17456 env->prev_insn_idx, env->insn_idx,
17457 env->cur_state->speculative ?
17458 " (speculative execution)" : "");
17459 else
17460 verbose(env, "%d: safe\n", env->insn_idx);
17461 }
17462 goto process_bpf_exit;
f1bca824 17463 }
a095f421
AN
17464 }
17465
17466 if (is_jmp_point(env, env->insn_idx)) {
17467 err = push_jmp_history(env, state);
17468 if (err)
17469 return err;
f1bca824
AS
17470 }
17471
c3494801
AS
17472 if (signal_pending(current))
17473 return -EAGAIN;
17474
3c2ce60b
DB
17475 if (need_resched())
17476 cond_resched();
17477
2e576648
CL
17478 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17479 verbose(env, "\nfrom %d to %d%s:",
17480 env->prev_insn_idx, env->insn_idx,
17481 env->cur_state->speculative ?
17482 " (speculative execution)" : "");
17483 print_verifier_state(env, state->frame[state->curframe], true);
17a52670
AS
17484 do_print_state = false;
17485 }
17486
06ee7115 17487 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 17488 const struct bpf_insn_cbs cbs = {
e6ac2450 17489 .cb_call = disasm_kfunc_name,
7105e828 17490 .cb_print = verbose,
abe08840 17491 .private_data = env,
7105e828
DB
17492 };
17493
2e576648
CL
17494 if (verifier_state_scratched(env))
17495 print_insn_state(env, state->frame[state->curframe]);
17496
c08435ec 17497 verbose_linfo(env, env->insn_idx, "; ");
12166409 17498 env->prev_log_pos = env->log.end_pos;
c08435ec 17499 verbose(env, "%d: ", env->insn_idx);
abe08840 17500 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12166409
AN
17501 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17502 env->prev_log_pos = env->log.end_pos;
17a52670
AS
17503 }
17504
9d03ebc7 17505 if (bpf_prog_is_offloaded(env->prog->aux)) {
c08435ec
DB
17506 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17507 env->prev_insn_idx);
cae1927c
JK
17508 if (err)
17509 return err;
17510 }
13a27dfc 17511
638f5b90 17512 regs = cur_regs(env);
fe9a5ca7 17513 sanitize_mark_insn_seen(env);
b5dc0163 17514 prev_insn_idx = env->insn_idx;
fd978bf7 17515
17a52670 17516 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 17517 err = check_alu_op(env, insn);
17a52670
AS
17518 if (err)
17519 return err;
17520
17521 } else if (class == BPF_LDX) {
0d80a619 17522 enum bpf_reg_type src_reg_type;
9bac3d6d
AS
17523
17524 /* check for reserved fields is already done */
17525
17a52670 17526 /* check src operand */
dc503a8a 17527 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
17528 if (err)
17529 return err;
17530
dc503a8a 17531 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
17532 if (err)
17533 return err;
17534
725f9dcd
AS
17535 src_reg_type = regs[insn->src_reg].type;
17536
17a52670
AS
17537 /* check that memory (src_reg + off) is readable,
17538 * the state of dst_reg will be updated by this func
17539 */
c08435ec
DB
17540 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17541 insn->off, BPF_SIZE(insn->code),
1f9a1ea8
YS
17542 BPF_READ, insn->dst_reg, false,
17543 BPF_MODE(insn->code) == BPF_MEMSX);
17a52670
AS
17544 if (err)
17545 return err;
17546
0d80a619
EZ
17547 err = save_aux_ptr_type(env, src_reg_type, true);
17548 if (err)
17549 return err;
17a52670 17550 } else if (class == BPF_STX) {
0d80a619 17551 enum bpf_reg_type dst_reg_type;
d691f9e8 17552
91c960b0
BJ
17553 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17554 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
17555 if (err)
17556 return err;
c08435ec 17557 env->insn_idx++;
17a52670
AS
17558 continue;
17559 }
17560
5ca419f2
BJ
17561 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17562 verbose(env, "BPF_STX uses reserved fields\n");
17563 return -EINVAL;
17564 }
17565
17a52670 17566 /* check src1 operand */
dc503a8a 17567 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
17568 if (err)
17569 return err;
17570 /* check src2 operand */
dc503a8a 17571 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
17572 if (err)
17573 return err;
17574
d691f9e8
AS
17575 dst_reg_type = regs[insn->dst_reg].type;
17576
17a52670 17577 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
17578 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17579 insn->off, BPF_SIZE(insn->code),
1f9a1ea8 17580 BPF_WRITE, insn->src_reg, false, false);
17a52670
AS
17581 if (err)
17582 return err;
17583
0d80a619
EZ
17584 err = save_aux_ptr_type(env, dst_reg_type, false);
17585 if (err)
17586 return err;
17a52670 17587 } else if (class == BPF_ST) {
0d80a619
EZ
17588 enum bpf_reg_type dst_reg_type;
17589
17a52670
AS
17590 if (BPF_MODE(insn->code) != BPF_MEM ||
17591 insn->src_reg != BPF_REG_0) {
61bd5218 17592 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
17593 return -EINVAL;
17594 }
17595 /* check src operand */
dc503a8a 17596 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
17597 if (err)
17598 return err;
17599
0d80a619 17600 dst_reg_type = regs[insn->dst_reg].type;
f37a8cb8 17601
17a52670 17602 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
17603 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17604 insn->off, BPF_SIZE(insn->code),
1f9a1ea8 17605 BPF_WRITE, -1, false, false);
17a52670
AS
17606 if (err)
17607 return err;
17608
0d80a619
EZ
17609 err = save_aux_ptr_type(env, dst_reg_type, false);
17610 if (err)
17611 return err;
092ed096 17612 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
17613 u8 opcode = BPF_OP(insn->code);
17614
2589726d 17615 env->jmps_processed++;
17a52670
AS
17616 if (opcode == BPF_CALL) {
17617 if (BPF_SRC(insn->code) != BPF_K ||
2357672c
KKD
17618 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17619 && insn->off != 0) ||
f4d7e40a 17620 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
17621 insn->src_reg != BPF_PSEUDO_CALL &&
17622 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
17623 insn->dst_reg != BPF_REG_0 ||
17624 class == BPF_JMP32) {
61bd5218 17625 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
17626 return -EINVAL;
17627 }
17628
8cab76ec
KKD
17629 if (env->cur_state->active_lock.ptr) {
17630 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17631 (insn->src_reg == BPF_PSEUDO_CALL) ||
17632 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
cd6791b4 17633 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
8cab76ec
KKD
17634 verbose(env, "function calls are not allowed while holding a lock\n");
17635 return -EINVAL;
17636 }
d83525ca 17637 }
f18b03fa 17638 if (insn->src_reg == BPF_PSEUDO_CALL) {
c08435ec 17639 err = check_func_call(env, insn, &env->insn_idx);
f18b03fa 17640 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
5c073f26 17641 err = check_kfunc_call(env, insn, &env->insn_idx);
f18b03fa
KKD
17642 if (!err && is_bpf_throw_kfunc(insn)) {
17643 exception_exit = true;
17644 goto process_bpf_exit_full;
17645 }
17646 } else {
69c087ba 17647 err = check_helper_call(env, insn, &env->insn_idx);
f18b03fa 17648 }
17a52670
AS
17649 if (err)
17650 return err;
553a64a8
AN
17651
17652 mark_reg_scratched(env, BPF_REG_0);
17a52670
AS
17653 } else if (opcode == BPF_JA) {
17654 if (BPF_SRC(insn->code) != BPF_K ||
17a52670 17655 insn->src_reg != BPF_REG_0 ||
092ed096 17656 insn->dst_reg != BPF_REG_0 ||
4cd58e9a
YS
17657 (class == BPF_JMP && insn->imm != 0) ||
17658 (class == BPF_JMP32 && insn->off != 0)) {
61bd5218 17659 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
17660 return -EINVAL;
17661 }
17662
4cd58e9a
YS
17663 if (class == BPF_JMP)
17664 env->insn_idx += insn->off + 1;
17665 else
17666 env->insn_idx += insn->imm + 1;
17a52670
AS
17667 continue;
17668
17669 } else if (opcode == BPF_EXIT) {
17670 if (BPF_SRC(insn->code) != BPF_K ||
17671 insn->imm != 0 ||
17672 insn->src_reg != BPF_REG_0 ||
092ed096
JW
17673 insn->dst_reg != BPF_REG_0 ||
17674 class == BPF_JMP32) {
61bd5218 17675 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
17676 return -EINVAL;
17677 }
f18b03fa 17678process_bpf_exit_full:
5d92ddc3
DM
17679 if (env->cur_state->active_lock.ptr &&
17680 !in_rbtree_lock_required_cb(env)) {
d83525ca
AS
17681 verbose(env, "bpf_spin_unlock is missing\n");
17682 return -EINVAL;
17683 }
17684
0816b8c6
DM
17685 if (env->cur_state->active_rcu_lock &&
17686 !in_rbtree_lock_required_cb(env)) {
9bb00b28
YS
17687 verbose(env, "bpf_rcu_read_unlock is missing\n");
17688 return -EINVAL;
17689 }
17690
9d9d00ac
KKD
17691 /* We must do check_reference_leak here before
17692 * prepare_func_exit to handle the case when
17693 * state->curframe > 0, it may be a callback
17694 * function, for which reference_state must
17695 * match caller reference state when it exits.
17696 */
f18b03fa 17697 err = check_reference_leak(env, exception_exit);
9d9d00ac
KKD
17698 if (err)
17699 return err;
17700
f18b03fa
KKD
17701 /* The side effect of the prepare_func_exit
17702 * which is being skipped is that it frees
17703 * bpf_func_state. Typically, process_bpf_exit
17704 * will only be hit with outermost exit.
17705 * copy_verifier_state in pop_stack will handle
17706 * freeing of any extra bpf_func_state left over
17707 * from not processing all nested function
17708 * exits. We also skip return code checks as
17709 * they are not needed for exceptional exits.
17710 */
17711 if (exception_exit)
17712 goto process_bpf_exit;
17713
f4d7e40a
AS
17714 if (state->curframe) {
17715 /* exit from nested function */
c08435ec 17716 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
17717 if (err)
17718 return err;
17719 do_print_state = true;
17720 continue;
17721 }
17722
a923819f 17723 err = check_return_code(env, BPF_REG_0);
390ee7e2
AS
17724 if (err)
17725 return err;
f1bca824 17726process_bpf_exit:
0f55f9ed 17727 mark_verifier_state_scratched(env);
2589726d 17728 update_branch_counts(env, env->cur_state);
b5dc0163 17729 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 17730 &env->insn_idx, pop_log);
638f5b90
AS
17731 if (err < 0) {
17732 if (err != -ENOENT)
17733 return err;
17a52670
AS
17734 break;
17735 } else {
17736 do_print_state = true;
17737 continue;
17738 }
17739 } else {
c08435ec 17740 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
17741 if (err)
17742 return err;
17743 }
17744 } else if (class == BPF_LD) {
17745 u8 mode = BPF_MODE(insn->code);
17746
17747 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
17748 err = check_ld_abs(env, insn);
17749 if (err)
17750 return err;
17751
17a52670
AS
17752 } else if (mode == BPF_IMM) {
17753 err = check_ld_imm(env, insn);
17754 if (err)
17755 return err;
17756
c08435ec 17757 env->insn_idx++;
fe9a5ca7 17758 sanitize_mark_insn_seen(env);
17a52670 17759 } else {
61bd5218 17760 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
17761 return -EINVAL;
17762 }
17763 } else {
61bd5218 17764 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
17765 return -EINVAL;
17766 }
17767
c08435ec 17768 env->insn_idx++;
17a52670
AS
17769 }
17770
17771 return 0;
17772}
17773
541c3bad
AN
17774static int find_btf_percpu_datasec(struct btf *btf)
17775{
17776 const struct btf_type *t;
17777 const char *tname;
17778 int i, n;
17779
17780 /*
17781 * Both vmlinux and module each have their own ".data..percpu"
17782 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17783 * types to look at only module's own BTF types.
17784 */
17785 n = btf_nr_types(btf);
17786 if (btf_is_module(btf))
17787 i = btf_nr_types(btf_vmlinux);
17788 else
17789 i = 1;
17790
17791 for(; i < n; i++) {
17792 t = btf_type_by_id(btf, i);
17793 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17794 continue;
17795
17796 tname = btf_name_by_offset(btf, t->name_off);
17797 if (!strcmp(tname, ".data..percpu"))
17798 return i;
17799 }
17800
17801 return -ENOENT;
17802}
17803
4976b718
HL
17804/* replace pseudo btf_id with kernel symbol address */
17805static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17806 struct bpf_insn *insn,
17807 struct bpf_insn_aux_data *aux)
17808{
eaa6bcb7
HL
17809 const struct btf_var_secinfo *vsi;
17810 const struct btf_type *datasec;
541c3bad 17811 struct btf_mod_pair *btf_mod;
4976b718
HL
17812 const struct btf_type *t;
17813 const char *sym_name;
eaa6bcb7 17814 bool percpu = false;
f16e6313 17815 u32 type, id = insn->imm;
541c3bad 17816 struct btf *btf;
f16e6313 17817 s32 datasec_id;
4976b718 17818 u64 addr;
541c3bad 17819 int i, btf_fd, err;
4976b718 17820
541c3bad
AN
17821 btf_fd = insn[1].imm;
17822 if (btf_fd) {
17823 btf = btf_get_by_fd(btf_fd);
17824 if (IS_ERR(btf)) {
17825 verbose(env, "invalid module BTF object FD specified.\n");
17826 return -EINVAL;
17827 }
17828 } else {
17829 if (!btf_vmlinux) {
17830 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17831 return -EINVAL;
17832 }
17833 btf = btf_vmlinux;
17834 btf_get(btf);
4976b718
HL
17835 }
17836
541c3bad 17837 t = btf_type_by_id(btf, id);
4976b718
HL
17838 if (!t) {
17839 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
17840 err = -ENOENT;
17841 goto err_put;
4976b718
HL
17842 }
17843
58aa2afb
AS
17844 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17845 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
541c3bad
AN
17846 err = -EINVAL;
17847 goto err_put;
4976b718
HL
17848 }
17849
541c3bad 17850 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
17851 addr = kallsyms_lookup_name(sym_name);
17852 if (!addr) {
17853 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17854 sym_name);
541c3bad
AN
17855 err = -ENOENT;
17856 goto err_put;
4976b718 17857 }
58aa2afb
AS
17858 insn[0].imm = (u32)addr;
17859 insn[1].imm = addr >> 32;
17860
17861 if (btf_type_is_func(t)) {
17862 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17863 aux->btf_var.mem_size = 0;
17864 goto check_btf;
17865 }
4976b718 17866
541c3bad 17867 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 17868 if (datasec_id > 0) {
541c3bad 17869 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
17870 for_each_vsi(i, datasec, vsi) {
17871 if (vsi->type == id) {
17872 percpu = true;
17873 break;
17874 }
17875 }
17876 }
17877
4976b718 17878 type = t->type;
541c3bad 17879 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7 17880 if (percpu) {
5844101a 17881 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
541c3bad 17882 aux->btf_var.btf = btf;
eaa6bcb7
HL
17883 aux->btf_var.btf_id = type;
17884 } else if (!btf_type_is_struct(t)) {
4976b718
HL
17885 const struct btf_type *ret;
17886 const char *tname;
17887 u32 tsize;
17888
17889 /* resolve the type size of ksym. */
541c3bad 17890 ret = btf_resolve_size(btf, t, &tsize);
4976b718 17891 if (IS_ERR(ret)) {
541c3bad 17892 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
17893 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17894 tname, PTR_ERR(ret));
541c3bad
AN
17895 err = -EINVAL;
17896 goto err_put;
4976b718 17897 }
34d3a78c 17898 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
4976b718
HL
17899 aux->btf_var.mem_size = tsize;
17900 } else {
17901 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 17902 aux->btf_var.btf = btf;
4976b718
HL
17903 aux->btf_var.btf_id = type;
17904 }
58aa2afb 17905check_btf:
541c3bad
AN
17906 /* check whether we recorded this BTF (and maybe module) already */
17907 for (i = 0; i < env->used_btf_cnt; i++) {
17908 if (env->used_btfs[i].btf == btf) {
17909 btf_put(btf);
17910 return 0;
17911 }
17912 }
17913
17914 if (env->used_btf_cnt >= MAX_USED_BTFS) {
17915 err = -E2BIG;
17916 goto err_put;
17917 }
17918
17919 btf_mod = &env->used_btfs[env->used_btf_cnt];
17920 btf_mod->btf = btf;
17921 btf_mod->module = NULL;
17922
17923 /* if we reference variables from kernel module, bump its refcount */
17924 if (btf_is_module(btf)) {
17925 btf_mod->module = btf_try_get_module(btf);
17926 if (!btf_mod->module) {
17927 err = -ENXIO;
17928 goto err_put;
17929 }
17930 }
17931
17932 env->used_btf_cnt++;
17933
4976b718 17934 return 0;
541c3bad
AN
17935err_put:
17936 btf_put(btf);
17937 return err;
4976b718
HL
17938}
17939
d83525ca
AS
17940static bool is_tracing_prog_type(enum bpf_prog_type type)
17941{
17942 switch (type) {
17943 case BPF_PROG_TYPE_KPROBE:
17944 case BPF_PROG_TYPE_TRACEPOINT:
17945 case BPF_PROG_TYPE_PERF_EVENT:
17946 case BPF_PROG_TYPE_RAW_TRACEPOINT:
5002615a 17947 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
d83525ca
AS
17948 return true;
17949 default:
17950 return false;
17951 }
17952}
17953
61bd5218
JK
17954static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17955 struct bpf_map *map,
fdc15d38
AS
17956 struct bpf_prog *prog)
17957
17958{
7e40781c 17959 enum bpf_prog_type prog_type = resolve_prog_type(prog);
a3884572 17960
9c395c1b
DM
17961 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17962 btf_record_has_field(map->record, BPF_RB_ROOT)) {
f0c5941f 17963 if (is_tracing_prog_type(prog_type)) {
9c395c1b 17964 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
f0c5941f
KKD
17965 return -EINVAL;
17966 }
17967 }
17968
db559117 17969 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
9e7a4d98
KS
17970 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17971 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17972 return -EINVAL;
17973 }
17974
17975 if (is_tracing_prog_type(prog_type)) {
17976 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17977 return -EINVAL;
17978 }
d83525ca
AS
17979 }
17980
db559117 17981 if (btf_record_has_field(map->record, BPF_TIMER)) {
5e0bc308
DB
17982 if (is_tracing_prog_type(prog_type)) {
17983 verbose(env, "tracing progs cannot use bpf_timer yet\n");
17984 return -EINVAL;
17985 }
17986 }
17987
9d03ebc7 17988 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
09728266 17989 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
17990 verbose(env, "offload device mismatch between prog and map\n");
17991 return -EINVAL;
17992 }
17993
85d33df3
MKL
17994 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17995 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17996 return -EINVAL;
17997 }
17998
1e6c62a8
AS
17999 if (prog->aux->sleepable)
18000 switch (map->map_type) {
18001 case BPF_MAP_TYPE_HASH:
18002 case BPF_MAP_TYPE_LRU_HASH:
18003 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
18004 case BPF_MAP_TYPE_PERCPU_HASH:
18005 case BPF_MAP_TYPE_PERCPU_ARRAY:
18006 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18007 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18008 case BPF_MAP_TYPE_HASH_OF_MAPS:
ba90c2cc 18009 case BPF_MAP_TYPE_RINGBUF:
583c1f42 18010 case BPF_MAP_TYPE_USER_RINGBUF:
0fe4b381
KS
18011 case BPF_MAP_TYPE_INODE_STORAGE:
18012 case BPF_MAP_TYPE_SK_STORAGE:
18013 case BPF_MAP_TYPE_TASK_STORAGE:
2c40d97d 18014 case BPF_MAP_TYPE_CGRP_STORAGE:
ba90c2cc 18015 break;
1e6c62a8
AS
18016 default:
18017 verbose(env,
2c40d97d 18018 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
1e6c62a8
AS
18019 return -EINVAL;
18020 }
18021
fdc15d38
AS
18022 return 0;
18023}
18024
b741f163
RG
18025static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18026{
18027 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18028 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18029}
18030
4976b718
HL
18031/* find and rewrite pseudo imm in ld_imm64 instructions:
18032 *
18033 * 1. if it accesses map FD, replace it with actual map pointer.
18034 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18035 *
18036 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 18037 */
4976b718 18038static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
18039{
18040 struct bpf_insn *insn = env->prog->insnsi;
18041 int insn_cnt = env->prog->len;
fdc15d38 18042 int i, j, err;
0246e64d 18043
f1f7714e 18044 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
18045 if (err)
18046 return err;
18047
0246e64d 18048 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 18049 if (BPF_CLASS(insn->code) == BPF_LDX &&
1f9a1ea8
YS
18050 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18051 insn->imm != 0)) {
61bd5218 18052 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
18053 return -EINVAL;
18054 }
18055
0246e64d 18056 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 18057 struct bpf_insn_aux_data *aux;
0246e64d
AS
18058 struct bpf_map *map;
18059 struct fd f;
d8eca5bb 18060 u64 addr;
387544bf 18061 u32 fd;
0246e64d
AS
18062
18063 if (i == insn_cnt - 1 || insn[1].code != 0 ||
18064 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18065 insn[1].off != 0) {
61bd5218 18066 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
18067 return -EINVAL;
18068 }
18069
d8eca5bb 18070 if (insn[0].src_reg == 0)
0246e64d
AS
18071 /* valid generic load 64-bit imm */
18072 goto next_insn;
18073
4976b718
HL
18074 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18075 aux = &env->insn_aux_data[i];
18076 err = check_pseudo_btf_id(env, insn, aux);
18077 if (err)
18078 return err;
18079 goto next_insn;
18080 }
18081
69c087ba
YS
18082 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18083 aux = &env->insn_aux_data[i];
18084 aux->ptr_type = PTR_TO_FUNC;
18085 goto next_insn;
18086 }
18087
d8eca5bb
DB
18088 /* In final convert_pseudo_ld_imm64() step, this is
18089 * converted into regular 64-bit imm load insn.
18090 */
387544bf
AS
18091 switch (insn[0].src_reg) {
18092 case BPF_PSEUDO_MAP_VALUE:
18093 case BPF_PSEUDO_MAP_IDX_VALUE:
18094 break;
18095 case BPF_PSEUDO_MAP_FD:
18096 case BPF_PSEUDO_MAP_IDX:
18097 if (insn[1].imm == 0)
18098 break;
18099 fallthrough;
18100 default:
18101 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
18102 return -EINVAL;
18103 }
18104
387544bf
AS
18105 switch (insn[0].src_reg) {
18106 case BPF_PSEUDO_MAP_IDX_VALUE:
18107 case BPF_PSEUDO_MAP_IDX:
18108 if (bpfptr_is_null(env->fd_array)) {
18109 verbose(env, "fd_idx without fd_array is invalid\n");
18110 return -EPROTO;
18111 }
18112 if (copy_from_bpfptr_offset(&fd, env->fd_array,
18113 insn[0].imm * sizeof(fd),
18114 sizeof(fd)))
18115 return -EFAULT;
18116 break;
18117 default:
18118 fd = insn[0].imm;
18119 break;
18120 }
18121
18122 f = fdget(fd);
c2101297 18123 map = __bpf_map_get(f);
0246e64d 18124 if (IS_ERR(map)) {
61bd5218 18125 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 18126 insn[0].imm);
0246e64d
AS
18127 return PTR_ERR(map);
18128 }
18129
61bd5218 18130 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
18131 if (err) {
18132 fdput(f);
18133 return err;
18134 }
18135
d8eca5bb 18136 aux = &env->insn_aux_data[i];
387544bf
AS
18137 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18138 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
d8eca5bb
DB
18139 addr = (unsigned long)map;
18140 } else {
18141 u32 off = insn[1].imm;
18142
18143 if (off >= BPF_MAX_VAR_OFF) {
18144 verbose(env, "direct value offset of %u is not allowed\n", off);
18145 fdput(f);
18146 return -EINVAL;
18147 }
18148
18149 if (!map->ops->map_direct_value_addr) {
18150 verbose(env, "no direct value access support for this map type\n");
18151 fdput(f);
18152 return -EINVAL;
18153 }
18154
18155 err = map->ops->map_direct_value_addr(map, &addr, off);
18156 if (err) {
18157 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18158 map->value_size, off);
18159 fdput(f);
18160 return err;
18161 }
18162
18163 aux->map_off = off;
18164 addr += off;
18165 }
18166
18167 insn[0].imm = (u32)addr;
18168 insn[1].imm = addr >> 32;
0246e64d
AS
18169
18170 /* check whether we recorded this map already */
d8eca5bb 18171 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 18172 if (env->used_maps[j] == map) {
d8eca5bb 18173 aux->map_index = j;
0246e64d
AS
18174 fdput(f);
18175 goto next_insn;
18176 }
d8eca5bb 18177 }
0246e64d
AS
18178
18179 if (env->used_map_cnt >= MAX_USED_MAPS) {
18180 fdput(f);
18181 return -E2BIG;
18182 }
18183
0246e64d
AS
18184 /* hold the map. If the program is rejected by verifier,
18185 * the map will be released by release_maps() or it
18186 * will be used by the valid program until it's unloaded
ab7f5bf0 18187 * and all maps are released in free_used_maps()
0246e64d 18188 */
1e0bd5a0 18189 bpf_map_inc(map);
d8eca5bb
DB
18190
18191 aux->map_index = env->used_map_cnt;
92117d84
AS
18192 env->used_maps[env->used_map_cnt++] = map;
18193
b741f163 18194 if (bpf_map_is_cgroup_storage(map) &&
e4730423 18195 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 18196 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
18197 fdput(f);
18198 return -EBUSY;
18199 }
18200
0246e64d
AS
18201 fdput(f);
18202next_insn:
18203 insn++;
18204 i++;
5e581dad
DB
18205 continue;
18206 }
18207
18208 /* Basic sanity check before we invest more work here. */
18209 if (!bpf_opcode_in_insntable(insn->code)) {
18210 verbose(env, "unknown opcode %02x\n", insn->code);
18211 return -EINVAL;
0246e64d
AS
18212 }
18213 }
18214
18215 /* now all pseudo BPF_LD_IMM64 instructions load valid
18216 * 'struct bpf_map *' into a register instead of user map_fd.
18217 * These pointers will be used later by verifier to validate map access.
18218 */
18219 return 0;
18220}
18221
18222/* drop refcnt of maps used by the rejected program */
58e2af8b 18223static void release_maps(struct bpf_verifier_env *env)
0246e64d 18224{
a2ea0746
DB
18225 __bpf_free_used_maps(env->prog->aux, env->used_maps,
18226 env->used_map_cnt);
0246e64d
AS
18227}
18228
541c3bad
AN
18229/* drop refcnt of maps used by the rejected program */
18230static void release_btfs(struct bpf_verifier_env *env)
18231{
18232 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18233 env->used_btf_cnt);
18234}
18235
0246e64d 18236/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 18237static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
18238{
18239 struct bpf_insn *insn = env->prog->insnsi;
18240 int insn_cnt = env->prog->len;
18241 int i;
18242
69c087ba
YS
18243 for (i = 0; i < insn_cnt; i++, insn++) {
18244 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18245 continue;
18246 if (insn->src_reg == BPF_PSEUDO_FUNC)
18247 continue;
18248 insn->src_reg = 0;
18249 }
0246e64d
AS
18250}
18251
8041902d
AS
18252/* single env->prog->insni[off] instruction was replaced with the range
18253 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
18254 * [0, off) and [off, end) to new locations, so the patched range stays zero
18255 */
75f0fc7b
HF
18256static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18257 struct bpf_insn_aux_data *new_data,
18258 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d 18259{
75f0fc7b 18260 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
b325fbca 18261 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 18262 u32 old_seen = old_data[off].seen;
b325fbca 18263 u32 prog_len;
c131187d 18264 int i;
8041902d 18265
b325fbca
JW
18266 /* aux info at OFF always needs adjustment, no matter fast path
18267 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18268 * original insn at old prog.
18269 */
18270 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18271
8041902d 18272 if (cnt == 1)
75f0fc7b 18273 return;
b325fbca 18274 prog_len = new_prog->len;
75f0fc7b 18275
8041902d
AS
18276 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18277 memcpy(new_data + off + cnt - 1, old_data + off,
18278 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 18279 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
18280 /* Expand insni[off]'s seen count to the patched range. */
18281 new_data[i].seen = old_seen;
b325fbca
JW
18282 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18283 }
8041902d
AS
18284 env->insn_aux_data = new_data;
18285 vfree(old_data);
8041902d
AS
18286}
18287
cc8b0b92
AS
18288static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18289{
18290 int i;
18291
18292 if (len == 1)
18293 return;
4cb3d99c
JW
18294 /* NOTE: fake 'exit' subprog should be updated as well. */
18295 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 18296 if (env->subprog_info[i].start <= off)
cc8b0b92 18297 continue;
9c8105bd 18298 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
18299 }
18300}
18301
7506d211 18302static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
a748c697
MF
18303{
18304 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18305 int i, sz = prog->aux->size_poke_tab;
18306 struct bpf_jit_poke_descriptor *desc;
18307
18308 for (i = 0; i < sz; i++) {
18309 desc = &tab[i];
7506d211
JF
18310 if (desc->insn_idx <= off)
18311 continue;
a748c697
MF
18312 desc->insn_idx += len - 1;
18313 }
18314}
18315
8041902d
AS
18316static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18317 const struct bpf_insn *patch, u32 len)
18318{
18319 struct bpf_prog *new_prog;
75f0fc7b
HF
18320 struct bpf_insn_aux_data *new_data = NULL;
18321
18322 if (len > 1) {
18323 new_data = vzalloc(array_size(env->prog->len + len - 1,
18324 sizeof(struct bpf_insn_aux_data)));
18325 if (!new_data)
18326 return NULL;
18327 }
8041902d
AS
18328
18329 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
18330 if (IS_ERR(new_prog)) {
18331 if (PTR_ERR(new_prog) == -ERANGE)
18332 verbose(env,
18333 "insn %d cannot be patched due to 16-bit range\n",
18334 env->insn_aux_data[off].orig_idx);
75f0fc7b 18335 vfree(new_data);
8041902d 18336 return NULL;
4f73379e 18337 }
75f0fc7b 18338 adjust_insn_aux_data(env, new_data, new_prog, off, len);
cc8b0b92 18339 adjust_subprog_starts(env, off, len);
7506d211 18340 adjust_poke_descs(new_prog, off, len);
8041902d
AS
18341 return new_prog;
18342}
18343
52875a04
JK
18344static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18345 u32 off, u32 cnt)
18346{
18347 int i, j;
18348
18349 /* find first prog starting at or after off (first to remove) */
18350 for (i = 0; i < env->subprog_cnt; i++)
18351 if (env->subprog_info[i].start >= off)
18352 break;
18353 /* find first prog starting at or after off + cnt (first to stay) */
18354 for (j = i; j < env->subprog_cnt; j++)
18355 if (env->subprog_info[j].start >= off + cnt)
18356 break;
18357 /* if j doesn't start exactly at off + cnt, we are just removing
18358 * the front of previous prog
18359 */
18360 if (env->subprog_info[j].start != off + cnt)
18361 j--;
18362
18363 if (j > i) {
18364 struct bpf_prog_aux *aux = env->prog->aux;
18365 int move;
18366
18367 /* move fake 'exit' subprog as well */
18368 move = env->subprog_cnt + 1 - j;
18369
18370 memmove(env->subprog_info + i,
18371 env->subprog_info + j,
18372 sizeof(*env->subprog_info) * move);
18373 env->subprog_cnt -= j - i;
18374
18375 /* remove func_info */
18376 if (aux->func_info) {
18377 move = aux->func_info_cnt - j;
18378
18379 memmove(aux->func_info + i,
18380 aux->func_info + j,
18381 sizeof(*aux->func_info) * move);
18382 aux->func_info_cnt -= j - i;
18383 /* func_info->insn_off is set after all code rewrites,
18384 * in adjust_btf_func() - no need to adjust
18385 */
18386 }
18387 } else {
18388 /* convert i from "first prog to remove" to "first to adjust" */
18389 if (env->subprog_info[i].start == off)
18390 i++;
18391 }
18392
18393 /* update fake 'exit' subprog as well */
18394 for (; i <= env->subprog_cnt; i++)
18395 env->subprog_info[i].start -= cnt;
18396
18397 return 0;
18398}
18399
18400static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18401 u32 cnt)
18402{
18403 struct bpf_prog *prog = env->prog;
18404 u32 i, l_off, l_cnt, nr_linfo;
18405 struct bpf_line_info *linfo;
18406
18407 nr_linfo = prog->aux->nr_linfo;
18408 if (!nr_linfo)
18409 return 0;
18410
18411 linfo = prog->aux->linfo;
18412
18413 /* find first line info to remove, count lines to be removed */
18414 for (i = 0; i < nr_linfo; i++)
18415 if (linfo[i].insn_off >= off)
18416 break;
18417
18418 l_off = i;
18419 l_cnt = 0;
18420 for (; i < nr_linfo; i++)
18421 if (linfo[i].insn_off < off + cnt)
18422 l_cnt++;
18423 else
18424 break;
18425
18426 /* First live insn doesn't match first live linfo, it needs to "inherit"
18427 * last removed linfo. prog is already modified, so prog->len == off
18428 * means no live instructions after (tail of the program was removed).
18429 */
18430 if (prog->len != off && l_cnt &&
18431 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18432 l_cnt--;
18433 linfo[--i].insn_off = off + cnt;
18434 }
18435
18436 /* remove the line info which refer to the removed instructions */
18437 if (l_cnt) {
18438 memmove(linfo + l_off, linfo + i,
18439 sizeof(*linfo) * (nr_linfo - i));
18440
18441 prog->aux->nr_linfo -= l_cnt;
18442 nr_linfo = prog->aux->nr_linfo;
18443 }
18444
18445 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18446 for (i = l_off; i < nr_linfo; i++)
18447 linfo[i].insn_off -= cnt;
18448
18449 /* fix up all subprogs (incl. 'exit') which start >= off */
18450 for (i = 0; i <= env->subprog_cnt; i++)
18451 if (env->subprog_info[i].linfo_idx > l_off) {
18452 /* program may have started in the removed region but
18453 * may not be fully removed
18454 */
18455 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18456 env->subprog_info[i].linfo_idx -= l_cnt;
18457 else
18458 env->subprog_info[i].linfo_idx = l_off;
18459 }
18460
18461 return 0;
18462}
18463
18464static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18465{
18466 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18467 unsigned int orig_prog_len = env->prog->len;
18468 int err;
18469
9d03ebc7 18470 if (bpf_prog_is_offloaded(env->prog->aux))
08ca90af
JK
18471 bpf_prog_offload_remove_insns(env, off, cnt);
18472
52875a04
JK
18473 err = bpf_remove_insns(env->prog, off, cnt);
18474 if (err)
18475 return err;
18476
18477 err = adjust_subprog_starts_after_remove(env, off, cnt);
18478 if (err)
18479 return err;
18480
18481 err = bpf_adj_linfo_after_remove(env, off, cnt);
18482 if (err)
18483 return err;
18484
18485 memmove(aux_data + off, aux_data + off + cnt,
18486 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18487
18488 return 0;
18489}
18490
2a5418a1
DB
18491/* The verifier does more data flow analysis than llvm and will not
18492 * explore branches that are dead at run time. Malicious programs can
18493 * have dead code too. Therefore replace all dead at-run-time code
18494 * with 'ja -1'.
18495 *
18496 * Just nops are not optimal, e.g. if they would sit at the end of the
18497 * program and through another bug we would manage to jump there, then
18498 * we'd execute beyond program memory otherwise. Returning exception
18499 * code also wouldn't work since we can have subprogs where the dead
18500 * code could be located.
c131187d
AS
18501 */
18502static void sanitize_dead_code(struct bpf_verifier_env *env)
18503{
18504 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 18505 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
18506 struct bpf_insn *insn = env->prog->insnsi;
18507 const int insn_cnt = env->prog->len;
18508 int i;
18509
18510 for (i = 0; i < insn_cnt; i++) {
18511 if (aux_data[i].seen)
18512 continue;
2a5418a1 18513 memcpy(insn + i, &trap, sizeof(trap));
45c709f8 18514 aux_data[i].zext_dst = false;
c131187d
AS
18515 }
18516}
18517
e2ae4ca2
JK
18518static bool insn_is_cond_jump(u8 code)
18519{
18520 u8 op;
18521
4cd58e9a 18522 op = BPF_OP(code);
092ed096 18523 if (BPF_CLASS(code) == BPF_JMP32)
4cd58e9a 18524 return op != BPF_JA;
092ed096 18525
e2ae4ca2
JK
18526 if (BPF_CLASS(code) != BPF_JMP)
18527 return false;
18528
e2ae4ca2
JK
18529 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18530}
18531
18532static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18533{
18534 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18535 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18536 struct bpf_insn *insn = env->prog->insnsi;
18537 const int insn_cnt = env->prog->len;
18538 int i;
18539
18540 for (i = 0; i < insn_cnt; i++, insn++) {
18541 if (!insn_is_cond_jump(insn->code))
18542 continue;
18543
18544 if (!aux_data[i + 1].seen)
18545 ja.off = insn->off;
18546 else if (!aux_data[i + 1 + insn->off].seen)
18547 ja.off = 0;
18548 else
18549 continue;
18550
9d03ebc7 18551 if (bpf_prog_is_offloaded(env->prog->aux))
08ca90af
JK
18552 bpf_prog_offload_replace_insn(env, i, &ja);
18553
e2ae4ca2
JK
18554 memcpy(insn, &ja, sizeof(ja));
18555 }
18556}
18557
52875a04
JK
18558static int opt_remove_dead_code(struct bpf_verifier_env *env)
18559{
18560 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18561 int insn_cnt = env->prog->len;
18562 int i, err;
18563
18564 for (i = 0; i < insn_cnt; i++) {
18565 int j;
18566
18567 j = 0;
18568 while (i + j < insn_cnt && !aux_data[i + j].seen)
18569 j++;
18570 if (!j)
18571 continue;
18572
18573 err = verifier_remove_insns(env, i, j);
18574 if (err)
18575 return err;
18576 insn_cnt = env->prog->len;
18577 }
18578
18579 return 0;
18580}
18581
a1b14abc
JK
18582static int opt_remove_nops(struct bpf_verifier_env *env)
18583{
18584 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18585 struct bpf_insn *insn = env->prog->insnsi;
18586 int insn_cnt = env->prog->len;
18587 int i, err;
18588
18589 for (i = 0; i < insn_cnt; i++) {
18590 if (memcmp(&insn[i], &ja, sizeof(ja)))
18591 continue;
18592
18593 err = verifier_remove_insns(env, i, 1);
18594 if (err)
18595 return err;
18596 insn_cnt--;
18597 i--;
18598 }
18599
18600 return 0;
18601}
18602
d6c2308c
JW
18603static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18604 const union bpf_attr *attr)
a4b1d3c1 18605{
d6c2308c 18606 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 18607 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 18608 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 18609 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 18610 struct bpf_prog *new_prog;
d6c2308c 18611 bool rnd_hi32;
a4b1d3c1 18612
d6c2308c 18613 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 18614 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
18615 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18616 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18617 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
18618 for (i = 0; i < len; i++) {
18619 int adj_idx = i + delta;
18620 struct bpf_insn insn;
83a28819 18621 int load_reg;
a4b1d3c1 18622
d6c2308c 18623 insn = insns[adj_idx];
83a28819 18624 load_reg = insn_def_regno(&insn);
d6c2308c
JW
18625 if (!aux[adj_idx].zext_dst) {
18626 u8 code, class;
18627 u32 imm_rnd;
18628
18629 if (!rnd_hi32)
18630 continue;
18631
18632 code = insn.code;
18633 class = BPF_CLASS(code);
83a28819 18634 if (load_reg == -1)
d6c2308c
JW
18635 continue;
18636
18637 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
18638 * BPF_STX + SRC_OP, so it is safe to pass NULL
18639 * here.
d6c2308c 18640 */
83a28819 18641 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
18642 if (class == BPF_LD &&
18643 BPF_MODE(code) == BPF_IMM)
18644 i++;
18645 continue;
18646 }
18647
18648 /* ctx load could be transformed into wider load. */
18649 if (class == BPF_LDX &&
18650 aux[adj_idx].ptr_type == PTR_TO_CTX)
18651 continue;
18652
a251c17a 18653 imm_rnd = get_random_u32();
d6c2308c
JW
18654 rnd_hi32_patch[0] = insn;
18655 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 18656 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
18657 patch = rnd_hi32_patch;
18658 patch_len = 4;
18659 goto apply_patch_buffer;
18660 }
18661
39491867
BJ
18662 /* Add in an zero-extend instruction if a) the JIT has requested
18663 * it or b) it's a CMPXCHG.
18664 *
18665 * The latter is because: BPF_CMPXCHG always loads a value into
18666 * R0, therefore always zero-extends. However some archs'
18667 * equivalent instruction only does this load when the
18668 * comparison is successful. This detail of CMPXCHG is
18669 * orthogonal to the general zero-extension behaviour of the
18670 * CPU, so it's treated independently of bpf_jit_needs_zext.
18671 */
18672 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
18673 continue;
18674
d35af0a7
BT
18675 /* Zero-extension is done by the caller. */
18676 if (bpf_pseudo_kfunc_call(&insn))
18677 continue;
18678
83a28819
IL
18679 if (WARN_ON(load_reg == -1)) {
18680 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18681 return -EFAULT;
b2e37a71
IL
18682 }
18683
a4b1d3c1 18684 zext_patch[0] = insn;
b2e37a71
IL
18685 zext_patch[1].dst_reg = load_reg;
18686 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
18687 patch = zext_patch;
18688 patch_len = 2;
18689apply_patch_buffer:
18690 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
18691 if (!new_prog)
18692 return -ENOMEM;
18693 env->prog = new_prog;
18694 insns = new_prog->insnsi;
18695 aux = env->insn_aux_data;
d6c2308c 18696 delta += patch_len - 1;
a4b1d3c1
JW
18697 }
18698
18699 return 0;
18700}
18701
c64b7983
JS
18702/* convert load instructions that access fields of a context type into a
18703 * sequence of instructions that access fields of the underlying structure:
18704 * struct __sk_buff -> struct sk_buff
18705 * struct bpf_sock_ops -> struct sock
9bac3d6d 18706 */
58e2af8b 18707static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 18708{
00176a34 18709 const struct bpf_verifier_ops *ops = env->ops;
f96da094 18710 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 18711 const int insn_cnt = env->prog->len;
36bbef52 18712 struct bpf_insn insn_buf[16], *insn;
46f53a65 18713 u32 target_size, size_default, off;
9bac3d6d 18714 struct bpf_prog *new_prog;
d691f9e8 18715 enum bpf_access_type type;
f96da094 18716 bool is_narrower_load;
9bac3d6d 18717
b09928b9
DB
18718 if (ops->gen_prologue || env->seen_direct_write) {
18719 if (!ops->gen_prologue) {
18720 verbose(env, "bpf verifier is misconfigured\n");
18721 return -EINVAL;
18722 }
36bbef52
DB
18723 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18724 env->prog);
18725 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 18726 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
18727 return -EINVAL;
18728 } else if (cnt) {
8041902d 18729 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
18730 if (!new_prog)
18731 return -ENOMEM;
8041902d 18732
36bbef52 18733 env->prog = new_prog;
3df126f3 18734 delta += cnt - 1;
36bbef52
DB
18735 }
18736 }
18737
9d03ebc7 18738 if (bpf_prog_is_offloaded(env->prog->aux))
9bac3d6d
AS
18739 return 0;
18740
3df126f3 18741 insn = env->prog->insnsi + delta;
36bbef52 18742
9bac3d6d 18743 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983 18744 bpf_convert_ctx_access_t convert_ctx_access;
1f1e864b 18745 u8 mode;
c64b7983 18746
62c7989b
DB
18747 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18748 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18749 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
1f9a1ea8
YS
18750 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18751 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18752 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18753 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
d691f9e8 18754 type = BPF_READ;
2039f26f
DB
18755 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18756 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18757 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18758 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18759 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18760 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18761 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18762 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
d691f9e8 18763 type = BPF_WRITE;
2039f26f 18764 } else {
9bac3d6d 18765 continue;
2039f26f 18766 }
9bac3d6d 18767
af86ca4e 18768 if (type == BPF_WRITE &&
2039f26f 18769 env->insn_aux_data[i + delta].sanitize_stack_spill) {
af86ca4e 18770 struct bpf_insn patch[] = {
af86ca4e 18771 *insn,
2039f26f 18772 BPF_ST_NOSPEC(),
af86ca4e
AS
18773 };
18774
18775 cnt = ARRAY_SIZE(patch);
18776 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18777 if (!new_prog)
18778 return -ENOMEM;
18779
18780 delta += cnt - 1;
18781 env->prog = new_prog;
18782 insn = new_prog->insnsi + i + delta;
18783 continue;
18784 }
18785
6efe152d 18786 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
c64b7983
JS
18787 case PTR_TO_CTX:
18788 if (!ops->convert_ctx_access)
18789 continue;
18790 convert_ctx_access = ops->convert_ctx_access;
18791 break;
18792 case PTR_TO_SOCKET:
46f8bc92 18793 case PTR_TO_SOCK_COMMON:
c64b7983
JS
18794 convert_ctx_access = bpf_sock_convert_ctx_access;
18795 break;
655a51e5
MKL
18796 case PTR_TO_TCP_SOCK:
18797 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18798 break;
fada7fdc
JL
18799 case PTR_TO_XDP_SOCK:
18800 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18801 break;
2a02759e 18802 case PTR_TO_BTF_ID:
6efe152d 18803 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
282de143
KKD
18804 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18805 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18806 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18807 * any faults for loads into such types. BPF_WRITE is disallowed
18808 * for this case.
18809 */
18810 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
27ae7997 18811 if (type == BPF_READ) {
1f9a1ea8
YS
18812 if (BPF_MODE(insn->code) == BPF_MEM)
18813 insn->code = BPF_LDX | BPF_PROBE_MEM |
18814 BPF_SIZE((insn)->code);
18815 else
18816 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18817 BPF_SIZE((insn)->code);
27ae7997 18818 env->prog->aux->num_exentries++;
2a02759e 18819 }
2a02759e 18820 continue;
c64b7983 18821 default:
9bac3d6d 18822 continue;
c64b7983 18823 }
9bac3d6d 18824
31fd8581 18825 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 18826 size = BPF_LDST_BYTES(insn);
1f1e864b 18827 mode = BPF_MODE(insn->code);
31fd8581
YS
18828
18829 /* If the read access is a narrower load of the field,
18830 * convert to a 4/8-byte load, to minimum program type specific
18831 * convert_ctx_access changes. If conversion is successful,
18832 * we will apply proper mask to the result.
18833 */
f96da094 18834 is_narrower_load = size < ctx_field_size;
46f53a65
AI
18835 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18836 off = insn->off;
31fd8581 18837 if (is_narrower_load) {
f96da094
DB
18838 u8 size_code;
18839
18840 if (type == BPF_WRITE) {
61bd5218 18841 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
18842 return -EINVAL;
18843 }
31fd8581 18844
f96da094 18845 size_code = BPF_H;
31fd8581
YS
18846 if (ctx_field_size == 4)
18847 size_code = BPF_W;
18848 else if (ctx_field_size == 8)
18849 size_code = BPF_DW;
f96da094 18850
bc23105c 18851 insn->off = off & ~(size_default - 1);
31fd8581
YS
18852 insn->code = BPF_LDX | BPF_MEM | size_code;
18853 }
f96da094
DB
18854
18855 target_size = 0;
c64b7983
JS
18856 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18857 &target_size);
f96da094
DB
18858 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18859 (ctx_field_size && !target_size)) {
61bd5218 18860 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
18861 return -EINVAL;
18862 }
f96da094
DB
18863
18864 if (is_narrower_load && size < target_size) {
d895a0f1
IL
18865 u8 shift = bpf_ctx_narrow_access_offset(
18866 off, size, size_default) * 8;
d7af7e49
AI
18867 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18868 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18869 return -EINVAL;
18870 }
46f53a65
AI
18871 if (ctx_field_size <= 4) {
18872 if (shift)
18873 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18874 insn->dst_reg,
18875 shift);
31fd8581 18876 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 18877 (1 << size * 8) - 1);
46f53a65
AI
18878 } else {
18879 if (shift)
18880 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18881 insn->dst_reg,
18882 shift);
0613d8ca 18883 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 18884 (1ULL << size * 8) - 1);
46f53a65 18885 }
31fd8581 18886 }
1f1e864b
YS
18887 if (mode == BPF_MEMSX)
18888 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18889 insn->dst_reg, insn->dst_reg,
18890 size * 8, 0);
9bac3d6d 18891
8041902d 18892 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
18893 if (!new_prog)
18894 return -ENOMEM;
18895
3df126f3 18896 delta += cnt - 1;
9bac3d6d
AS
18897
18898 /* keep walking new program and skip insns we just inserted */
18899 env->prog = new_prog;
3df126f3 18900 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
18901 }
18902
18903 return 0;
18904}
18905
1c2a088a
AS
18906static int jit_subprogs(struct bpf_verifier_env *env)
18907{
18908 struct bpf_prog *prog = env->prog, **func, *tmp;
18909 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 18910 struct bpf_map *map_ptr;
7105e828 18911 struct bpf_insn *insn;
1c2a088a 18912 void *old_bpf_func;
c4c0bdc0 18913 int err, num_exentries;
1c2a088a 18914
f910cefa 18915 if (env->subprog_cnt <= 1)
1c2a088a
AS
18916 return 0;
18917
7105e828 18918 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
3990ed4c 18919 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
69c087ba 18920 continue;
69c087ba 18921
c7a89784
DB
18922 /* Upon error here we cannot fall back to interpreter but
18923 * need a hard reject of the program. Thus -EFAULT is
18924 * propagated in any case.
18925 */
1c2a088a
AS
18926 subprog = find_subprog(env, i + insn->imm + 1);
18927 if (subprog < 0) {
18928 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18929 i + insn->imm + 1);
18930 return -EFAULT;
18931 }
18932 /* temporarily remember subprog id inside insn instead of
18933 * aux_data, since next loop will split up all insns into funcs
18934 */
f910cefa 18935 insn->off = subprog;
1c2a088a
AS
18936 /* remember original imm in case JIT fails and fallback
18937 * to interpreter will be needed
18938 */
18939 env->insn_aux_data[i].call_imm = insn->imm;
18940 /* point imm to __bpf_call_base+1 from JITs point of view */
18941 insn->imm = 1;
3990ed4c
MKL
18942 if (bpf_pseudo_func(insn))
18943 /* jit (e.g. x86_64) may emit fewer instructions
18944 * if it learns a u32 imm is the same as a u64 imm.
18945 * Force a non zero here.
18946 */
18947 insn[1].imm = 1;
1c2a088a
AS
18948 }
18949
c454a46b
MKL
18950 err = bpf_prog_alloc_jited_linfo(prog);
18951 if (err)
18952 goto out_undo_insn;
18953
18954 err = -ENOMEM;
6396bb22 18955 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 18956 if (!func)
c7a89784 18957 goto out_undo_insn;
1c2a088a 18958
f910cefa 18959 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 18960 subprog_start = subprog_end;
4cb3d99c 18961 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
18962
18963 len = subprog_end - subprog_start;
fb7dd8bc 18964 /* bpf_prog_run() doesn't call subprogs directly,
492ecee8
AS
18965 * hence main prog stats include the runtime of subprogs.
18966 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 18967 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
18968 */
18969 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
18970 if (!func[i])
18971 goto out_free;
18972 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18973 len * sizeof(struct bpf_insn));
4f74d809 18974 func[i]->type = prog->type;
1c2a088a 18975 func[i]->len = len;
4f74d809
DB
18976 if (bpf_prog_calc_tag(func[i]))
18977 goto out_free;
1c2a088a 18978 func[i]->is_func = 1;
ba64e7d8 18979 func[i]->aux->func_idx = i;
f263a814 18980 /* Below members will be freed only at prog->aux */
ba64e7d8
YS
18981 func[i]->aux->btf = prog->aux->btf;
18982 func[i]->aux->func_info = prog->aux->func_info;
9c7c48d6 18983 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
f263a814
JF
18984 func[i]->aux->poke_tab = prog->aux->poke_tab;
18985 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
ba64e7d8 18986
a748c697 18987 for (j = 0; j < prog->aux->size_poke_tab; j++) {
f263a814 18988 struct bpf_jit_poke_descriptor *poke;
a748c697 18989
f263a814
JF
18990 poke = &prog->aux->poke_tab[j];
18991 if (poke->insn_idx < subprog_end &&
18992 poke->insn_idx >= subprog_start)
18993 poke->aux = func[i]->aux;
a748c697
MF
18994 }
18995
1c2a088a 18996 func[i]->aux->name[0] = 'F';
9c8105bd 18997 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 18998 func[i]->jit_requested = 1;
d2a3b7c5 18999 func[i]->blinding_requested = prog->blinding_requested;
e6ac2450 19000 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
2357672c 19001 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
c454a46b
MKL
19002 func[i]->aux->linfo = prog->aux->linfo;
19003 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19004 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19005 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
19006 num_exentries = 0;
19007 insn = func[i]->insnsi;
19008 for (j = 0; j < func[i]->len; j++, insn++) {
19009 if (BPF_CLASS(insn->code) == BPF_LDX &&
1f9a1ea8
YS
19010 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19011 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
c4c0bdc0
YS
19012 num_exentries++;
19013 }
19014 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 19015 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
f18b03fa
KKD
19016 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19017 if (!i)
19018 func[i]->aux->exception_boundary = env->seen_exception;
1c2a088a
AS
19019 func[i] = bpf_int_jit_compile(func[i]);
19020 if (!func[i]->jited) {
19021 err = -ENOTSUPP;
19022 goto out_free;
19023 }
19024 cond_resched();
19025 }
a748c697 19026
1c2a088a
AS
19027 /* at this point all bpf functions were successfully JITed
19028 * now populate all bpf_calls with correct addresses and
19029 * run last pass of JIT
19030 */
f910cefa 19031 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
19032 insn = func[i]->insnsi;
19033 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba 19034 if (bpf_pseudo_func(insn)) {
3990ed4c 19035 subprog = insn->off;
69c087ba
YS
19036 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19037 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19038 continue;
19039 }
23a2d70c 19040 if (!bpf_pseudo_call(insn))
1c2a088a
AS
19041 continue;
19042 subprog = insn->off;
3d717fad 19043 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
1c2a088a 19044 }
2162fed4
SD
19045
19046 /* we use the aux data to keep a list of the start addresses
19047 * of the JITed images for each function in the program
19048 *
19049 * for some architectures, such as powerpc64, the imm field
19050 * might not be large enough to hold the offset of the start
19051 * address of the callee's JITed image from __bpf_call_base
19052 *
19053 * in such cases, we can lookup the start address of a callee
19054 * by using its subprog id, available from the off field of
19055 * the call instruction, as an index for this list
19056 */
19057 func[i]->aux->func = func;
335d1c5b
KKD
19058 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19059 func[i]->aux->real_func_cnt = env->subprog_cnt;
1c2a088a 19060 }
f910cefa 19061 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
19062 old_bpf_func = func[i]->bpf_func;
19063 tmp = bpf_int_jit_compile(func[i]);
19064 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19065 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 19066 err = -ENOTSUPP;
1c2a088a
AS
19067 goto out_free;
19068 }
19069 cond_resched();
19070 }
19071
19072 /* finally lock prog and jit images for all functions and
0108a4e9
KJ
19073 * populate kallsysm. Begin at the first subprogram, since
19074 * bpf_prog_load will add the kallsyms for the main program.
1c2a088a 19075 */
0108a4e9 19076 for (i = 1; i < env->subprog_cnt; i++) {
1c2a088a
AS
19077 bpf_prog_lock_ro(func[i]);
19078 bpf_prog_kallsyms_add(func[i]);
19079 }
7105e828
DB
19080
19081 /* Last step: make now unused interpreter insns from main
19082 * prog consistent for later dump requests, so they can
19083 * later look the same as if they were interpreted only.
19084 */
19085 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
19086 if (bpf_pseudo_func(insn)) {
19087 insn[0].imm = env->insn_aux_data[i].call_imm;
3990ed4c
MKL
19088 insn[1].imm = insn->off;
19089 insn->off = 0;
69c087ba
YS
19090 continue;
19091 }
23a2d70c 19092 if (!bpf_pseudo_call(insn))
7105e828
DB
19093 continue;
19094 insn->off = env->insn_aux_data[i].call_imm;
19095 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 19096 insn->imm = subprog;
7105e828
DB
19097 }
19098
1c2a088a
AS
19099 prog->jited = 1;
19100 prog->bpf_func = func[0]->bpf_func;
d00c6473 19101 prog->jited_len = func[0]->jited_len;
0108a4e9
KJ
19102 prog->aux->extable = func[0]->aux->extable;
19103 prog->aux->num_exentries = func[0]->aux->num_exentries;
1c2a088a 19104 prog->aux->func = func;
335d1c5b
KKD
19105 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19106 prog->aux->real_func_cnt = env->subprog_cnt;
f18b03fa
KKD
19107 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19108 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
e16301fb 19109 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
19110 return 0;
19111out_free:
f263a814
JF
19112 /* We failed JIT'ing, so at this point we need to unregister poke
19113 * descriptors from subprogs, so that kernel is not attempting to
19114 * patch it anymore as we're freeing the subprog JIT memory.
19115 */
19116 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19117 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19118 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19119 }
19120 /* At this point we're guaranteed that poke descriptors are not
19121 * live anymore. We can just unlink its descriptor table as it's
19122 * released with the main prog.
19123 */
a748c697
MF
19124 for (i = 0; i < env->subprog_cnt; i++) {
19125 if (!func[i])
19126 continue;
f263a814 19127 func[i]->aux->poke_tab = NULL;
a748c697
MF
19128 bpf_jit_free(func[i]);
19129 }
1c2a088a 19130 kfree(func);
c7a89784 19131out_undo_insn:
1c2a088a
AS
19132 /* cleanup main prog to be interpreted */
19133 prog->jit_requested = 0;
d2a3b7c5 19134 prog->blinding_requested = 0;
1c2a088a 19135 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 19136 if (!bpf_pseudo_call(insn))
1c2a088a
AS
19137 continue;
19138 insn->off = 0;
19139 insn->imm = env->insn_aux_data[i].call_imm;
19140 }
e16301fb 19141 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
19142 return err;
19143}
19144
1ea47e01
AS
19145static int fixup_call_args(struct bpf_verifier_env *env)
19146{
19d28fbd 19147#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
19148 struct bpf_prog *prog = env->prog;
19149 struct bpf_insn *insn = prog->insnsi;
e6ac2450 19150 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 19151 int i, depth;
19d28fbd 19152#endif
e4052d06 19153 int err = 0;
1ea47e01 19154
e4052d06 19155 if (env->prog->jit_requested &&
9d03ebc7 19156 !bpf_prog_is_offloaded(env->prog->aux)) {
19d28fbd
DM
19157 err = jit_subprogs(env);
19158 if (err == 0)
1c2a088a 19159 return 0;
c7a89784
DB
19160 if (err == -EFAULT)
19161 return err;
19d28fbd
DM
19162 }
19163#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
19164 if (has_kfunc_call) {
19165 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19166 return -EINVAL;
19167 }
e411901c
MF
19168 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19169 /* When JIT fails the progs with bpf2bpf calls and tail_calls
19170 * have to be rejected, since interpreter doesn't support them yet.
19171 */
19172 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19173 return -EINVAL;
19174 }
1ea47e01 19175 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
19176 if (bpf_pseudo_func(insn)) {
19177 /* When JIT fails the progs with callback calls
19178 * have to be rejected, since interpreter doesn't support them yet.
19179 */
19180 verbose(env, "callbacks are not allowed in non-JITed programs\n");
19181 return -EINVAL;
19182 }
19183
23a2d70c 19184 if (!bpf_pseudo_call(insn))
1ea47e01
AS
19185 continue;
19186 depth = get_callee_stack_depth(env, insn, i);
19187 if (depth < 0)
19188 return depth;
19189 bpf_patch_call_args(insn, depth);
19190 }
19d28fbd
DM
19191 err = 0;
19192#endif
19193 return err;
1ea47e01
AS
19194}
19195
1cf3bfc6
IL
19196/* replace a generic kfunc with a specialized version if necessary */
19197static void specialize_kfunc(struct bpf_verifier_env *env,
19198 u32 func_id, u16 offset, unsigned long *addr)
19199{
19200 struct bpf_prog *prog = env->prog;
19201 bool seen_direct_write;
19202 void *xdp_kfunc;
19203 bool is_rdonly;
19204
19205 if (bpf_dev_bound_kfunc_id(func_id)) {
19206 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19207 if (xdp_kfunc) {
19208 *addr = (unsigned long)xdp_kfunc;
19209 return;
19210 }
19211 /* fallback to default kfunc when not supported by netdev */
19212 }
19213
19214 if (offset)
19215 return;
19216
19217 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19218 seen_direct_write = env->seen_direct_write;
19219 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19220
19221 if (is_rdonly)
19222 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19223
19224 /* restore env->seen_direct_write to its original value, since
19225 * may_access_direct_pkt_data mutates it
19226 */
19227 env->seen_direct_write = seen_direct_write;
19228 }
19229}
19230
d2dcc67d
DM
19231static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19232 u16 struct_meta_reg,
19233 u16 node_offset_reg,
19234 struct bpf_insn *insn,
19235 struct bpf_insn *insn_buf,
19236 int *cnt)
19237{
19238 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19239 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19240
19241 insn_buf[0] = addr[0];
19242 insn_buf[1] = addr[1];
19243 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19244 insn_buf[3] = *insn;
19245 *cnt = 4;
19246}
19247
958cf2e2
KKD
19248static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19249 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
e6ac2450
MKL
19250{
19251 const struct bpf_kfunc_desc *desc;
19252
a5d82727
KKD
19253 if (!insn->imm) {
19254 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19255 return -EINVAL;
19256 }
19257
3d76a4d3
SF
19258 *cnt = 0;
19259
1cf3bfc6
IL
19260 /* insn->imm has the btf func_id. Replace it with an offset relative to
19261 * __bpf_call_base, unless the JIT needs to call functions that are
19262 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
e6ac2450 19263 */
2357672c 19264 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
e6ac2450
MKL
19265 if (!desc) {
19266 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19267 insn->imm);
19268 return -EFAULT;
19269 }
19270
1cf3bfc6
IL
19271 if (!bpf_jit_supports_far_kfunc_call())
19272 insn->imm = BPF_CALL_IMM(desc->addr);
958cf2e2
KKD
19273 if (insn->off)
19274 return 0;
36d8bdf7
YS
19275 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19276 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
958cf2e2
KKD
19277 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19278 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19279 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
e6ac2450 19280
36d8bdf7
YS
19281 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19282 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19283 insn_idx);
19284 return -EFAULT;
19285 }
19286
958cf2e2
KKD
19287 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19288 insn_buf[1] = addr[0];
19289 insn_buf[2] = addr[1];
19290 insn_buf[3] = *insn;
19291 *cnt = 4;
7c50b1cb 19292 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
36d8bdf7 19293 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
7c50b1cb 19294 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
ac9f0605
KKD
19295 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19296 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19297
36d8bdf7
YS
19298 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19299 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19300 insn_idx);
19301 return -EFAULT;
19302 }
19303
f0d991a0
DM
19304 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19305 !kptr_struct_meta) {
19306 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19307 insn_idx);
19308 return -EFAULT;
19309 }
19310
ac9f0605
KKD
19311 insn_buf[0] = addr[0];
19312 insn_buf[1] = addr[1];
19313 insn_buf[2] = *insn;
19314 *cnt = 3;
d2dcc67d
DM
19315 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19316 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19317 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
f0d991a0 19318 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
d2dcc67d
DM
19319 int struct_meta_reg = BPF_REG_3;
19320 int node_offset_reg = BPF_REG_4;
19321
19322 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19323 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19324 struct_meta_reg = BPF_REG_4;
19325 node_offset_reg = BPF_REG_5;
19326 }
19327
f0d991a0
DM
19328 if (!kptr_struct_meta) {
19329 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19330 insn_idx);
19331 return -EFAULT;
19332 }
19333
d2dcc67d
DM
19334 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19335 node_offset_reg, insn, insn_buf, cnt);
a35b9af4
YS
19336 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19337 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
fd264ca0
YS
19338 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19339 *cnt = 1;
958cf2e2 19340 }
e6ac2450
MKL
19341 return 0;
19342}
19343
335d1c5b 19344/* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
f18b03fa 19345static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
335d1c5b
KKD
19346{
19347 struct bpf_subprog_info *info = env->subprog_info;
19348 int cnt = env->subprog_cnt;
19349 struct bpf_prog *prog;
19350
19351 /* We only reserve one slot for hidden subprogs in subprog_info. */
19352 if (env->hidden_subprog_cnt) {
19353 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19354 return -EFAULT;
19355 }
19356 /* We're not patching any existing instruction, just appending the new
19357 * ones for the hidden subprog. Hence all of the adjustment operations
19358 * in bpf_patch_insn_data are no-ops.
19359 */
19360 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19361 if (!prog)
19362 return -ENOMEM;
19363 env->prog = prog;
19364 info[cnt + 1].start = info[cnt].start;
19365 info[cnt].start = prog->len - len + 1;
19366 env->subprog_cnt++;
19367 env->hidden_subprog_cnt++;
19368 return 0;
19369}
19370
e6ac5933
BJ
19371/* Do various post-verification rewrites in a single program pass.
19372 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 19373 */
e6ac5933 19374static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 19375{
79741b3b 19376 struct bpf_prog *prog = env->prog;
f92c1e18 19377 enum bpf_attach_type eatype = prog->expected_attach_type;
9b99edca 19378 enum bpf_prog_type prog_type = resolve_prog_type(prog);
79741b3b 19379 struct bpf_insn *insn = prog->insnsi;
e245c5c6 19380 const struct bpf_func_proto *fn;
79741b3b 19381 const int insn_cnt = prog->len;
09772d92 19382 const struct bpf_map_ops *ops;
c93552c4 19383 struct bpf_insn_aux_data *aux;
81ed18ab
AS
19384 struct bpf_insn insn_buf[16];
19385 struct bpf_prog *new_prog;
19386 struct bpf_map *map_ptr;
d2e4c1e6 19387 int i, ret, cnt, delta = 0;
e245c5c6 19388
f18b03fa
KKD
19389 if (env->seen_exception && !env->exception_callback_subprog) {
19390 struct bpf_insn patch[] = {
19391 env->prog->insnsi[insn_cnt - 1],
a923819f 19392 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
f18b03fa
KKD
19393 BPF_EXIT_INSN(),
19394 };
19395
19396 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19397 if (ret < 0)
19398 return ret;
19399 prog = env->prog;
19400 insn = prog->insnsi;
19401
19402 env->exception_callback_subprog = env->subprog_cnt - 1;
19403 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19404 env->subprog_info[env->exception_callback_subprog].is_cb = true;
19405 env->subprog_info[env->exception_callback_subprog].is_async_cb = true;
19406 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true;
19407 }
19408
79741b3b 19409 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 19410 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
19411 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19412 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19413 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 19414 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 19415 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
19416 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19417 struct bpf_insn *patchlet;
19418 struct bpf_insn chk_and_div[] = {
9b00f1b7 19419 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
19420 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19421 BPF_JNE | BPF_K, insn->src_reg,
19422 0, 2, 0),
f6b1b3bf
DB
19423 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19424 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19425 *insn,
19426 };
e88b2c6e 19427 struct bpf_insn chk_and_mod[] = {
9b00f1b7 19428 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
19429 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19430 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 19431 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 19432 *insn,
9b00f1b7
DB
19433 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19434 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 19435 };
f6b1b3bf 19436
e88b2c6e
DB
19437 patchlet = isdiv ? chk_and_div : chk_and_mod;
19438 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 19439 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
19440
19441 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
19442 if (!new_prog)
19443 return -ENOMEM;
19444
19445 delta += cnt - 1;
19446 env->prog = prog = new_prog;
19447 insn = new_prog->insnsi + i + delta;
19448 continue;
19449 }
19450
e6ac5933 19451 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
19452 if (BPF_CLASS(insn->code) == BPF_LD &&
19453 (BPF_MODE(insn->code) == BPF_ABS ||
19454 BPF_MODE(insn->code) == BPF_IND)) {
19455 cnt = env->ops->gen_ld_abs(insn, insn_buf);
19456 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19457 verbose(env, "bpf verifier is misconfigured\n");
19458 return -EINVAL;
19459 }
19460
19461 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19462 if (!new_prog)
19463 return -ENOMEM;
19464
19465 delta += cnt - 1;
19466 env->prog = prog = new_prog;
19467 insn = new_prog->insnsi + i + delta;
19468 continue;
19469 }
19470
e6ac5933 19471 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
19472 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19473 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19474 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19475 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 19476 struct bpf_insn *patch = &insn_buf[0];
801c6058 19477 bool issrc, isneg, isimm;
979d63d5
DB
19478 u32 off_reg;
19479
19480 aux = &env->insn_aux_data[i + delta];
3612af78
DB
19481 if (!aux->alu_state ||
19482 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
19483 continue;
19484
19485 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19486 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19487 BPF_ALU_SANITIZE_SRC;
801c6058 19488 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
19489
19490 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
19491 if (isimm) {
19492 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19493 } else {
19494 if (isneg)
19495 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19496 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19497 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19498 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19499 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19500 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19501 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19502 }
b9b34ddb
DB
19503 if (!issrc)
19504 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19505 insn->src_reg = BPF_REG_AX;
979d63d5
DB
19506 if (isneg)
19507 insn->code = insn->code == code_add ?
19508 code_sub : code_add;
19509 *patch++ = *insn;
801c6058 19510 if (issrc && isneg && !isimm)
979d63d5
DB
19511 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19512 cnt = patch - insn_buf;
19513
19514 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19515 if (!new_prog)
19516 return -ENOMEM;
19517
19518 delta += cnt - 1;
19519 env->prog = prog = new_prog;
19520 insn = new_prog->insnsi + i + delta;
19521 continue;
19522 }
19523
79741b3b
AS
19524 if (insn->code != (BPF_JMP | BPF_CALL))
19525 continue;
cc8b0b92
AS
19526 if (insn->src_reg == BPF_PSEUDO_CALL)
19527 continue;
e6ac2450 19528 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
958cf2e2 19529 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
e6ac2450
MKL
19530 if (ret)
19531 return ret;
958cf2e2
KKD
19532 if (cnt == 0)
19533 continue;
19534
19535 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19536 if (!new_prog)
19537 return -ENOMEM;
19538
19539 delta += cnt - 1;
19540 env->prog = prog = new_prog;
19541 insn = new_prog->insnsi + i + delta;
e6ac2450
MKL
19542 continue;
19543 }
e245c5c6 19544
79741b3b
AS
19545 if (insn->imm == BPF_FUNC_get_route_realm)
19546 prog->dst_needed = 1;
19547 if (insn->imm == BPF_FUNC_get_prandom_u32)
19548 bpf_user_rnd_init_once();
9802d865
JB
19549 if (insn->imm == BPF_FUNC_override_return)
19550 prog->kprobe_override = 1;
79741b3b 19551 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
19552 /* If we tail call into other programs, we
19553 * cannot make any assumptions since they can
19554 * be replaced dynamically during runtime in
19555 * the program array.
19556 */
19557 prog->cb_access = 1;
e411901c
MF
19558 if (!allow_tail_call_in_subprogs(env))
19559 prog->aux->stack_depth = MAX_BPF_STACK;
19560 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 19561
79741b3b 19562 /* mark bpf_tail_call as different opcode to avoid
8fb33b60 19563 * conditional branch in the interpreter for every normal
79741b3b
AS
19564 * call and to prevent accidental JITing by JIT compiler
19565 * that doesn't support bpf_tail_call yet
e245c5c6 19566 */
79741b3b 19567 insn->imm = 0;
71189fa9 19568 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 19569
c93552c4 19570 aux = &env->insn_aux_data[i + delta];
d2a3b7c5 19571 if (env->bpf_capable && !prog->blinding_requested &&
cc52d914 19572 prog->jit_requested &&
d2e4c1e6
DB
19573 !bpf_map_key_poisoned(aux) &&
19574 !bpf_map_ptr_poisoned(aux) &&
19575 !bpf_map_ptr_unpriv(aux)) {
19576 struct bpf_jit_poke_descriptor desc = {
19577 .reason = BPF_POKE_REASON_TAIL_CALL,
19578 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19579 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 19580 .insn_idx = i + delta,
d2e4c1e6
DB
19581 };
19582
19583 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19584 if (ret < 0) {
19585 verbose(env, "adding tail call poke descriptor failed\n");
19586 return ret;
19587 }
19588
19589 insn->imm = ret + 1;
19590 continue;
19591 }
19592
c93552c4
DB
19593 if (!bpf_map_ptr_unpriv(aux))
19594 continue;
19595
b2157399
AS
19596 /* instead of changing every JIT dealing with tail_call
19597 * emit two extra insns:
19598 * if (index >= max_entries) goto out;
19599 * index &= array->index_mask;
19600 * to avoid out-of-bounds cpu speculation
19601 */
c93552c4 19602 if (bpf_map_ptr_poisoned(aux)) {
40950343 19603 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
19604 return -EINVAL;
19605 }
c93552c4 19606
d2e4c1e6 19607 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
19608 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19609 map_ptr->max_entries, 2);
19610 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19611 container_of(map_ptr,
19612 struct bpf_array,
19613 map)->index_mask);
19614 insn_buf[2] = *insn;
19615 cnt = 3;
19616 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19617 if (!new_prog)
19618 return -ENOMEM;
19619
19620 delta += cnt - 1;
19621 env->prog = prog = new_prog;
19622 insn = new_prog->insnsi + i + delta;
79741b3b
AS
19623 continue;
19624 }
e245c5c6 19625
b00628b1
AS
19626 if (insn->imm == BPF_FUNC_timer_set_callback) {
19627 /* The verifier will process callback_fn as many times as necessary
19628 * with different maps and the register states prepared by
19629 * set_timer_callback_state will be accurate.
19630 *
19631 * The following use case is valid:
19632 * map1 is shared by prog1, prog2, prog3.
19633 * prog1 calls bpf_timer_init for some map1 elements
19634 * prog2 calls bpf_timer_set_callback for some map1 elements.
19635 * Those that were not bpf_timer_init-ed will return -EINVAL.
19636 * prog3 calls bpf_timer_start for some map1 elements.
19637 * Those that were not both bpf_timer_init-ed and
19638 * bpf_timer_set_callback-ed will return -EINVAL.
19639 */
19640 struct bpf_insn ld_addrs[2] = {
19641 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19642 };
19643
19644 insn_buf[0] = ld_addrs[0];
19645 insn_buf[1] = ld_addrs[1];
19646 insn_buf[2] = *insn;
19647 cnt = 3;
19648
19649 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19650 if (!new_prog)
19651 return -ENOMEM;
19652
19653 delta += cnt - 1;
19654 env->prog = prog = new_prog;
19655 insn = new_prog->insnsi + i + delta;
19656 goto patch_call_imm;
19657 }
19658
9bb00b28
YS
19659 if (is_storage_get_function(insn->imm)) {
19660 if (!env->prog->aux->sleepable ||
19661 env->insn_aux_data[i + delta].storage_get_func_atomic)
d56c9fe6 19662 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
9bb00b28
YS
19663 else
19664 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
b00fa38a
JK
19665 insn_buf[1] = *insn;
19666 cnt = 2;
19667
19668 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19669 if (!new_prog)
19670 return -ENOMEM;
19671
19672 delta += cnt - 1;
19673 env->prog = prog = new_prog;
19674 insn = new_prog->insnsi + i + delta;
19675 goto patch_call_imm;
19676 }
19677
01cc55af
YS
19678 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19679 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19680 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19681 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19682 */
19683 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19684 insn_buf[1] = *insn;
19685 cnt = 2;
19686
19687 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19688 if (!new_prog)
19689 return -ENOMEM;
19690
19691 delta += cnt - 1;
19692 env->prog = prog = new_prog;
19693 insn = new_prog->insnsi + i + delta;
19694 goto patch_call_imm;
19695 }
19696
89c63074 19697 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
19698 * and other inlining handlers are currently limited to 64 bit
19699 * only.
89c63074 19700 */
60b58afc 19701 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
19702 (insn->imm == BPF_FUNC_map_lookup_elem ||
19703 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
19704 insn->imm == BPF_FUNC_map_delete_elem ||
19705 insn->imm == BPF_FUNC_map_push_elem ||
19706 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f 19707 insn->imm == BPF_FUNC_map_peek_elem ||
0640c77c 19708 insn->imm == BPF_FUNC_redirect_map ||
07343110
FZ
19709 insn->imm == BPF_FUNC_for_each_map_elem ||
19710 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
c93552c4
DB
19711 aux = &env->insn_aux_data[i + delta];
19712 if (bpf_map_ptr_poisoned(aux))
19713 goto patch_call_imm;
19714
d2e4c1e6 19715 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
19716 ops = map_ptr->ops;
19717 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19718 ops->map_gen_lookup) {
19719 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
19720 if (cnt == -EOPNOTSUPP)
19721 goto patch_map_ops_generic;
19722 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
19723 verbose(env, "bpf verifier is misconfigured\n");
19724 return -EINVAL;
19725 }
81ed18ab 19726
09772d92
DB
19727 new_prog = bpf_patch_insn_data(env, i + delta,
19728 insn_buf, cnt);
19729 if (!new_prog)
19730 return -ENOMEM;
81ed18ab 19731
09772d92
DB
19732 delta += cnt - 1;
19733 env->prog = prog = new_prog;
19734 insn = new_prog->insnsi + i + delta;
19735 continue;
19736 }
81ed18ab 19737
09772d92
DB
19738 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19739 (void *(*)(struct bpf_map *map, void *key))NULL));
19740 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
d7ba4cc9 19741 (long (*)(struct bpf_map *map, void *key))NULL));
09772d92 19742 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
d7ba4cc9 19743 (long (*)(struct bpf_map *map, void *key, void *value,
09772d92 19744 u64 flags))NULL));
84430d42 19745 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
d7ba4cc9 19746 (long (*)(struct bpf_map *map, void *value,
84430d42
DB
19747 u64 flags))NULL));
19748 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
d7ba4cc9 19749 (long (*)(struct bpf_map *map, void *value))NULL));
84430d42 19750 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
d7ba4cc9 19751 (long (*)(struct bpf_map *map, void *value))NULL));
e6a4750f 19752 BUILD_BUG_ON(!__same_type(ops->map_redirect,
d7ba4cc9 19753 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
0640c77c 19754 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
d7ba4cc9 19755 (long (*)(struct bpf_map *map,
0640c77c
AI
19756 bpf_callback_t callback_fn,
19757 void *callback_ctx,
19758 u64 flags))NULL));
07343110
FZ
19759 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19760 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
e6a4750f 19761
4a8f87e6 19762patch_map_ops_generic:
09772d92
DB
19763 switch (insn->imm) {
19764 case BPF_FUNC_map_lookup_elem:
3d717fad 19765 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
09772d92
DB
19766 continue;
19767 case BPF_FUNC_map_update_elem:
3d717fad 19768 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
09772d92
DB
19769 continue;
19770 case BPF_FUNC_map_delete_elem:
3d717fad 19771 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
09772d92 19772 continue;
84430d42 19773 case BPF_FUNC_map_push_elem:
3d717fad 19774 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
84430d42
DB
19775 continue;
19776 case BPF_FUNC_map_pop_elem:
3d717fad 19777 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
84430d42
DB
19778 continue;
19779 case BPF_FUNC_map_peek_elem:
3d717fad 19780 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
84430d42 19781 continue;
e6a4750f 19782 case BPF_FUNC_redirect_map:
3d717fad 19783 insn->imm = BPF_CALL_IMM(ops->map_redirect);
e6a4750f 19784 continue;
0640c77c
AI
19785 case BPF_FUNC_for_each_map_elem:
19786 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
e6a4750f 19787 continue;
07343110
FZ
19788 case BPF_FUNC_map_lookup_percpu_elem:
19789 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19790 continue;
09772d92 19791 }
81ed18ab 19792
09772d92 19793 goto patch_call_imm;
81ed18ab
AS
19794 }
19795
e6ac5933 19796 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
19797 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19798 insn->imm == BPF_FUNC_jiffies64) {
19799 struct bpf_insn ld_jiffies_addr[2] = {
19800 BPF_LD_IMM64(BPF_REG_0,
19801 (unsigned long)&jiffies),
19802 };
19803
19804 insn_buf[0] = ld_jiffies_addr[0];
19805 insn_buf[1] = ld_jiffies_addr[1];
19806 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19807 BPF_REG_0, 0);
19808 cnt = 3;
19809
19810 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19811 cnt);
19812 if (!new_prog)
19813 return -ENOMEM;
19814
19815 delta += cnt - 1;
19816 env->prog = prog = new_prog;
19817 insn = new_prog->insnsi + i + delta;
19818 continue;
19819 }
19820
f92c1e18
JO
19821 /* Implement bpf_get_func_arg inline. */
19822 if (prog_type == BPF_PROG_TYPE_TRACING &&
19823 insn->imm == BPF_FUNC_get_func_arg) {
19824 /* Load nr_args from ctx - 8 */
19825 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19826 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19827 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19828 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19829 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19830 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19831 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19832 insn_buf[7] = BPF_JMP_A(1);
19833 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19834 cnt = 9;
19835
19836 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19837 if (!new_prog)
19838 return -ENOMEM;
19839
19840 delta += cnt - 1;
19841 env->prog = prog = new_prog;
19842 insn = new_prog->insnsi + i + delta;
19843 continue;
19844 }
19845
19846 /* Implement bpf_get_func_ret inline. */
19847 if (prog_type == BPF_PROG_TYPE_TRACING &&
19848 insn->imm == BPF_FUNC_get_func_ret) {
19849 if (eatype == BPF_TRACE_FEXIT ||
19850 eatype == BPF_MODIFY_RETURN) {
19851 /* Load nr_args from ctx - 8 */
19852 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19853 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19854 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19855 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19856 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19857 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19858 cnt = 6;
19859 } else {
19860 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19861 cnt = 1;
19862 }
19863
19864 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19865 if (!new_prog)
19866 return -ENOMEM;
19867
19868 delta += cnt - 1;
19869 env->prog = prog = new_prog;
19870 insn = new_prog->insnsi + i + delta;
19871 continue;
19872 }
19873
19874 /* Implement get_func_arg_cnt inline. */
19875 if (prog_type == BPF_PROG_TYPE_TRACING &&
19876 insn->imm == BPF_FUNC_get_func_arg_cnt) {
19877 /* Load nr_args from ctx - 8 */
19878 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19879
19880 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19881 if (!new_prog)
19882 return -ENOMEM;
19883
19884 env->prog = prog = new_prog;
19885 insn = new_prog->insnsi + i + delta;
19886 continue;
19887 }
19888
f705ec76 19889 /* Implement bpf_get_func_ip inline. */
9b99edca
JO
19890 if (prog_type == BPF_PROG_TYPE_TRACING &&
19891 insn->imm == BPF_FUNC_get_func_ip) {
f92c1e18
JO
19892 /* Load IP address from ctx - 16 */
19893 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
9b99edca
JO
19894
19895 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19896 if (!new_prog)
19897 return -ENOMEM;
19898
19899 env->prog = prog = new_prog;
19900 insn = new_prog->insnsi + i + delta;
19901 continue;
19902 }
19903
81ed18ab 19904patch_call_imm:
5e43f899 19905 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
19906 /* all functions that have prototype and verifier allowed
19907 * programs to call them, must be real in-kernel functions
19908 */
19909 if (!fn->func) {
61bd5218
JK
19910 verbose(env,
19911 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
19912 func_id_name(insn->imm), insn->imm);
19913 return -EFAULT;
e245c5c6 19914 }
79741b3b 19915 insn->imm = fn->func - __bpf_call_base;
e245c5c6 19916 }
e245c5c6 19917
d2e4c1e6
DB
19918 /* Since poke tab is now finalized, publish aux to tracker. */
19919 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19920 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19921 if (!map_ptr->ops->map_poke_track ||
19922 !map_ptr->ops->map_poke_untrack ||
19923 !map_ptr->ops->map_poke_run) {
19924 verbose(env, "bpf verifier is misconfigured\n");
19925 return -EINVAL;
19926 }
19927
19928 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19929 if (ret < 0) {
19930 verbose(env, "tracking tail call prog failed\n");
19931 return ret;
19932 }
19933 }
19934
1cf3bfc6 19935 sort_kfunc_descs_by_imm_off(env->prog);
e6ac2450 19936
79741b3b
AS
19937 return 0;
19938}
e245c5c6 19939
1ade2371
EZ
19940static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19941 int position,
19942 s32 stack_base,
19943 u32 callback_subprogno,
19944 u32 *cnt)
19945{
19946 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19947 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19948 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19949 int reg_loop_max = BPF_REG_6;
19950 int reg_loop_cnt = BPF_REG_7;
19951 int reg_loop_ctx = BPF_REG_8;
19952
19953 struct bpf_prog *new_prog;
19954 u32 callback_start;
19955 u32 call_insn_offset;
19956 s32 callback_offset;
19957
19958 /* This represents an inlined version of bpf_iter.c:bpf_loop,
19959 * be careful to modify this code in sync.
19960 */
19961 struct bpf_insn insn_buf[] = {
19962 /* Return error and jump to the end of the patch if
19963 * expected number of iterations is too big.
19964 */
19965 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19966 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19967 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19968 /* spill R6, R7, R8 to use these as loop vars */
19969 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19970 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19971 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19972 /* initialize loop vars */
19973 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19974 BPF_MOV32_IMM(reg_loop_cnt, 0),
19975 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19976 /* loop header,
19977 * if reg_loop_cnt >= reg_loop_max skip the loop body
19978 */
19979 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19980 /* callback call,
19981 * correct callback offset would be set after patching
19982 */
19983 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19984 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19985 BPF_CALL_REL(0),
19986 /* increment loop counter */
19987 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19988 /* jump to loop header if callback returned 0 */
19989 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19990 /* return value of bpf_loop,
19991 * set R0 to the number of iterations
19992 */
19993 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19994 /* restore original values of R6, R7, R8 */
19995 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19996 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19997 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19998 };
19999
20000 *cnt = ARRAY_SIZE(insn_buf);
20001 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20002 if (!new_prog)
20003 return new_prog;
20004
20005 /* callback start is known only after patching */
20006 callback_start = env->subprog_info[callback_subprogno].start;
20007 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20008 call_insn_offset = position + 12;
20009 callback_offset = callback_start - call_insn_offset - 1;
fb4e3b33 20010 new_prog->insnsi[call_insn_offset].imm = callback_offset;
1ade2371
EZ
20011
20012 return new_prog;
20013}
20014
20015static bool is_bpf_loop_call(struct bpf_insn *insn)
20016{
20017 return insn->code == (BPF_JMP | BPF_CALL) &&
20018 insn->src_reg == 0 &&
20019 insn->imm == BPF_FUNC_loop;
20020}
20021
20022/* For all sub-programs in the program (including main) check
20023 * insn_aux_data to see if there are bpf_loop calls that require
20024 * inlining. If such calls are found the calls are replaced with a
20025 * sequence of instructions produced by `inline_bpf_loop` function and
20026 * subprog stack_depth is increased by the size of 3 registers.
20027 * This stack space is used to spill values of the R6, R7, R8. These
20028 * registers are used to store the loop bound, counter and context
20029 * variables.
20030 */
20031static int optimize_bpf_loop(struct bpf_verifier_env *env)
20032{
20033 struct bpf_subprog_info *subprogs = env->subprog_info;
20034 int i, cur_subprog = 0, cnt, delta = 0;
20035 struct bpf_insn *insn = env->prog->insnsi;
20036 int insn_cnt = env->prog->len;
20037 u16 stack_depth = subprogs[cur_subprog].stack_depth;
20038 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20039 u16 stack_depth_extra = 0;
20040
20041 for (i = 0; i < insn_cnt; i++, insn++) {
20042 struct bpf_loop_inline_state *inline_state =
20043 &env->insn_aux_data[i + delta].loop_inline_state;
20044
20045 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20046 struct bpf_prog *new_prog;
20047
20048 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20049 new_prog = inline_bpf_loop(env,
20050 i + delta,
20051 -(stack_depth + stack_depth_extra),
20052 inline_state->callback_subprogno,
20053 &cnt);
20054 if (!new_prog)
20055 return -ENOMEM;
20056
20057 delta += cnt - 1;
20058 env->prog = new_prog;
20059 insn = new_prog->insnsi + i + delta;
20060 }
20061
20062 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20063 subprogs[cur_subprog].stack_depth += stack_depth_extra;
20064 cur_subprog++;
20065 stack_depth = subprogs[cur_subprog].stack_depth;
20066 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20067 stack_depth_extra = 0;
20068 }
20069 }
20070
20071 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20072
20073 return 0;
20074}
20075
58e2af8b 20076static void free_states(struct bpf_verifier_env *env)
f1bca824 20077{
58e2af8b 20078 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
20079 int i;
20080
9f4686c4
AS
20081 sl = env->free_list;
20082 while (sl) {
20083 sln = sl->next;
20084 free_verifier_state(&sl->state, false);
20085 kfree(sl);
20086 sl = sln;
20087 }
51c39bb1 20088 env->free_list = NULL;
9f4686c4 20089
f1bca824
AS
20090 if (!env->explored_states)
20091 return;
20092
dc2a4ebc 20093 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
20094 sl = env->explored_states[i];
20095
a8f500af
AS
20096 while (sl) {
20097 sln = sl->next;
20098 free_verifier_state(&sl->state, false);
20099 kfree(sl);
20100 sl = sln;
20101 }
51c39bb1 20102 env->explored_states[i] = NULL;
f1bca824 20103 }
51c39bb1 20104}
f1bca824 20105
b9ae0c9d 20106static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb)
51c39bb1 20107{
6f8a57cc 20108 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
20109 struct bpf_verifier_state *state;
20110 struct bpf_reg_state *regs;
20111 int ret, i;
20112
20113 env->prev_linfo = NULL;
20114 env->pass_cnt++;
20115
20116 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20117 if (!state)
20118 return -ENOMEM;
20119 state->curframe = 0;
20120 state->speculative = false;
20121 state->branches = 1;
20122 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20123 if (!state->frame[0]) {
20124 kfree(state);
20125 return -ENOMEM;
20126 }
20127 env->cur_state = state;
20128 init_func_state(env, state->frame[0],
20129 BPF_MAIN_FUNC /* callsite */,
20130 0 /* frameno */,
20131 subprog);
be2ef816
AN
20132 state->first_insn_idx = env->subprog_info[subprog].start;
20133 state->last_insn_idx = -1;
51c39bb1
AS
20134
20135 regs = state->frame[state->curframe]->regs;
be8704ff 20136 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
b9ae0c9d 20137 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb);
51c39bb1
AS
20138 if (ret)
20139 goto out;
20140 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
20141 if (regs[i].type == PTR_TO_CTX)
20142 mark_reg_known_zero(env, regs, i);
20143 else if (regs[i].type == SCALAR_VALUE)
20144 mark_reg_unknown(env, regs, i);
cf9f2f8d 20145 else if (base_type(regs[i].type) == PTR_TO_MEM) {
e5069b9c
DB
20146 const u32 mem_size = regs[i].mem_size;
20147
20148 mark_reg_known_zero(env, regs, i);
20149 regs[i].mem_size = mem_size;
20150 regs[i].id = ++env->id_gen;
20151 }
51c39bb1 20152 }
b9ae0c9d
KKD
20153 if (is_ex_cb) {
20154 state->frame[0]->in_exception_callback_fn = true;
20155 env->subprog_info[subprog].is_cb = true;
20156 env->subprog_info[subprog].is_async_cb = true;
20157 env->subprog_info[subprog].is_exception_cb = true;
20158 }
51c39bb1
AS
20159 } else {
20160 /* 1st arg to a function */
20161 regs[BPF_REG_1].type = PTR_TO_CTX;
20162 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 20163 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
20164 if (ret == -EFAULT)
20165 /* unlikely verifier bug. abort.
20166 * ret == 0 and ret < 0 are sadly acceptable for
20167 * main() function due to backward compatibility.
20168 * Like socket filter program may be written as:
20169 * int bpf_prog(struct pt_regs *ctx)
20170 * and never dereference that ctx in the program.
20171 * 'struct pt_regs' is a type mismatch for socket
20172 * filter that should be using 'struct __sk_buff'.
20173 */
20174 goto out;
20175 }
20176
20177 ret = do_check(env);
20178out:
f59bbfc2
AS
20179 /* check for NULL is necessary, since cur_state can be freed inside
20180 * do_check() under memory pressure.
20181 */
20182 if (env->cur_state) {
20183 free_verifier_state(env->cur_state, true);
20184 env->cur_state = NULL;
20185 }
6f8a57cc
AN
20186 while (!pop_stack(env, NULL, NULL, false));
20187 if (!ret && pop_log)
20188 bpf_vlog_reset(&env->log, 0);
51c39bb1 20189 free_states(env);
51c39bb1
AS
20190 return ret;
20191}
20192
20193/* Verify all global functions in a BPF program one by one based on their BTF.
20194 * All global functions must pass verification. Otherwise the whole program is rejected.
20195 * Consider:
20196 * int bar(int);
20197 * int foo(int f)
20198 * {
20199 * return bar(f);
20200 * }
20201 * int bar(int b)
20202 * {
20203 * ...
20204 * }
20205 * foo() will be verified first for R1=any_scalar_value. During verification it
20206 * will be assumed that bar() already verified successfully and call to bar()
20207 * from foo() will be checked for type match only. Later bar() will be verified
20208 * independently to check that it's safe for R1=any_scalar_value.
20209 */
20210static int do_check_subprogs(struct bpf_verifier_env *env)
20211{
20212 struct bpf_prog_aux *aux = env->prog->aux;
20213 int i, ret;
20214
20215 if (!aux->func_info)
20216 return 0;
20217
20218 for (i = 1; i < env->subprog_cnt; i++) {
20219 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
20220 continue;
20221 env->insn_idx = env->subprog_info[i].start;
20222 WARN_ON_ONCE(env->insn_idx == 0);
b9ae0c9d 20223 ret = do_check_common(env, i, env->exception_callback_subprog == i);
51c39bb1
AS
20224 if (ret) {
20225 return ret;
20226 } else if (env->log.level & BPF_LOG_LEVEL) {
20227 verbose(env,
20228 "Func#%d is safe for any args that match its prototype\n",
20229 i);
20230 }
20231 }
20232 return 0;
20233}
20234
20235static int do_check_main(struct bpf_verifier_env *env)
20236{
20237 int ret;
20238
20239 env->insn_idx = 0;
b9ae0c9d 20240 ret = do_check_common(env, 0, false);
51c39bb1
AS
20241 if (!ret)
20242 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20243 return ret;
20244}
20245
20246
06ee7115
AS
20247static void print_verification_stats(struct bpf_verifier_env *env)
20248{
20249 int i;
20250
20251 if (env->log.level & BPF_LOG_STATS) {
20252 verbose(env, "verification time %lld usec\n",
20253 div_u64(env->verification_time, 1000));
20254 verbose(env, "stack depth ");
20255 for (i = 0; i < env->subprog_cnt; i++) {
20256 u32 depth = env->subprog_info[i].stack_depth;
20257
20258 verbose(env, "%d", depth);
20259 if (i + 1 < env->subprog_cnt)
20260 verbose(env, "+");
20261 }
20262 verbose(env, "\n");
20263 }
20264 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20265 "total_states %d peak_states %d mark_read %d\n",
20266 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20267 env->max_states_per_insn, env->total_states,
20268 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
20269}
20270
27ae7997
MKL
20271static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20272{
20273 const struct btf_type *t, *func_proto;
20274 const struct bpf_struct_ops *st_ops;
20275 const struct btf_member *member;
20276 struct bpf_prog *prog = env->prog;
20277 u32 btf_id, member_idx;
20278 const char *mname;
20279
12aa8a94
THJ
20280 if (!prog->gpl_compatible) {
20281 verbose(env, "struct ops programs must have a GPL compatible license\n");
20282 return -EINVAL;
20283 }
20284
27ae7997
MKL
20285 btf_id = prog->aux->attach_btf_id;
20286 st_ops = bpf_struct_ops_find(btf_id);
20287 if (!st_ops) {
20288 verbose(env, "attach_btf_id %u is not a supported struct\n",
20289 btf_id);
20290 return -ENOTSUPP;
20291 }
20292
20293 t = st_ops->type;
20294 member_idx = prog->expected_attach_type;
20295 if (member_idx >= btf_type_vlen(t)) {
20296 verbose(env, "attach to invalid member idx %u of struct %s\n",
20297 member_idx, st_ops->name);
20298 return -EINVAL;
20299 }
20300
20301 member = &btf_type_member(t)[member_idx];
20302 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20303 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20304 NULL);
20305 if (!func_proto) {
20306 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20307 mname, member_idx, st_ops->name);
20308 return -EINVAL;
20309 }
20310
20311 if (st_ops->check_member) {
51a52a29 20312 int err = st_ops->check_member(t, member, prog);
27ae7997
MKL
20313
20314 if (err) {
20315 verbose(env, "attach to unsupported member %s of struct %s\n",
20316 mname, st_ops->name);
20317 return err;
20318 }
20319 }
20320
20321 prog->aux->attach_func_proto = func_proto;
20322 prog->aux->attach_func_name = mname;
20323 env->ops = st_ops->verifier_ops;
20324
20325 return 0;
20326}
6ba43b76
KS
20327#define SECURITY_PREFIX "security_"
20328
f7b12b6f 20329static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 20330{
69191754 20331 if (within_error_injection_list(addr) ||
f7b12b6f 20332 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 20333 return 0;
6ba43b76 20334
6ba43b76
KS
20335 return -EINVAL;
20336}
27ae7997 20337
1e6c62a8
AS
20338/* list of non-sleepable functions that are otherwise on
20339 * ALLOW_ERROR_INJECTION list
20340 */
20341BTF_SET_START(btf_non_sleepable_error_inject)
20342/* Three functions below can be called from sleepable and non-sleepable context.
20343 * Assume non-sleepable from bpf safety point of view.
20344 */
9dd3d069 20345BTF_ID(func, __filemap_add_folio)
1e6c62a8
AS
20346BTF_ID(func, should_fail_alloc_page)
20347BTF_ID(func, should_failslab)
20348BTF_SET_END(btf_non_sleepable_error_inject)
20349
20350static int check_non_sleepable_error_inject(u32 btf_id)
20351{
20352 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20353}
20354
f7b12b6f
THJ
20355int bpf_check_attach_target(struct bpf_verifier_log *log,
20356 const struct bpf_prog *prog,
20357 const struct bpf_prog *tgt_prog,
20358 u32 btf_id,
20359 struct bpf_attach_target_info *tgt_info)
38207291 20360{
be8704ff 20361 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 20362 const char prefix[] = "btf_trace_";
5b92a28a 20363 int ret = 0, subprog = -1, i;
38207291 20364 const struct btf_type *t;
5b92a28a 20365 bool conservative = true;
38207291 20366 const char *tname;
5b92a28a 20367 struct btf *btf;
f7b12b6f 20368 long addr = 0;
31bf1dbc 20369 struct module *mod = NULL;
38207291 20370
f1b9509c 20371 if (!btf_id) {
efc68158 20372 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
20373 return -EINVAL;
20374 }
22dc4a0f 20375 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 20376 if (!btf) {
efc68158 20377 bpf_log(log,
5b92a28a
AS
20378 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20379 return -EINVAL;
20380 }
20381 t = btf_type_by_id(btf, btf_id);
f1b9509c 20382 if (!t) {
efc68158 20383 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
20384 return -EINVAL;
20385 }
5b92a28a 20386 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 20387 if (!tname) {
efc68158 20388 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
20389 return -EINVAL;
20390 }
5b92a28a
AS
20391 if (tgt_prog) {
20392 struct bpf_prog_aux *aux = tgt_prog->aux;
20393
fd7c211d
THJ
20394 if (bpf_prog_is_dev_bound(prog->aux) &&
20395 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20396 bpf_log(log, "Target program bound device mismatch");
3d76a4d3
SF
20397 return -EINVAL;
20398 }
20399
5b92a28a
AS
20400 for (i = 0; i < aux->func_info_cnt; i++)
20401 if (aux->func_info[i].type_id == btf_id) {
20402 subprog = i;
20403 break;
20404 }
20405 if (subprog == -1) {
efc68158 20406 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
20407 return -EINVAL;
20408 }
fd548e1a
KKD
20409 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20410 bpf_log(log,
20411 "%s programs cannot attach to exception callback\n",
20412 prog_extension ? "Extension" : "FENTRY/FEXIT");
20413 return -EINVAL;
20414 }
5b92a28a 20415 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
20416 if (prog_extension) {
20417 if (conservative) {
efc68158 20418 bpf_log(log,
be8704ff
AS
20419 "Cannot replace static functions\n");
20420 return -EINVAL;
20421 }
20422 if (!prog->jit_requested) {
efc68158 20423 bpf_log(log,
be8704ff
AS
20424 "Extension programs should be JITed\n");
20425 return -EINVAL;
20426 }
be8704ff
AS
20427 }
20428 if (!tgt_prog->jited) {
efc68158 20429 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
20430 return -EINVAL;
20431 }
20432 if (tgt_prog->type == prog->type) {
20433 /* Cannot fentry/fexit another fentry/fexit program.
20434 * Cannot attach program extension to another extension.
20435 * It's ok to attach fentry/fexit to extension program.
20436 */
efc68158 20437 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
20438 return -EINVAL;
20439 }
20440 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20441 prog_extension &&
20442 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20443 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20444 /* Program extensions can extend all program types
20445 * except fentry/fexit. The reason is the following.
20446 * The fentry/fexit programs are used for performance
20447 * analysis, stats and can be attached to any program
20448 * type except themselves. When extension program is
20449 * replacing XDP function it is necessary to allow
20450 * performance analysis of all functions. Both original
20451 * XDP program and its program extension. Hence
20452 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
20453 * allowed. If extending of fentry/fexit was allowed it
20454 * would be possible to create long call chain
20455 * fentry->extension->fentry->extension beyond
20456 * reasonable stack size. Hence extending fentry is not
20457 * allowed.
20458 */
efc68158 20459 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
20460 return -EINVAL;
20461 }
5b92a28a 20462 } else {
be8704ff 20463 if (prog_extension) {
efc68158 20464 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
20465 return -EINVAL;
20466 }
5b92a28a 20467 }
f1b9509c
AS
20468
20469 switch (prog->expected_attach_type) {
20470 case BPF_TRACE_RAW_TP:
5b92a28a 20471 if (tgt_prog) {
efc68158 20472 bpf_log(log,
5b92a28a
AS
20473 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20474 return -EINVAL;
20475 }
38207291 20476 if (!btf_type_is_typedef(t)) {
efc68158 20477 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
20478 btf_id);
20479 return -EINVAL;
20480 }
f1b9509c 20481 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 20482 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
20483 btf_id, tname);
20484 return -EINVAL;
20485 }
20486 tname += sizeof(prefix) - 1;
5b92a28a 20487 t = btf_type_by_id(btf, t->type);
38207291
MKL
20488 if (!btf_type_is_ptr(t))
20489 /* should never happen in valid vmlinux build */
20490 return -EINVAL;
5b92a28a 20491 t = btf_type_by_id(btf, t->type);
38207291
MKL
20492 if (!btf_type_is_func_proto(t))
20493 /* should never happen in valid vmlinux build */
20494 return -EINVAL;
20495
f7b12b6f 20496 break;
15d83c4d
YS
20497 case BPF_TRACE_ITER:
20498 if (!btf_type_is_func(t)) {
efc68158 20499 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
20500 btf_id);
20501 return -EINVAL;
20502 }
20503 t = btf_type_by_id(btf, t->type);
20504 if (!btf_type_is_func_proto(t))
20505 return -EINVAL;
f7b12b6f
THJ
20506 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20507 if (ret)
20508 return ret;
20509 break;
be8704ff
AS
20510 default:
20511 if (!prog_extension)
20512 return -EINVAL;
df561f66 20513 fallthrough;
ae240823 20514 case BPF_MODIFY_RETURN:
9e4e01df 20515 case BPF_LSM_MAC:
69fd337a 20516 case BPF_LSM_CGROUP:
fec56f58
AS
20517 case BPF_TRACE_FENTRY:
20518 case BPF_TRACE_FEXIT:
20519 if (!btf_type_is_func(t)) {
efc68158 20520 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
20521 btf_id);
20522 return -EINVAL;
20523 }
be8704ff 20524 if (prog_extension &&
efc68158 20525 btf_check_type_match(log, prog, btf, t))
be8704ff 20526 return -EINVAL;
5b92a28a 20527 t = btf_type_by_id(btf, t->type);
fec56f58
AS
20528 if (!btf_type_is_func_proto(t))
20529 return -EINVAL;
f7b12b6f 20530
4a1e7c0c
THJ
20531 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20532 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20533 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20534 return -EINVAL;
20535
f7b12b6f 20536 if (tgt_prog && conservative)
5b92a28a 20537 t = NULL;
f7b12b6f
THJ
20538
20539 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 20540 if (ret < 0)
f7b12b6f
THJ
20541 return ret;
20542
5b92a28a 20543 if (tgt_prog) {
e9eeec58
YS
20544 if (subprog == 0)
20545 addr = (long) tgt_prog->bpf_func;
20546 else
20547 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a 20548 } else {
31bf1dbc
VM
20549 if (btf_is_module(btf)) {
20550 mod = btf_try_get_module(btf);
20551 if (mod)
20552 addr = find_kallsyms_symbol_value(mod, tname);
20553 else
20554 addr = 0;
20555 } else {
20556 addr = kallsyms_lookup_name(tname);
20557 }
5b92a28a 20558 if (!addr) {
31bf1dbc 20559 module_put(mod);
efc68158 20560 bpf_log(log,
5b92a28a
AS
20561 "The address of function %s cannot be found\n",
20562 tname);
f7b12b6f 20563 return -ENOENT;
5b92a28a 20564 }
fec56f58 20565 }
18644cec 20566
1e6c62a8
AS
20567 if (prog->aux->sleepable) {
20568 ret = -EINVAL;
20569 switch (prog->type) {
20570 case BPF_PROG_TYPE_TRACING:
5b481aca
BT
20571
20572 /* fentry/fexit/fmod_ret progs can be sleepable if they are
1e6c62a8
AS
20573 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20574 */
20575 if (!check_non_sleepable_error_inject(btf_id) &&
20576 within_error_injection_list(addr))
20577 ret = 0;
5b481aca
BT
20578 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20579 * in the fmodret id set with the KF_SLEEPABLE flag.
20580 */
20581 else {
e924e80e
AG
20582 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20583 prog);
5b481aca
BT
20584
20585 if (flags && (*flags & KF_SLEEPABLE))
20586 ret = 0;
20587 }
1e6c62a8
AS
20588 break;
20589 case BPF_PROG_TYPE_LSM:
20590 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20591 * Only some of them are sleepable.
20592 */
423f1610 20593 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
20594 ret = 0;
20595 break;
20596 default:
20597 break;
20598 }
f7b12b6f 20599 if (ret) {
31bf1dbc 20600 module_put(mod);
f7b12b6f
THJ
20601 bpf_log(log, "%s is not sleepable\n", tname);
20602 return ret;
20603 }
1e6c62a8 20604 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 20605 if (tgt_prog) {
31bf1dbc 20606 module_put(mod);
efc68158 20607 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
20608 return -EINVAL;
20609 }
5b481aca 20610 ret = -EINVAL;
e924e80e 20611 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
5b481aca
BT
20612 !check_attach_modify_return(addr, tname))
20613 ret = 0;
f7b12b6f 20614 if (ret) {
31bf1dbc 20615 module_put(mod);
f7b12b6f
THJ
20616 bpf_log(log, "%s() is not modifiable\n", tname);
20617 return ret;
1af9270e 20618 }
18644cec 20619 }
f7b12b6f
THJ
20620
20621 break;
20622 }
20623 tgt_info->tgt_addr = addr;
20624 tgt_info->tgt_name = tname;
20625 tgt_info->tgt_type = t;
31bf1dbc 20626 tgt_info->tgt_mod = mod;
f7b12b6f
THJ
20627 return 0;
20628}
20629
35e3815f
JO
20630BTF_SET_START(btf_id_deny)
20631BTF_ID_UNUSED
20632#ifdef CONFIG_SMP
20633BTF_ID(func, migrate_disable)
20634BTF_ID(func, migrate_enable)
20635#endif
20636#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20637BTF_ID(func, rcu_read_unlock_strict)
20638#endif
c11bd046
Y
20639#if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20640BTF_ID(func, preempt_count_add)
20641BTF_ID(func, preempt_count_sub)
20642#endif
a0c109dc
YS
20643#ifdef CONFIG_PREEMPT_RCU
20644BTF_ID(func, __rcu_read_lock)
20645BTF_ID(func, __rcu_read_unlock)
20646#endif
35e3815f
JO
20647BTF_SET_END(btf_id_deny)
20648
700e6f85
JO
20649static bool can_be_sleepable(struct bpf_prog *prog)
20650{
20651 if (prog->type == BPF_PROG_TYPE_TRACING) {
20652 switch (prog->expected_attach_type) {
20653 case BPF_TRACE_FENTRY:
20654 case BPF_TRACE_FEXIT:
20655 case BPF_MODIFY_RETURN:
20656 case BPF_TRACE_ITER:
20657 return true;
20658 default:
20659 return false;
20660 }
20661 }
20662 return prog->type == BPF_PROG_TYPE_LSM ||
1e12d3ef
DV
20663 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20664 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
700e6f85
JO
20665}
20666
f7b12b6f
THJ
20667static int check_attach_btf_id(struct bpf_verifier_env *env)
20668{
20669 struct bpf_prog *prog = env->prog;
3aac1ead 20670 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
20671 struct bpf_attach_target_info tgt_info = {};
20672 u32 btf_id = prog->aux->attach_btf_id;
20673 struct bpf_trampoline *tr;
20674 int ret;
20675 u64 key;
20676
79a7f8bd
AS
20677 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20678 if (prog->aux->sleepable)
20679 /* attach_btf_id checked to be zero already */
20680 return 0;
20681 verbose(env, "Syscall programs can only be sleepable\n");
20682 return -EINVAL;
20683 }
20684
700e6f85 20685 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
1e12d3ef 20686 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
f7b12b6f
THJ
20687 return -EINVAL;
20688 }
20689
20690 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20691 return check_struct_ops_btf_id(env);
20692
20693 if (prog->type != BPF_PROG_TYPE_TRACING &&
20694 prog->type != BPF_PROG_TYPE_LSM &&
20695 prog->type != BPF_PROG_TYPE_EXT)
20696 return 0;
20697
20698 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20699 if (ret)
fec56f58 20700 return ret;
f7b12b6f
THJ
20701
20702 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
20703 /* to make freplace equivalent to their targets, they need to
20704 * inherit env->ops and expected_attach_type for the rest of the
20705 * verification
20706 */
f7b12b6f
THJ
20707 env->ops = bpf_verifier_ops[tgt_prog->type];
20708 prog->expected_attach_type = tgt_prog->expected_attach_type;
20709 }
20710
20711 /* store info about the attachment target that will be used later */
20712 prog->aux->attach_func_proto = tgt_info.tgt_type;
20713 prog->aux->attach_func_name = tgt_info.tgt_name;
31bf1dbc 20714 prog->aux->mod = tgt_info.tgt_mod;
f7b12b6f 20715
4a1e7c0c
THJ
20716 if (tgt_prog) {
20717 prog->aux->saved_dst_prog_type = tgt_prog->type;
20718 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20719 }
20720
f7b12b6f
THJ
20721 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20722 prog->aux->attach_btf_trace = true;
20723 return 0;
20724 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20725 if (!bpf_iter_prog_supported(prog))
20726 return -EINVAL;
20727 return 0;
20728 }
20729
20730 if (prog->type == BPF_PROG_TYPE_LSM) {
20731 ret = bpf_lsm_verify_prog(&env->log, prog);
20732 if (ret < 0)
20733 return ret;
35e3815f
JO
20734 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20735 btf_id_set_contains(&btf_id_deny, btf_id)) {
20736 return -EINVAL;
38207291 20737 }
f7b12b6f 20738
22dc4a0f 20739 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
20740 tr = bpf_trampoline_get(key, &tgt_info);
20741 if (!tr)
20742 return -ENOMEM;
20743
2b5dcb31
LH
20744 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20745 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20746
3aac1ead 20747 prog->aux->dst_trampoline = tr;
f7b12b6f 20748 return 0;
38207291
MKL
20749}
20750
76654e67
AM
20751struct btf *bpf_get_btf_vmlinux(void)
20752{
20753 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20754 mutex_lock(&bpf_verifier_lock);
20755 if (!btf_vmlinux)
20756 btf_vmlinux = btf_parse_vmlinux();
20757 mutex_unlock(&bpf_verifier_lock);
20758 }
20759 return btf_vmlinux;
20760}
20761
47a71c1f 20762int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
51580e79 20763{
06ee7115 20764 u64 start_time = ktime_get_ns();
58e2af8b 20765 struct bpf_verifier_env *env;
bdcab414
AN
20766 int i, len, ret = -EINVAL, err;
20767 u32 log_true_size;
e2ae4ca2 20768 bool is_priv;
51580e79 20769
eba0c929
AB
20770 /* no program is valid */
20771 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20772 return -EINVAL;
20773
58e2af8b 20774 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
20775 * allocate/free it every time bpf_check() is called
20776 */
58e2af8b 20777 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
20778 if (!env)
20779 return -ENOMEM;
20780
407958a0
AN
20781 env->bt.env = env;
20782
9e4c24e7 20783 len = (*prog)->len;
fad953ce 20784 env->insn_aux_data =
9e4c24e7 20785 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
20786 ret = -ENOMEM;
20787 if (!env->insn_aux_data)
20788 goto err_free_env;
9e4c24e7
JK
20789 for (i = 0; i < len; i++)
20790 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 20791 env->prog = *prog;
00176a34 20792 env->ops = bpf_verifier_ops[env->prog->type];
387544bf 20793 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
2c78ee89 20794 is_priv = bpf_capable();
0246e64d 20795
76654e67 20796 bpf_get_btf_vmlinux();
8580ac94 20797
cbd35700 20798 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
20799 if (!is_priv)
20800 mutex_lock(&bpf_verifier_lock);
cbd35700 20801
bdcab414
AN
20802 /* user could have requested verbose verifier output
20803 * and supplied buffer to store the verification trace
20804 */
20805 ret = bpf_vlog_init(&env->log, attr->log_level,
20806 (char __user *) (unsigned long) attr->log_buf,
20807 attr->log_size);
20808 if (ret)
20809 goto err_unlock;
1ad2f583 20810
0f55f9ed
CL
20811 mark_verifier_state_clean(env);
20812
8580ac94
AS
20813 if (IS_ERR(btf_vmlinux)) {
20814 /* Either gcc or pahole or kernel are broken. */
20815 verbose(env, "in-kernel BTF is malformed\n");
20816 ret = PTR_ERR(btf_vmlinux);
38207291 20817 goto skip_full_check;
8580ac94
AS
20818 }
20819
1ad2f583
DB
20820 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20821 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 20822 env->strict_alignment = true;
e9ee9efc
DM
20823 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20824 env->strict_alignment = false;
cbd35700 20825
2c78ee89 20826 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 20827 env->allow_uninit_stack = bpf_allow_uninit_stack();
2c78ee89
AS
20828 env->bypass_spec_v1 = bpf_bypass_spec_v1();
20829 env->bypass_spec_v4 = bpf_bypass_spec_v4();
20830 env->bpf_capable = bpf_capable();
e2ae4ca2 20831
10d274e8
AS
20832 if (is_priv)
20833 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20834
dc2a4ebc 20835 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 20836 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
20837 GFP_USER);
20838 ret = -ENOMEM;
20839 if (!env->explored_states)
20840 goto skip_full_check;
20841
aaa619eb
KKD
20842 ret = check_btf_info_early(env, attr, uattr);
20843 if (ret < 0)
20844 goto skip_full_check;
20845
e6ac2450
MKL
20846 ret = add_subprog_and_kfunc(env);
20847 if (ret < 0)
20848 goto skip_full_check;
20849
d9762e84 20850 ret = check_subprogs(env);
475fb78f
AS
20851 if (ret < 0)
20852 goto skip_full_check;
20853
c454a46b 20854 ret = check_btf_info(env, attr, uattr);
838e9690
YS
20855 if (ret < 0)
20856 goto skip_full_check;
20857
be8704ff
AS
20858 ret = check_attach_btf_id(env);
20859 if (ret)
20860 goto skip_full_check;
20861
4976b718
HL
20862 ret = resolve_pseudo_ldimm64(env);
20863 if (ret < 0)
20864 goto skip_full_check;
20865
9d03ebc7 20866 if (bpf_prog_is_offloaded(env->prog->aux)) {
ceb11679
YZ
20867 ret = bpf_prog_offload_verifier_prep(env->prog);
20868 if (ret)
20869 goto skip_full_check;
20870 }
20871
d9762e84
MKL
20872 ret = check_cfg(env);
20873 if (ret < 0)
20874 goto skip_full_check;
20875
51c39bb1
AS
20876 ret = do_check_subprogs(env);
20877 ret = ret ?: do_check_main(env);
cbd35700 20878
9d03ebc7 20879 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
c941ce9c
QM
20880 ret = bpf_prog_offload_finalize(env);
20881
0246e64d 20882skip_full_check:
51c39bb1 20883 kvfree(env->explored_states);
0246e64d 20884
c131187d 20885 if (ret == 0)
9b38c405 20886 ret = check_max_stack_depth(env);
c131187d 20887
9b38c405 20888 /* instruction rewrites happen after this point */
1ade2371
EZ
20889 if (ret == 0)
20890 ret = optimize_bpf_loop(env);
20891
e2ae4ca2
JK
20892 if (is_priv) {
20893 if (ret == 0)
20894 opt_hard_wire_dead_code_branches(env);
52875a04
JK
20895 if (ret == 0)
20896 ret = opt_remove_dead_code(env);
a1b14abc
JK
20897 if (ret == 0)
20898 ret = opt_remove_nops(env);
52875a04
JK
20899 } else {
20900 if (ret == 0)
20901 sanitize_dead_code(env);
e2ae4ca2
JK
20902 }
20903
9bac3d6d
AS
20904 if (ret == 0)
20905 /* program is valid, convert *(u32*)(ctx + off) accesses */
20906 ret = convert_ctx_accesses(env);
20907
e245c5c6 20908 if (ret == 0)
e6ac5933 20909 ret = do_misc_fixups(env);
e245c5c6 20910
a4b1d3c1
JW
20911 /* do 32-bit optimization after insn patching has done so those patched
20912 * insns could be handled correctly.
20913 */
9d03ebc7 20914 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
d6c2308c
JW
20915 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20916 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20917 : false;
a4b1d3c1
JW
20918 }
20919
1ea47e01
AS
20920 if (ret == 0)
20921 ret = fixup_call_args(env);
20922
06ee7115
AS
20923 env->verification_time = ktime_get_ns() - start_time;
20924 print_verification_stats(env);
aba64c7d 20925 env->prog->aux->verified_insns = env->insn_processed;
06ee7115 20926
bdcab414
AN
20927 /* preserve original error even if log finalization is successful */
20928 err = bpf_vlog_finalize(&env->log, &log_true_size);
20929 if (err)
20930 ret = err;
20931
47a71c1f
AN
20932 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20933 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
bdcab414 20934 &log_true_size, sizeof(log_true_size))) {
47a71c1f
AN
20935 ret = -EFAULT;
20936 goto err_release_maps;
20937 }
cbd35700 20938
541c3bad
AN
20939 if (ret)
20940 goto err_release_maps;
20941
20942 if (env->used_map_cnt) {
0246e64d 20943 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
20944 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20945 sizeof(env->used_maps[0]),
20946 GFP_KERNEL);
0246e64d 20947
9bac3d6d 20948 if (!env->prog->aux->used_maps) {
0246e64d 20949 ret = -ENOMEM;
a2a7d570 20950 goto err_release_maps;
0246e64d
AS
20951 }
20952
9bac3d6d 20953 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 20954 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 20955 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
20956 }
20957 if (env->used_btf_cnt) {
20958 /* if program passed verifier, update used_btfs in bpf_prog_aux */
20959 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20960 sizeof(env->used_btfs[0]),
20961 GFP_KERNEL);
20962 if (!env->prog->aux->used_btfs) {
20963 ret = -ENOMEM;
20964 goto err_release_maps;
20965 }
0246e64d 20966
541c3bad
AN
20967 memcpy(env->prog->aux->used_btfs, env->used_btfs,
20968 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20969 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20970 }
20971 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
20972 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
20973 * bpf_ld_imm64 instructions
20974 */
20975 convert_pseudo_ld_imm64(env);
20976 }
cbd35700 20977
541c3bad 20978 adjust_btf_func(env);
ba64e7d8 20979
a2a7d570 20980err_release_maps:
9bac3d6d 20981 if (!env->prog->aux->used_maps)
0246e64d 20982 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 20983 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
20984 */
20985 release_maps(env);
541c3bad
AN
20986 if (!env->prog->aux->used_btfs)
20987 release_btfs(env);
03f87c0b
THJ
20988
20989 /* extension progs temporarily inherit the attach_type of their targets
20990 for verification purposes, so set it back to zero before returning
20991 */
20992 if (env->prog->type == BPF_PROG_TYPE_EXT)
20993 env->prog->expected_attach_type = 0;
20994
9bac3d6d 20995 *prog = env->prog;
3df126f3 20996err_unlock:
45a73c17
AS
20997 if (!is_priv)
20998 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
20999 vfree(env->insn_aux_data);
21000err_free_env:
21001 kfree(env);
51580e79
AS
21002 return ret;
21003}