bpf: Support new sign-extension load insns
[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>
51580e79 29
f4ac7e0b
JK
30#include "disasm.h"
31
00176a34 32static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 33#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
34 [_id] = & _name ## _verifier_ops,
35#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 36#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
37#include <linux/bpf_types.h>
38#undef BPF_PROG_TYPE
39#undef BPF_MAP_TYPE
f2e10bff 40#undef BPF_LINK_TYPE
00176a34
JK
41};
42
51580e79
AS
43/* bpf_check() is a static code analyzer that walks eBPF program
44 * instruction by instruction and updates register/stack state.
45 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46 *
47 * The first pass is depth-first-search to check that the program is a DAG.
48 * It rejects the following programs:
49 * - larger than BPF_MAXINSNS insns
50 * - if loop is present (detected via back-edge)
51 * - unreachable insns exist (shouldn't be a forest. program = one function)
52 * - out of bounds or malformed jumps
53 * The second pass is all possible path descent from the 1st insn.
8fb33b60 54 * Since it's analyzing all paths through the program, the length of the
eba38a96 55 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
56 * insn is less then 4K, but there are too many branches that change stack/regs.
57 * Number of 'branches to be analyzed' is limited to 1k
58 *
59 * On entry to each instruction, each register has a type, and the instruction
60 * changes the types of the registers depending on instruction semantics.
61 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
62 * copied to R1.
63 *
64 * All registers are 64-bit.
65 * R0 - return register
66 * R1-R5 argument passing registers
67 * R6-R9 callee saved registers
68 * R10 - frame pointer read-only
69 *
70 * At the start of BPF program the register R1 contains a pointer to bpf_context
71 * and has type PTR_TO_CTX.
72 *
73 * Verifier tracks arithmetic operations on pointers in case:
74 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
75 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
76 * 1st insn copies R10 (which has FRAME_PTR) type into R1
77 * and 2nd arithmetic instruction is pattern matched to recognize
78 * that it wants to construct a pointer to some element within stack.
79 * So after 2nd insn, the register R1 has type PTR_TO_STACK
80 * (and -20 constant is saved for further stack bounds checking).
81 * Meaning that this reg is a pointer to stack plus known immediate constant.
82 *
f1174f77 83 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 84 * means the register has some value, but it's not a valid pointer.
f1174f77 85 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
86 *
87 * When verifier sees load or store instructions the type of base register
c64b7983
JS
88 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
89 * four pointer types recognized by check_mem_access() function.
51580e79
AS
90 *
91 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
92 * and the range of [ptr, ptr + map's value_size) is accessible.
93 *
94 * registers used to pass values to function calls are checked against
95 * function argument constraints.
96 *
97 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
98 * It means that the register type passed to this function must be
99 * PTR_TO_STACK and it will be used inside the function as
100 * 'pointer to map element key'
101 *
102 * For example the argument constraints for bpf_map_lookup_elem():
103 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
104 * .arg1_type = ARG_CONST_MAP_PTR,
105 * .arg2_type = ARG_PTR_TO_MAP_KEY,
106 *
107 * ret_type says that this function returns 'pointer to map elem value or null'
108 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
109 * 2nd argument should be a pointer to stack, which will be used inside
110 * the helper function as a pointer to map element key.
111 *
112 * On the kernel side the helper function looks like:
113 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114 * {
115 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
116 * void *key = (void *) (unsigned long) r2;
117 * void *value;
118 *
119 * here kernel can access 'key' and 'map' pointers safely, knowing that
120 * [key, key + map->key_size) bytes are valid and were initialized on
121 * the stack of eBPF program.
122 * }
123 *
124 * Corresponding eBPF program may look like:
125 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
126 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
127 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
128 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
129 * here verifier looks at prototype of map_lookup_elem() and sees:
130 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
131 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132 *
133 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
134 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
135 * and were initialized prior to this call.
136 * If it's ok, then verifier allows this BPF_CALL insn and looks at
137 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
138 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
8fb33b60 139 * returns either pointer to map value or NULL.
51580e79
AS
140 *
141 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
142 * insn, the register holding that pointer in the true branch changes state to
143 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
144 * branch. See check_cond_jmp_op().
145 *
146 * After the call R0 is set to return type of the function and registers R1-R5
147 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
148 *
149 * The following reference types represent a potential reference to a kernel
150 * resource which, after first being allocated, must be checked and freed by
151 * the BPF program:
152 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153 *
154 * When the verifier sees a helper call return a reference type, it allocates a
155 * pointer id for the reference and stores it in the current function state.
156 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
157 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
158 * passes through a NULL-check conditional. For the branch wherein the state is
159 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
160 *
161 * For each helper function that allocates a reference, such as
162 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
163 * bpf_sk_release(). When a reference type passes into the release function,
164 * the verifier also releases the reference. If any unchecked or unreleased
165 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
166 */
167
17a52670 168/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 169struct bpf_verifier_stack_elem {
17a52670
AS
170 /* verifer state is 'st'
171 * before processing instruction 'insn_idx'
172 * and after processing instruction 'prev_insn_idx'
173 */
58e2af8b 174 struct bpf_verifier_state st;
17a52670
AS
175 int insn_idx;
176 int prev_insn_idx;
58e2af8b 177 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
178 /* length of verifier log at the time this state was pushed on stack */
179 u32 log_pos;
cbd35700
AS
180};
181
b285fcb7 182#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 183#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 184
d2e4c1e6
DB
185#define BPF_MAP_KEY_POISON (1ULL << 63)
186#define BPF_MAP_KEY_SEEN (1ULL << 62)
187
c93552c4
DB
188#define BPF_MAP_PTR_UNPRIV 1UL
189#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
190 POISON_POINTER_DELTA))
191#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
192
bc34dee6
JK
193static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
194static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
6a3cd331 195static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
5d92ddc3 196static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
6a3cd331
DM
197static int ref_set_non_owning(struct bpf_verifier_env *env,
198 struct bpf_reg_state *reg);
1cf3bfc6
IL
199static void specialize_kfunc(struct bpf_verifier_env *env,
200 u32 func_id, u16 offset, unsigned long *addr);
51302c95 201static bool is_trusted_reg(const struct bpf_reg_state *reg);
bc34dee6 202
c93552c4
DB
203static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
204{
d2e4c1e6 205 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
206}
207
208static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
209{
d2e4c1e6 210 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
211}
212
213static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
214 const struct bpf_map *map, bool unpriv)
215{
216 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
217 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
218 aux->map_ptr_state = (unsigned long)map |
219 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
220}
221
222static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
223{
224 return aux->map_key_state & BPF_MAP_KEY_POISON;
225}
226
227static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
228{
229 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
230}
231
232static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
233{
234 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
235}
236
237static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
238{
239 bool poisoned = bpf_map_key_poisoned(aux);
240
241 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
242 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 243}
fad73a1a 244
fde2a388
AN
245static bool bpf_helper_call(const struct bpf_insn *insn)
246{
247 return insn->code == (BPF_JMP | BPF_CALL) &&
248 insn->src_reg == 0;
249}
250
23a2d70c
YS
251static bool bpf_pseudo_call(const struct bpf_insn *insn)
252{
253 return insn->code == (BPF_JMP | BPF_CALL) &&
254 insn->src_reg == BPF_PSEUDO_CALL;
255}
256
e6ac2450
MKL
257static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
258{
259 return insn->code == (BPF_JMP | BPF_CALL) &&
260 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
261}
262
33ff9823
DB
263struct bpf_call_arg_meta {
264 struct bpf_map *map_ptr;
435faee1 265 bool raw_mode;
36bbef52 266 bool pkt_access;
8f14852e 267 u8 release_regno;
435faee1
DB
268 int regno;
269 int access_size;
457f4436 270 int mem_size;
10060503 271 u64 msize_max_value;
1b986589 272 int ref_obj_id;
f8064ab9 273 int dynptr_id;
3e8ce298 274 int map_uid;
d83525ca 275 int func_id;
22dc4a0f 276 struct btf *btf;
eaa6bcb7 277 u32 btf_id;
22dc4a0f 278 struct btf *ret_btf;
eaa6bcb7 279 u32 ret_btf_id;
69c087ba 280 u32 subprogno;
aa3496ac 281 struct btf_field *kptr_field;
33ff9823
DB
282};
283
d0e1ac22
AN
284struct bpf_kfunc_call_arg_meta {
285 /* In parameters */
286 struct btf *btf;
287 u32 func_id;
288 u32 kfunc_flags;
289 const struct btf_type *func_proto;
290 const char *func_name;
291 /* Out parameters */
292 u32 ref_obj_id;
293 u8 release_regno;
294 bool r0_rdonly;
295 u32 ret_btf_id;
296 u64 r0_size;
297 u32 subprogno;
298 struct {
299 u64 value;
300 bool found;
301 } arg_constant;
4d585f48 302
7793fc3b 303 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
4d585f48
DM
304 * generally to pass info about user-defined local kptr types to later
305 * verification logic
306 * bpf_obj_drop
307 * Record the local kptr type to be drop'd
308 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
7793fc3b
DM
309 * Record the local kptr type to be refcount_incr'd and use
310 * arg_owning_ref to determine whether refcount_acquire should be
311 * fallible
4d585f48
DM
312 */
313 struct btf *arg_btf;
314 u32 arg_btf_id;
7793fc3b 315 bool arg_owning_ref;
4d585f48 316
d0e1ac22
AN
317 struct {
318 struct btf_field *field;
319 } arg_list_head;
320 struct {
321 struct btf_field *field;
322 } arg_rbtree_root;
323 struct {
324 enum bpf_dynptr_type type;
325 u32 id;
361f129f 326 u32 ref_obj_id;
d0e1ac22 327 } initialized_dynptr;
06accc87
AN
328 struct {
329 u8 spi;
330 u8 frameno;
331 } iter;
d0e1ac22
AN
332 u64 mem_size;
333};
334
8580ac94
AS
335struct btf *btf_vmlinux;
336
cbd35700
AS
337static DEFINE_MUTEX(bpf_verifier_lock);
338
d9762e84
MKL
339static const struct bpf_line_info *
340find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
341{
342 const struct bpf_line_info *linfo;
343 const struct bpf_prog *prog;
344 u32 i, nr_linfo;
345
346 prog = env->prog;
347 nr_linfo = prog->aux->nr_linfo;
348
349 if (!nr_linfo || insn_off >= prog->len)
350 return NULL;
351
352 linfo = prog->aux->linfo;
353 for (i = 1; i < nr_linfo; i++)
354 if (insn_off < linfo[i].insn_off)
355 break;
356
357 return &linfo[i - 1];
358}
359
abe08840
JO
360__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
361{
77d2e05a 362 struct bpf_verifier_env *env = private_data;
abe08840
JO
363 va_list args;
364
77d2e05a
MKL
365 if (!bpf_verifier_log_needed(&env->log))
366 return;
367
abe08840 368 va_start(args, fmt);
77d2e05a 369 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
370 va_end(args);
371}
cbd35700 372
d9762e84
MKL
373static const char *ltrim(const char *s)
374{
375 while (isspace(*s))
376 s++;
377
378 return s;
379}
380
381__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
382 u32 insn_off,
383 const char *prefix_fmt, ...)
384{
385 const struct bpf_line_info *linfo;
386
387 if (!bpf_verifier_log_needed(&env->log))
388 return;
389
390 linfo = find_linfo(env, insn_off);
391 if (!linfo || linfo == env->prev_linfo)
392 return;
393
394 if (prefix_fmt) {
395 va_list args;
396
397 va_start(args, prefix_fmt);
398 bpf_verifier_vlog(&env->log, prefix_fmt, args);
399 va_end(args);
400 }
401
402 verbose(env, "%s\n",
403 ltrim(btf_name_by_offset(env->prog->aux->btf,
404 linfo->line_off)));
405
406 env->prev_linfo = linfo;
407}
408
bc2591d6
YS
409static void verbose_invalid_scalar(struct bpf_verifier_env *env,
410 struct bpf_reg_state *reg,
411 struct tnum *range, const char *ctx,
412 const char *reg_name)
413{
414 char tn_buf[48];
415
416 verbose(env, "At %s the register %s ", ctx, reg_name);
417 if (!tnum_is_unknown(reg->var_off)) {
418 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
419 verbose(env, "has value %s", tn_buf);
420 } else {
421 verbose(env, "has unknown scalar value");
422 }
423 tnum_strn(tn_buf, sizeof(tn_buf), *range);
424 verbose(env, " should have been in %s\n", tn_buf);
425}
426
de8f3a83
DB
427static bool type_is_pkt_pointer(enum bpf_reg_type type)
428{
0c9a7a7e 429 type = base_type(type);
de8f3a83
DB
430 return type == PTR_TO_PACKET ||
431 type == PTR_TO_PACKET_META;
432}
433
46f8bc92
MKL
434static bool type_is_sk_pointer(enum bpf_reg_type type)
435{
436 return type == PTR_TO_SOCKET ||
655a51e5 437 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
438 type == PTR_TO_TCP_SOCK ||
439 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
440}
441
1057d299
AS
442static bool type_may_be_null(u32 type)
443{
444 return type & PTR_MAYBE_NULL;
445}
446
51302c95 447static bool reg_not_null(const struct bpf_reg_state *reg)
cac616db 448{
51302c95
DV
449 enum bpf_reg_type type;
450
451 type = reg->type;
1057d299
AS
452 if (type_may_be_null(type))
453 return false;
454
455 type = base_type(type);
cac616db
JF
456 return type == PTR_TO_SOCKET ||
457 type == PTR_TO_TCP_SOCK ||
458 type == PTR_TO_MAP_VALUE ||
69c087ba 459 type == PTR_TO_MAP_KEY ||
d5271c5b 460 type == PTR_TO_SOCK_COMMON ||
51302c95 461 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
d5271c5b 462 type == PTR_TO_MEM;
cac616db
JF
463}
464
d8939cb0
DM
465static bool type_is_ptr_alloc_obj(u32 type)
466{
467 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
468}
469
6a3cd331
DM
470static bool type_is_non_owning_ref(u32 type)
471{
472 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
473}
474
4e814da0
KKD
475static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
476{
477 struct btf_record *rec = NULL;
478 struct btf_struct_meta *meta;
479
480 if (reg->type == PTR_TO_MAP_VALUE) {
481 rec = reg->map_ptr->record;
d8939cb0 482 } else if (type_is_ptr_alloc_obj(reg->type)) {
4e814da0
KKD
483 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
484 if (meta)
485 rec = meta->record;
486 }
487 return rec;
488}
489
fde2a388
AN
490static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
491{
492 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
493
494 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
495}
496
d83525ca
AS
497static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
498{
4e814da0 499 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
cba368c1
MKL
500}
501
20b2aff4
HL
502static bool type_is_rdonly_mem(u32 type)
503{
504 return type & MEM_RDONLY;
cba368c1
MKL
505}
506
64d85290
JS
507static bool is_acquire_function(enum bpf_func_id func_id,
508 const struct bpf_map *map)
509{
510 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511
512 if (func_id == BPF_FUNC_sk_lookup_tcp ||
513 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436 514 func_id == BPF_FUNC_skc_lookup_tcp ||
c0a5a21c
KKD
515 func_id == BPF_FUNC_ringbuf_reserve ||
516 func_id == BPF_FUNC_kptr_xchg)
64d85290
JS
517 return true;
518
519 if (func_id == BPF_FUNC_map_lookup_elem &&
520 (map_type == BPF_MAP_TYPE_SOCKMAP ||
521 map_type == BPF_MAP_TYPE_SOCKHASH))
522 return true;
523
524 return false;
46f8bc92
MKL
525}
526
1b986589
MKL
527static bool is_ptr_cast_function(enum bpf_func_id func_id)
528{
529 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
530 func_id == BPF_FUNC_sk_fullsock ||
531 func_id == BPF_FUNC_skc_to_tcp_sock ||
532 func_id == BPF_FUNC_skc_to_tcp6_sock ||
533 func_id == BPF_FUNC_skc_to_udp6_sock ||
3bc253c2 534 func_id == BPF_FUNC_skc_to_mptcp_sock ||
1df8f55a
MKL
535 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
537}
538
88374342 539static bool is_dynptr_ref_function(enum bpf_func_id func_id)
b2d8ef19
DM
540{
541 return func_id == BPF_FUNC_dynptr_data;
542}
543
fde2a388
AN
544static bool is_callback_calling_kfunc(u32 btf_id);
545
be2ef816
AN
546static bool is_callback_calling_function(enum bpf_func_id func_id)
547{
548 return func_id == BPF_FUNC_for_each_map_elem ||
549 func_id == BPF_FUNC_timer_set_callback ||
550 func_id == BPF_FUNC_find_vma ||
551 func_id == BPF_FUNC_loop ||
552 func_id == BPF_FUNC_user_ringbuf_drain;
553}
554
fde2a388
AN
555static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556{
557 return func_id == BPF_FUNC_timer_set_callback;
558}
559
9bb00b28
YS
560static bool is_storage_get_function(enum bpf_func_id func_id)
561{
562 return func_id == BPF_FUNC_sk_storage_get ||
563 func_id == BPF_FUNC_inode_storage_get ||
564 func_id == BPF_FUNC_task_storage_get ||
565 func_id == BPF_FUNC_cgrp_storage_get;
566}
567
b2d8ef19
DM
568static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 const struct bpf_map *map)
570{
571 int ref_obj_uses = 0;
572
573 if (is_ptr_cast_function(func_id))
574 ref_obj_uses++;
575 if (is_acquire_function(func_id, map))
576 ref_obj_uses++;
88374342 577 if (is_dynptr_ref_function(func_id))
b2d8ef19
DM
578 ref_obj_uses++;
579
580 return ref_obj_uses > 1;
581}
582
39491867
BJ
583static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584{
585 return BPF_CLASS(insn->code) == BPF_STX &&
586 BPF_MODE(insn->code) == BPF_ATOMIC &&
587 insn->imm == BPF_CMPXCHG;
588}
589
c25b2ae1
HL
590/* string representation of 'enum bpf_reg_type'
591 *
592 * Note that reg_type_str() can not appear more than once in a single verbose()
593 * statement.
594 */
595static const char *reg_type_str(struct bpf_verifier_env *env,
596 enum bpf_reg_type type)
597{
ef66c547 598 char postfix[16] = {0}, prefix[64] = {0};
c25b2ae1
HL
599 static const char * const str[] = {
600 [NOT_INIT] = "?",
7df5072c 601 [SCALAR_VALUE] = "scalar",
c25b2ae1
HL
602 [PTR_TO_CTX] = "ctx",
603 [CONST_PTR_TO_MAP] = "map_ptr",
604 [PTR_TO_MAP_VALUE] = "map_value",
605 [PTR_TO_STACK] = "fp",
606 [PTR_TO_PACKET] = "pkt",
607 [PTR_TO_PACKET_META] = "pkt_meta",
608 [PTR_TO_PACKET_END] = "pkt_end",
609 [PTR_TO_FLOW_KEYS] = "flow_keys",
610 [PTR_TO_SOCKET] = "sock",
611 [PTR_TO_SOCK_COMMON] = "sock_common",
612 [PTR_TO_TCP_SOCK] = "tcp_sock",
613 [PTR_TO_TP_BUFFER] = "tp_buffer",
614 [PTR_TO_XDP_SOCK] = "xdp_sock",
615 [PTR_TO_BTF_ID] = "ptr_",
c25b2ae1 616 [PTR_TO_MEM] = "mem",
20b2aff4 617 [PTR_TO_BUF] = "buf",
c25b2ae1
HL
618 [PTR_TO_FUNC] = "func",
619 [PTR_TO_MAP_KEY] = "map_key",
27060531 620 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
c25b2ae1
HL
621 };
622
623 if (type & PTR_MAYBE_NULL) {
5844101a 624 if (base_type(type) == PTR_TO_BTF_ID)
c25b2ae1
HL
625 strncpy(postfix, "or_null_", 16);
626 else
627 strncpy(postfix, "_or_null", 16);
628 }
629
9bb00b28 630 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
ef66c547
DV
631 type & MEM_RDONLY ? "rdonly_" : "",
632 type & MEM_RINGBUF ? "ringbuf_" : "",
633 type & MEM_USER ? "user_" : "",
634 type & MEM_PERCPU ? "percpu_" : "",
9bb00b28 635 type & MEM_RCU ? "rcu_" : "",
3f00c523
DV
636 type & PTR_UNTRUSTED ? "untrusted_" : "",
637 type & PTR_TRUSTED ? "trusted_" : ""
ef66c547 638 );
20b2aff4 639
d9439c21 640 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
20b2aff4 641 prefix, str[base_type(type)], postfix);
d9439c21 642 return env->tmp_str_buf;
c25b2ae1 643}
17a52670 644
8efea21d
EC
645static char slot_type_char[] = {
646 [STACK_INVALID] = '?',
647 [STACK_SPILL] = 'r',
648 [STACK_MISC] = 'm',
649 [STACK_ZERO] = '0',
97e03f52 650 [STACK_DYNPTR] = 'd',
06accc87 651 [STACK_ITER] = 'i',
8efea21d
EC
652};
653
4e92024a
AS
654static void print_liveness(struct bpf_verifier_env *env,
655 enum bpf_reg_liveness live)
656{
9242b5f5 657 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
658 verbose(env, "_");
659 if (live & REG_LIVE_READ)
660 verbose(env, "r");
661 if (live & REG_LIVE_WRITTEN)
662 verbose(env, "w");
9242b5f5
AS
663 if (live & REG_LIVE_DONE)
664 verbose(env, "D");
4e92024a
AS
665}
666
79168a66 667static int __get_spi(s32 off)
97e03f52
JK
668{
669 return (-off - 1) / BPF_REG_SIZE;
670}
671
f5b625e5
KKD
672static struct bpf_func_state *func(struct bpf_verifier_env *env,
673 const struct bpf_reg_state *reg)
674{
675 struct bpf_verifier_state *cur = env->cur_state;
676
677 return cur->frame[reg->frameno];
678}
679
97e03f52
JK
680static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
681{
f5b625e5 682 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
97e03f52 683
f5b625e5
KKD
684 /* We need to check that slots between [spi - nr_slots + 1, spi] are
685 * within [0, allocated_stack).
686 *
687 * Please note that the spi grows downwards. For example, a dynptr
688 * takes the size of two stack slots; the first slot will be at
689 * spi and the second slot will be at spi - 1.
690 */
691 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
97e03f52
JK
692}
693
a461f5ad
AN
694static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
695 const char *obj_kind, int nr_slots)
f4d7e40a 696{
79168a66 697 int off, spi;
f4d7e40a 698
79168a66 699 if (!tnum_is_const(reg->var_off)) {
a461f5ad 700 verbose(env, "%s has to be at a constant offset\n", obj_kind);
79168a66
KKD
701 return -EINVAL;
702 }
703
704 off = reg->off + reg->var_off.value;
705 if (off % BPF_REG_SIZE) {
a461f5ad 706 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
79168a66
KKD
707 return -EINVAL;
708 }
709
710 spi = __get_spi(off);
a461f5ad
AN
711 if (spi + 1 < nr_slots) {
712 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
79168a66
KKD
713 return -EINVAL;
714 }
97e03f52 715
a461f5ad 716 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
f5b625e5
KKD
717 return -ERANGE;
718 return spi;
f4d7e40a
AS
719}
720
a461f5ad
AN
721static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
722{
723 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
724}
725
06accc87
AN
726static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
727{
728 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
729}
730
b32a5dae 731static const char *btf_type_name(const struct btf *btf, u32 id)
9e15db66 732{
22dc4a0f 733 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
734}
735
d54e0f6c
AN
736static const char *dynptr_type_str(enum bpf_dynptr_type type)
737{
738 switch (type) {
739 case BPF_DYNPTR_TYPE_LOCAL:
740 return "local";
741 case BPF_DYNPTR_TYPE_RINGBUF:
742 return "ringbuf";
743 case BPF_DYNPTR_TYPE_SKB:
744 return "skb";
745 case BPF_DYNPTR_TYPE_XDP:
746 return "xdp";
747 case BPF_DYNPTR_TYPE_INVALID:
748 return "<invalid>";
749 default:
750 WARN_ONCE(1, "unknown dynptr type %d\n", type);
751 return "<unknown>";
752 }
753}
754
06accc87
AN
755static const char *iter_type_str(const struct btf *btf, u32 btf_id)
756{
757 if (!btf || btf_id == 0)
758 return "<invalid>";
759
760 /* we already validated that type is valid and has conforming name */
b32a5dae 761 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
06accc87
AN
762}
763
764static const char *iter_state_str(enum bpf_iter_state state)
765{
766 switch (state) {
767 case BPF_ITER_STATE_ACTIVE:
768 return "active";
769 case BPF_ITER_STATE_DRAINED:
770 return "drained";
771 case BPF_ITER_STATE_INVALID:
772 return "<invalid>";
773 default:
774 WARN_ONCE(1, "unknown iter state %d\n", state);
775 return "<unknown>";
776 }
777}
778
0f55f9ed
CL
779static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
780{
781 env->scratched_regs |= 1U << regno;
782}
783
784static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
785{
343e5375 786 env->scratched_stack_slots |= 1ULL << spi;
0f55f9ed
CL
787}
788
789static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
790{
791 return (env->scratched_regs >> regno) & 1;
792}
793
794static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
795{
796 return (env->scratched_stack_slots >> regno) & 1;
797}
798
799static bool verifier_state_scratched(const struct bpf_verifier_env *env)
800{
801 return env->scratched_regs || env->scratched_stack_slots;
802}
803
804static void mark_verifier_state_clean(struct bpf_verifier_env *env)
805{
806 env->scratched_regs = 0U;
343e5375 807 env->scratched_stack_slots = 0ULL;
0f55f9ed
CL
808}
809
810/* Used for printing the entire verifier state. */
811static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
812{
813 env->scratched_regs = ~0U;
343e5375 814 env->scratched_stack_slots = ~0ULL;
0f55f9ed
CL
815}
816
97e03f52
JK
817static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
818{
819 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
820 case DYNPTR_TYPE_LOCAL:
821 return BPF_DYNPTR_TYPE_LOCAL;
bc34dee6
JK
822 case DYNPTR_TYPE_RINGBUF:
823 return BPF_DYNPTR_TYPE_RINGBUF;
b5964b96
JK
824 case DYNPTR_TYPE_SKB:
825 return BPF_DYNPTR_TYPE_SKB;
05421aec
JK
826 case DYNPTR_TYPE_XDP:
827 return BPF_DYNPTR_TYPE_XDP;
97e03f52
JK
828 default:
829 return BPF_DYNPTR_TYPE_INVALID;
830 }
831}
832
66e3a13e
JK
833static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
834{
835 switch (type) {
836 case BPF_DYNPTR_TYPE_LOCAL:
837 return DYNPTR_TYPE_LOCAL;
838 case BPF_DYNPTR_TYPE_RINGBUF:
839 return DYNPTR_TYPE_RINGBUF;
840 case BPF_DYNPTR_TYPE_SKB:
841 return DYNPTR_TYPE_SKB;
842 case BPF_DYNPTR_TYPE_XDP:
843 return DYNPTR_TYPE_XDP;
844 default:
845 return 0;
846 }
847}
848
bc34dee6
JK
849static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
850{
851 return type == BPF_DYNPTR_TYPE_RINGBUF;
852}
853
27060531
KKD
854static void __mark_dynptr_reg(struct bpf_reg_state *reg,
855 enum bpf_dynptr_type type,
f8064ab9 856 bool first_slot, int dynptr_id);
27060531
KKD
857
858static void __mark_reg_not_init(const struct bpf_verifier_env *env,
859 struct bpf_reg_state *reg);
860
f8064ab9
KKD
861static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
862 struct bpf_reg_state *sreg1,
27060531
KKD
863 struct bpf_reg_state *sreg2,
864 enum bpf_dynptr_type type)
865{
f8064ab9
KKD
866 int id = ++env->id_gen;
867
868 __mark_dynptr_reg(sreg1, type, true, id);
869 __mark_dynptr_reg(sreg2, type, false, id);
27060531
KKD
870}
871
f8064ab9
KKD
872static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
873 struct bpf_reg_state *reg,
27060531
KKD
874 enum bpf_dynptr_type type)
875{
f8064ab9 876 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
27060531
KKD
877}
878
ef8fc7a0
KKD
879static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
880 struct bpf_func_state *state, int spi);
27060531 881
97e03f52 882static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
361f129f 883 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
97e03f52
JK
884{
885 struct bpf_func_state *state = func(env, reg);
886 enum bpf_dynptr_type type;
361f129f 887 int spi, i, err;
97e03f52 888
79168a66
KKD
889 spi = dynptr_get_spi(env, reg);
890 if (spi < 0)
891 return spi;
97e03f52 892
379d4ba8
KKD
893 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
894 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
895 * to ensure that for the following example:
896 * [d1][d1][d2][d2]
897 * spi 3 2 1 0
898 * So marking spi = 2 should lead to destruction of both d1 and d2. In
899 * case they do belong to same dynptr, second call won't see slot_type
900 * as STACK_DYNPTR and will simply skip destruction.
901 */
902 err = destroy_if_dynptr_stack_slot(env, state, spi);
903 if (err)
904 return err;
905 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
906 if (err)
907 return err;
97e03f52
JK
908
909 for (i = 0; i < BPF_REG_SIZE; i++) {
910 state->stack[spi].slot_type[i] = STACK_DYNPTR;
911 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
912 }
913
914 type = arg_to_dynptr_type(arg_type);
915 if (type == BPF_DYNPTR_TYPE_INVALID)
916 return -EINVAL;
917
f8064ab9 918 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
27060531 919 &state->stack[spi - 1].spilled_ptr, type);
97e03f52 920
bc34dee6
JK
921 if (dynptr_type_refcounted(type)) {
922 /* The id is used to track proper releasing */
361f129f
JK
923 int id;
924
925 if (clone_ref_obj_id)
926 id = clone_ref_obj_id;
927 else
928 id = acquire_reference_state(env, insn_idx);
929
bc34dee6
JK
930 if (id < 0)
931 return id;
932
27060531
KKD
933 state->stack[spi].spilled_ptr.ref_obj_id = id;
934 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
bc34dee6
JK
935 }
936
d6fefa11
KKD
937 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
938 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
939
97e03f52
JK
940 return 0;
941}
942
361f129f 943static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
97e03f52 944{
361f129f 945 int i;
97e03f52
JK
946
947 for (i = 0; i < BPF_REG_SIZE; i++) {
948 state->stack[spi].slot_type[i] = STACK_INVALID;
949 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
950 }
951
27060531
KKD
952 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
953 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
d6fefa11
KKD
954
955 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
956 *
957 * While we don't allow reading STACK_INVALID, it is still possible to
958 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
959 * helpers or insns can do partial read of that part without failing,
960 * but check_stack_range_initialized, check_stack_read_var_off, and
961 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
962 * the slot conservatively. Hence we need to prevent those liveness
963 * marking walks.
964 *
965 * This was not a problem before because STACK_INVALID is only set by
966 * default (where the default reg state has its reg->parent as NULL), or
967 * in clean_live_states after REG_LIVE_DONE (at which point
968 * mark_reg_read won't walk reg->parent chain), but not randomly during
969 * verifier state exploration (like we did above). Hence, for our case
970 * parentage chain will still be live (i.e. reg->parent may be
971 * non-NULL), while earlier reg->parent was NULL, so we need
972 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
973 * done later on reads or by mark_dynptr_read as well to unnecessary
974 * mark registers in verifier state.
975 */
976 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
977 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
361f129f
JK
978}
979
980static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
981{
982 struct bpf_func_state *state = func(env, reg);
983 int spi, ref_obj_id, i;
984
985 spi = dynptr_get_spi(env, reg);
986 if (spi < 0)
987 return spi;
988
989 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
990 invalidate_dynptr(env, state, spi);
991 return 0;
992 }
993
994 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
995
996 /* If the dynptr has a ref_obj_id, then we need to invalidate
997 * two things:
998 *
999 * 1) Any dynptrs with a matching ref_obj_id (clones)
1000 * 2) Any slices derived from this dynptr.
1001 */
1002
1003 /* Invalidate any slices associated with this dynptr */
1004 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1005
1006 /* Invalidate any dynptr clones */
1007 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1008 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1009 continue;
1010
1011 /* it should always be the case that if the ref obj id
1012 * matches then the stack slot also belongs to a
1013 * dynptr
1014 */
1015 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1016 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1017 return -EFAULT;
1018 }
1019 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1020 invalidate_dynptr(env, state, i);
1021 }
d6fefa11 1022
97e03f52
JK
1023 return 0;
1024}
1025
ef8fc7a0
KKD
1026static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1027 struct bpf_reg_state *reg);
1028
dbd8d228
KKD
1029static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1030{
1031 if (!env->allow_ptr_leaks)
1032 __mark_reg_not_init(env, reg);
1033 else
1034 __mark_reg_unknown(env, reg);
1035}
1036
ef8fc7a0
KKD
1037static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1038 struct bpf_func_state *state, int spi)
97e03f52 1039{
f8064ab9
KKD
1040 struct bpf_func_state *fstate;
1041 struct bpf_reg_state *dreg;
1042 int i, dynptr_id;
27060531 1043
ef8fc7a0
KKD
1044 /* We always ensure that STACK_DYNPTR is never set partially,
1045 * hence just checking for slot_type[0] is enough. This is
1046 * different for STACK_SPILL, where it may be only set for
1047 * 1 byte, so code has to use is_spilled_reg.
1048 */
1049 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1050 return 0;
97e03f52 1051
ef8fc7a0
KKD
1052 /* Reposition spi to first slot */
1053 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1054 spi = spi + 1;
1055
1056 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1057 verbose(env, "cannot overwrite referenced dynptr\n");
1058 return -EINVAL;
1059 }
1060
1061 mark_stack_slot_scratched(env, spi);
1062 mark_stack_slot_scratched(env, spi - 1);
97e03f52 1063
ef8fc7a0 1064 /* Writing partially to one dynptr stack slot destroys both. */
97e03f52 1065 for (i = 0; i < BPF_REG_SIZE; i++) {
ef8fc7a0
KKD
1066 state->stack[spi].slot_type[i] = STACK_INVALID;
1067 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
97e03f52
JK
1068 }
1069
f8064ab9
KKD
1070 dynptr_id = state->stack[spi].spilled_ptr.id;
1071 /* Invalidate any slices associated with this dynptr */
1072 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1073 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1074 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1075 continue;
dbd8d228
KKD
1076 if (dreg->dynptr_id == dynptr_id)
1077 mark_reg_invalid(env, dreg);
f8064ab9 1078 }));
ef8fc7a0
KKD
1079
1080 /* Do not release reference state, we are destroying dynptr on stack,
1081 * not using some helper to release it. Just reset register.
1082 */
1083 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1084 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1085
1086 /* Same reason as unmark_stack_slots_dynptr above */
1087 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1088 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089
1090 return 0;
1091}
1092
7e0dac28 1093static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
97e03f52 1094{
7e0dac28
JK
1095 int spi;
1096
27060531
KKD
1097 if (reg->type == CONST_PTR_TO_DYNPTR)
1098 return false;
97e03f52 1099
7e0dac28
JK
1100 spi = dynptr_get_spi(env, reg);
1101
1102 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1103 * error because this just means the stack state hasn't been updated yet.
1104 * We will do check_mem_access to check and update stack bounds later.
f5b625e5 1105 */
7e0dac28
JK
1106 if (spi < 0 && spi != -ERANGE)
1107 return false;
1108
1109 /* We don't need to check if the stack slots are marked by previous
1110 * dynptr initializations because we allow overwriting existing unreferenced
1111 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1112 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1113 * touching are completely destructed before we reinitialize them for a new
1114 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1115 * instead of delaying it until the end where the user will get "Unreleased
379d4ba8
KKD
1116 * reference" error.
1117 */
97e03f52
JK
1118 return true;
1119}
1120
7e0dac28 1121static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
97e03f52
JK
1122{
1123 struct bpf_func_state *state = func(env, reg);
7e0dac28 1124 int i, spi;
97e03f52 1125
7e0dac28
JK
1126 /* This already represents first slot of initialized bpf_dynptr.
1127 *
1128 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1129 * check_func_arg_reg_off's logic, so we don't need to check its
1130 * offset and alignment.
1131 */
27060531
KKD
1132 if (reg->type == CONST_PTR_TO_DYNPTR)
1133 return true;
1134
7e0dac28 1135 spi = dynptr_get_spi(env, reg);
79168a66
KKD
1136 if (spi < 0)
1137 return false;
f5b625e5 1138 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
97e03f52
JK
1139 return false;
1140
1141 for (i = 0; i < BPF_REG_SIZE; i++) {
1142 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1143 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1144 return false;
1145 }
1146
e9e315b4
RS
1147 return true;
1148}
1149
6b75bd3d
KKD
1150static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1151 enum bpf_arg_type arg_type)
e9e315b4
RS
1152{
1153 struct bpf_func_state *state = func(env, reg);
1154 enum bpf_dynptr_type dynptr_type;
27060531 1155 int spi;
e9e315b4 1156
97e03f52
JK
1157 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1158 if (arg_type == ARG_PTR_TO_DYNPTR)
1159 return true;
1160
e9e315b4 1161 dynptr_type = arg_to_dynptr_type(arg_type);
27060531
KKD
1162 if (reg->type == CONST_PTR_TO_DYNPTR) {
1163 return reg->dynptr.type == dynptr_type;
1164 } else {
79168a66
KKD
1165 spi = dynptr_get_spi(env, reg);
1166 if (spi < 0)
1167 return false;
27060531
KKD
1168 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1169 }
97e03f52
JK
1170}
1171
06accc87
AN
1172static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1173
1174static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1175 struct bpf_reg_state *reg, int insn_idx,
1176 struct btf *btf, u32 btf_id, int nr_slots)
1177{
1178 struct bpf_func_state *state = func(env, reg);
1179 int spi, i, j, id;
1180
1181 spi = iter_get_spi(env, reg, nr_slots);
1182 if (spi < 0)
1183 return spi;
1184
1185 id = acquire_reference_state(env, insn_idx);
1186 if (id < 0)
1187 return id;
1188
1189 for (i = 0; i < nr_slots; i++) {
1190 struct bpf_stack_state *slot = &state->stack[spi - i];
1191 struct bpf_reg_state *st = &slot->spilled_ptr;
1192
1193 __mark_reg_known_zero(st);
1194 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1195 st->live |= REG_LIVE_WRITTEN;
1196 st->ref_obj_id = i == 0 ? id : 0;
1197 st->iter.btf = btf;
1198 st->iter.btf_id = btf_id;
1199 st->iter.state = BPF_ITER_STATE_ACTIVE;
1200 st->iter.depth = 0;
1201
1202 for (j = 0; j < BPF_REG_SIZE; j++)
1203 slot->slot_type[j] = STACK_ITER;
1204
1205 mark_stack_slot_scratched(env, spi - i);
1206 }
1207
1208 return 0;
1209}
1210
1211static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1212 struct bpf_reg_state *reg, int nr_slots)
1213{
1214 struct bpf_func_state *state = func(env, reg);
1215 int spi, i, j;
1216
1217 spi = iter_get_spi(env, reg, nr_slots);
1218 if (spi < 0)
1219 return spi;
1220
1221 for (i = 0; i < nr_slots; i++) {
1222 struct bpf_stack_state *slot = &state->stack[spi - i];
1223 struct bpf_reg_state *st = &slot->spilled_ptr;
1224
1225 if (i == 0)
1226 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1227
1228 __mark_reg_not_init(env, st);
1229
1230 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1231 st->live |= REG_LIVE_WRITTEN;
1232
1233 for (j = 0; j < BPF_REG_SIZE; j++)
1234 slot->slot_type[j] = STACK_INVALID;
1235
1236 mark_stack_slot_scratched(env, spi - i);
1237 }
1238
1239 return 0;
1240}
1241
1242static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1243 struct bpf_reg_state *reg, int nr_slots)
1244{
1245 struct bpf_func_state *state = func(env, reg);
1246 int spi, i, j;
1247
1248 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1249 * will do check_mem_access to check and update stack bounds later, so
1250 * return true for that case.
1251 */
1252 spi = iter_get_spi(env, reg, nr_slots);
1253 if (spi == -ERANGE)
1254 return true;
1255 if (spi < 0)
1256 return false;
1257
1258 for (i = 0; i < nr_slots; i++) {
1259 struct bpf_stack_state *slot = &state->stack[spi - i];
1260
1261 for (j = 0; j < BPF_REG_SIZE; j++)
1262 if (slot->slot_type[j] == STACK_ITER)
1263 return false;
1264 }
1265
1266 return true;
1267}
1268
1269static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1270 struct btf *btf, u32 btf_id, int nr_slots)
1271{
1272 struct bpf_func_state *state = func(env, reg);
1273 int spi, i, j;
1274
1275 spi = iter_get_spi(env, reg, nr_slots);
1276 if (spi < 0)
1277 return false;
1278
1279 for (i = 0; i < nr_slots; i++) {
1280 struct bpf_stack_state *slot = &state->stack[spi - i];
1281 struct bpf_reg_state *st = &slot->spilled_ptr;
1282
1283 /* only main (first) slot has ref_obj_id set */
1284 if (i == 0 && !st->ref_obj_id)
1285 return false;
1286 if (i != 0 && st->ref_obj_id)
1287 return false;
1288 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1289 return false;
1290
1291 for (j = 0; j < BPF_REG_SIZE; j++)
1292 if (slot->slot_type[j] != STACK_ITER)
1293 return false;
1294 }
1295
1296 return true;
1297}
1298
1299/* Check if given stack slot is "special":
1300 * - spilled register state (STACK_SPILL);
1301 * - dynptr state (STACK_DYNPTR);
1302 * - iter state (STACK_ITER).
1303 */
1304static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1305{
1306 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1307
1308 switch (type) {
1309 case STACK_SPILL:
1310 case STACK_DYNPTR:
1311 case STACK_ITER:
1312 return true;
1313 case STACK_INVALID:
1314 case STACK_MISC:
1315 case STACK_ZERO:
1316 return false;
1317 default:
1318 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1319 return true;
1320 }
1321}
1322
27113c59
MKL
1323/* The reg state of a pointer or a bounded scalar was saved when
1324 * it was spilled to the stack.
1325 */
1326static bool is_spilled_reg(const struct bpf_stack_state *stack)
1327{
1328 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1329}
1330
407958a0
AN
1331static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1332{
1333 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1334 stack->spilled_ptr.type == SCALAR_VALUE;
1335}
1336
354e8f19
MKL
1337static void scrub_spilled_slot(u8 *stype)
1338{
1339 if (*stype != STACK_INVALID)
1340 *stype = STACK_MISC;
1341}
1342
61bd5218 1343static void print_verifier_state(struct bpf_verifier_env *env,
0f55f9ed
CL
1344 const struct bpf_func_state *state,
1345 bool print_all)
17a52670 1346{
f4d7e40a 1347 const struct bpf_reg_state *reg;
17a52670
AS
1348 enum bpf_reg_type t;
1349 int i;
1350
f4d7e40a
AS
1351 if (state->frameno)
1352 verbose(env, " frame%d:", state->frameno);
17a52670 1353 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
1354 reg = &state->regs[i];
1355 t = reg->type;
17a52670
AS
1356 if (t == NOT_INIT)
1357 continue;
0f55f9ed
CL
1358 if (!print_all && !reg_scratched(env, i))
1359 continue;
4e92024a
AS
1360 verbose(env, " R%d", i);
1361 print_liveness(env, reg->live);
7df5072c 1362 verbose(env, "=");
b5dc0163
AS
1363 if (t == SCALAR_VALUE && reg->precise)
1364 verbose(env, "P");
f1174f77
EC
1365 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1366 tnum_is_const(reg->var_off)) {
1367 /* reg->off should be 0 for SCALAR_VALUE */
7df5072c 1368 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
61bd5218 1369 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 1370 } else {
7df5072c
ML
1371 const char *sep = "";
1372
1373 verbose(env, "%s", reg_type_str(env, t));
5844101a 1374 if (base_type(t) == PTR_TO_BTF_ID)
b32a5dae 1375 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
7df5072c
ML
1376 verbose(env, "(");
1377/*
1378 * _a stands for append, was shortened to avoid multiline statements below.
1379 * This macro is used to output a comma separated list of attributes.
1380 */
1381#define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1382
1383 if (reg->id)
1384 verbose_a("id=%d", reg->id);
a28ace78 1385 if (reg->ref_obj_id)
7df5072c 1386 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
6a3cd331
DM
1387 if (type_is_non_owning_ref(reg->type))
1388 verbose_a("%s", "non_own_ref");
f1174f77 1389 if (t != SCALAR_VALUE)
7df5072c 1390 verbose_a("off=%d", reg->off);
de8f3a83 1391 if (type_is_pkt_pointer(t))
7df5072c 1392 verbose_a("r=%d", reg->range);
c25b2ae1
HL
1393 else if (base_type(t) == CONST_PTR_TO_MAP ||
1394 base_type(t) == PTR_TO_MAP_KEY ||
1395 base_type(t) == PTR_TO_MAP_VALUE)
7df5072c
ML
1396 verbose_a("ks=%d,vs=%d",
1397 reg->map_ptr->key_size,
1398 reg->map_ptr->value_size);
7d1238f2
EC
1399 if (tnum_is_const(reg->var_off)) {
1400 /* Typically an immediate SCALAR_VALUE, but
1401 * could be a pointer whose offset is too big
1402 * for reg->off
1403 */
7df5072c 1404 verbose_a("imm=%llx", reg->var_off.value);
7d1238f2
EC
1405 } else {
1406 if (reg->smin_value != reg->umin_value &&
1407 reg->smin_value != S64_MIN)
7df5072c 1408 verbose_a("smin=%lld", (long long)reg->smin_value);
7d1238f2
EC
1409 if (reg->smax_value != reg->umax_value &&
1410 reg->smax_value != S64_MAX)
7df5072c 1411 verbose_a("smax=%lld", (long long)reg->smax_value);
7d1238f2 1412 if (reg->umin_value != 0)
7df5072c 1413 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
7d1238f2 1414 if (reg->umax_value != U64_MAX)
7df5072c 1415 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
7d1238f2
EC
1416 if (!tnum_is_unknown(reg->var_off)) {
1417 char tn_buf[48];
f1174f77 1418
7d1238f2 1419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7df5072c 1420 verbose_a("var_off=%s", tn_buf);
7d1238f2 1421 }
3f50f132
JF
1422 if (reg->s32_min_value != reg->smin_value &&
1423 reg->s32_min_value != S32_MIN)
7df5072c 1424 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
3f50f132
JF
1425 if (reg->s32_max_value != reg->smax_value &&
1426 reg->s32_max_value != S32_MAX)
7df5072c 1427 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
3f50f132
JF
1428 if (reg->u32_min_value != reg->umin_value &&
1429 reg->u32_min_value != U32_MIN)
7df5072c 1430 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
3f50f132
JF
1431 if (reg->u32_max_value != reg->umax_value &&
1432 reg->u32_max_value != U32_MAX)
7df5072c 1433 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
f1174f77 1434 }
7df5072c
ML
1435#undef verbose_a
1436
61bd5218 1437 verbose(env, ")");
f1174f77 1438 }
17a52670 1439 }
638f5b90 1440 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
1441 char types_buf[BPF_REG_SIZE + 1];
1442 bool valid = false;
1443 int j;
1444
1445 for (j = 0; j < BPF_REG_SIZE; j++) {
1446 if (state->stack[i].slot_type[j] != STACK_INVALID)
1447 valid = true;
d54e0f6c 1448 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
8efea21d
EC
1449 }
1450 types_buf[BPF_REG_SIZE] = 0;
1451 if (!valid)
1452 continue;
0f55f9ed
CL
1453 if (!print_all && !stack_slot_scratched(env, i))
1454 continue;
d54e0f6c
AN
1455 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1456 case STACK_SPILL:
b5dc0163
AS
1457 reg = &state->stack[i].spilled_ptr;
1458 t = reg->type;
d54e0f6c
AN
1459
1460 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1461 print_liveness(env, reg->live);
7df5072c 1462 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
b5dc0163
AS
1463 if (t == SCALAR_VALUE && reg->precise)
1464 verbose(env, "P");
1465 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1466 verbose(env, "%lld", reg->var_off.value + reg->off);
d54e0f6c
AN
1467 break;
1468 case STACK_DYNPTR:
1469 i += BPF_DYNPTR_NR_SLOTS - 1;
1470 reg = &state->stack[i].spilled_ptr;
1471
1472 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 print_liveness(env, reg->live);
1474 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1475 if (reg->ref_obj_id)
1476 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1477 break;
06accc87
AN
1478 case STACK_ITER:
1479 /* only main slot has ref_obj_id set; skip others */
1480 reg = &state->stack[i].spilled_ptr;
1481 if (!reg->ref_obj_id)
1482 continue;
1483
1484 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 print_liveness(env, reg->live);
1486 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1487 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1488 reg->ref_obj_id, iter_state_str(reg->iter.state),
1489 reg->iter.depth);
1490 break;
d54e0f6c
AN
1491 case STACK_MISC:
1492 case STACK_ZERO:
1493 default:
1494 reg = &state->stack[i].spilled_ptr;
1495
1496 for (j = 0; j < BPF_REG_SIZE; j++)
1497 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1498 types_buf[BPF_REG_SIZE] = 0;
1499
1500 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1501 print_liveness(env, reg->live);
8efea21d 1502 verbose(env, "=%s", types_buf);
d54e0f6c 1503 break;
b5dc0163 1504 }
17a52670 1505 }
fd978bf7
JS
1506 if (state->acquired_refs && state->refs[0].id) {
1507 verbose(env, " refs=%d", state->refs[0].id);
1508 for (i = 1; i < state->acquired_refs; i++)
1509 if (state->refs[i].id)
1510 verbose(env, ",%d", state->refs[i].id);
1511 }
bfc6bb74
AS
1512 if (state->in_callback_fn)
1513 verbose(env, " cb");
1514 if (state->in_async_callback_fn)
1515 verbose(env, " async_cb");
61bd5218 1516 verbose(env, "\n");
0f55f9ed 1517 mark_verifier_state_clean(env);
17a52670
AS
1518}
1519
2e576648
CL
1520static inline u32 vlog_alignment(u32 pos)
1521{
1522 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1523 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1524}
1525
1526static void print_insn_state(struct bpf_verifier_env *env,
1527 const struct bpf_func_state *state)
1528{
12166409 1529 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
2e576648 1530 /* remove new line character */
12166409
AN
1531 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1532 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
2e576648
CL
1533 } else {
1534 verbose(env, "%d:", env->insn_idx);
1535 }
1536 print_verifier_state(env, state, false);
17a52670
AS
1537}
1538
c69431aa
LB
1539/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1540 * small to hold src. This is different from krealloc since we don't want to preserve
1541 * the contents of dst.
1542 *
1543 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1544 * not be allocated.
638f5b90 1545 */
c69431aa 1546static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 1547{
45435d8d
KC
1548 size_t alloc_bytes;
1549 void *orig = dst;
c69431aa
LB
1550 size_t bytes;
1551
1552 if (ZERO_OR_NULL_PTR(src))
1553 goto out;
1554
1555 if (unlikely(check_mul_overflow(n, size, &bytes)))
1556 return NULL;
1557
45435d8d
KC
1558 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1559 dst = krealloc(orig, alloc_bytes, flags);
1560 if (!dst) {
1561 kfree(orig);
1562 return NULL;
c69431aa
LB
1563 }
1564
1565 memcpy(dst, src, bytes);
1566out:
1567 return dst ? dst : ZERO_SIZE_PTR;
1568}
1569
1570/* resize an array from old_n items to new_n items. the array is reallocated if it's too
1571 * small to hold new_n items. new items are zeroed out if the array grows.
1572 *
1573 * Contrary to krealloc_array, does not free arr if new_n is zero.
1574 */
1575static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1576{
ceb35b66 1577 size_t alloc_size;
42378a9c
KC
1578 void *new_arr;
1579
c69431aa
LB
1580 if (!new_n || old_n == new_n)
1581 goto out;
1582
ceb35b66
KC
1583 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1584 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
42378a9c
KC
1585 if (!new_arr) {
1586 kfree(arr);
c69431aa 1587 return NULL;
42378a9c
KC
1588 }
1589 arr = new_arr;
c69431aa
LB
1590
1591 if (new_n > old_n)
1592 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1593
1594out:
1595 return arr ? arr : ZERO_SIZE_PTR;
1596}
1597
1598static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1599{
1600 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1601 sizeof(struct bpf_reference_state), GFP_KERNEL);
1602 if (!dst->refs)
1603 return -ENOMEM;
1604
1605 dst->acquired_refs = src->acquired_refs;
1606 return 0;
1607}
1608
1609static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1610{
1611 size_t n = src->allocated_stack / BPF_REG_SIZE;
1612
1613 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1614 GFP_KERNEL);
1615 if (!dst->stack)
1616 return -ENOMEM;
1617
1618 dst->allocated_stack = src->allocated_stack;
1619 return 0;
1620}
1621
1622static int resize_reference_state(struct bpf_func_state *state, size_t n)
1623{
1624 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1625 sizeof(struct bpf_reference_state));
1626 if (!state->refs)
1627 return -ENOMEM;
1628
1629 state->acquired_refs = n;
1630 return 0;
1631}
1632
1633static int grow_stack_state(struct bpf_func_state *state, int size)
1634{
1635 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1636
1637 if (old_n >= n)
1638 return 0;
1639
1640 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1641 if (!state->stack)
1642 return -ENOMEM;
1643
1644 state->allocated_stack = size;
1645 return 0;
fd978bf7
JS
1646}
1647
1648/* Acquire a pointer id from the env and update the state->refs to include
1649 * this new pointer reference.
1650 * On success, returns a valid pointer id to associate with the register
1651 * On failure, returns a negative errno.
638f5b90 1652 */
fd978bf7 1653static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 1654{
fd978bf7
JS
1655 struct bpf_func_state *state = cur_func(env);
1656 int new_ofs = state->acquired_refs;
1657 int id, err;
1658
c69431aa 1659 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
1660 if (err)
1661 return err;
1662 id = ++env->id_gen;
1663 state->refs[new_ofs].id = id;
1664 state->refs[new_ofs].insn_idx = insn_idx;
9d9d00ac 1665 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
638f5b90 1666
fd978bf7
JS
1667 return id;
1668}
1669
1670/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 1671static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
1672{
1673 int i, last_idx;
1674
fd978bf7
JS
1675 last_idx = state->acquired_refs - 1;
1676 for (i = 0; i < state->acquired_refs; i++) {
1677 if (state->refs[i].id == ptr_id) {
9d9d00ac
KKD
1678 /* Cannot release caller references in callbacks */
1679 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1680 return -EINVAL;
fd978bf7
JS
1681 if (last_idx && i != last_idx)
1682 memcpy(&state->refs[i], &state->refs[last_idx],
1683 sizeof(*state->refs));
1684 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1685 state->acquired_refs--;
638f5b90 1686 return 0;
638f5b90 1687 }
638f5b90 1688 }
46f8bc92 1689 return -EINVAL;
fd978bf7
JS
1690}
1691
f4d7e40a
AS
1692static void free_func_state(struct bpf_func_state *state)
1693{
5896351e
AS
1694 if (!state)
1695 return;
fd978bf7 1696 kfree(state->refs);
f4d7e40a
AS
1697 kfree(state->stack);
1698 kfree(state);
1699}
1700
b5dc0163
AS
1701static void clear_jmp_history(struct bpf_verifier_state *state)
1702{
1703 kfree(state->jmp_history);
1704 state->jmp_history = NULL;
1705 state->jmp_history_cnt = 0;
1706}
1707
1969db47
AS
1708static void free_verifier_state(struct bpf_verifier_state *state,
1709 bool free_self)
638f5b90 1710{
f4d7e40a
AS
1711 int i;
1712
1713 for (i = 0; i <= state->curframe; i++) {
1714 free_func_state(state->frame[i]);
1715 state->frame[i] = NULL;
1716 }
b5dc0163 1717 clear_jmp_history(state);
1969db47
AS
1718 if (free_self)
1719 kfree(state);
638f5b90
AS
1720}
1721
1722/* copy verifier state from src to dst growing dst stack space
1723 * when necessary to accommodate larger src stack
1724 */
f4d7e40a
AS
1725static int copy_func_state(struct bpf_func_state *dst,
1726 const struct bpf_func_state *src)
638f5b90
AS
1727{
1728 int err;
1729
fd978bf7
JS
1730 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1731 err = copy_reference_state(dst, src);
638f5b90
AS
1732 if (err)
1733 return err;
638f5b90
AS
1734 return copy_stack_state(dst, src);
1735}
1736
f4d7e40a
AS
1737static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1738 const struct bpf_verifier_state *src)
1739{
1740 struct bpf_func_state *dst;
1741 int i, err;
1742
06ab6a50
LB
1743 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1744 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1745 GFP_USER);
1746 if (!dst_state->jmp_history)
1747 return -ENOMEM;
b5dc0163
AS
1748 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1749
f4d7e40a
AS
1750 /* if dst has more stack frames then src frame, free them */
1751 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752 free_func_state(dst_state->frame[i]);
1753 dst_state->frame[i] = NULL;
1754 }
979d63d5 1755 dst_state->speculative = src->speculative;
9bb00b28 1756 dst_state->active_rcu_lock = src->active_rcu_lock;
f4d7e40a 1757 dst_state->curframe = src->curframe;
d0d78c1d
KKD
1758 dst_state->active_lock.ptr = src->active_lock.ptr;
1759 dst_state->active_lock.id = src->active_lock.id;
2589726d
AS
1760 dst_state->branches = src->branches;
1761 dst_state->parent = src->parent;
b5dc0163
AS
1762 dst_state->first_insn_idx = src->first_insn_idx;
1763 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
1764 for (i = 0; i <= src->curframe; i++) {
1765 dst = dst_state->frame[i];
1766 if (!dst) {
1767 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1768 if (!dst)
1769 return -ENOMEM;
1770 dst_state->frame[i] = dst;
1771 }
1772 err = copy_func_state(dst, src->frame[i]);
1773 if (err)
1774 return err;
1775 }
1776 return 0;
1777}
1778
2589726d
AS
1779static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1780{
1781 while (st) {
1782 u32 br = --st->branches;
1783
1784 /* WARN_ON(br > 1) technically makes sense here,
1785 * but see comment in push_stack(), hence:
1786 */
1787 WARN_ONCE((int)br < 0,
1788 "BUG update_branch_counts:branches_to_explore=%d\n",
1789 br);
1790 if (br)
1791 break;
1792 st = st->parent;
1793 }
1794}
1795
638f5b90 1796static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 1797 int *insn_idx, bool pop_log)
638f5b90
AS
1798{
1799 struct bpf_verifier_state *cur = env->cur_state;
1800 struct bpf_verifier_stack_elem *elem, *head = env->head;
1801 int err;
17a52670
AS
1802
1803 if (env->head == NULL)
638f5b90 1804 return -ENOENT;
17a52670 1805
638f5b90
AS
1806 if (cur) {
1807 err = copy_verifier_state(cur, &head->st);
1808 if (err)
1809 return err;
1810 }
6f8a57cc
AN
1811 if (pop_log)
1812 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
1813 if (insn_idx)
1814 *insn_idx = head->insn_idx;
17a52670 1815 if (prev_insn_idx)
638f5b90
AS
1816 *prev_insn_idx = head->prev_insn_idx;
1817 elem = head->next;
1969db47 1818 free_verifier_state(&head->st, false);
638f5b90 1819 kfree(head);
17a52670
AS
1820 env->head = elem;
1821 env->stack_size--;
638f5b90 1822 return 0;
17a52670
AS
1823}
1824
58e2af8b 1825static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1826 int insn_idx, int prev_insn_idx,
1827 bool speculative)
17a52670 1828{
638f5b90 1829 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1830 struct bpf_verifier_stack_elem *elem;
638f5b90 1831 int err;
17a52670 1832
638f5b90 1833 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1834 if (!elem)
1835 goto err;
1836
17a52670
AS
1837 elem->insn_idx = insn_idx;
1838 elem->prev_insn_idx = prev_insn_idx;
1839 elem->next = env->head;
12166409 1840 elem->log_pos = env->log.end_pos;
17a52670
AS
1841 env->head = elem;
1842 env->stack_size++;
1969db47
AS
1843 err = copy_verifier_state(&elem->st, cur);
1844 if (err)
1845 goto err;
979d63d5 1846 elem->st.speculative |= speculative;
b285fcb7
AS
1847 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1848 verbose(env, "The sequence of %d jumps is too complex.\n",
1849 env->stack_size);
17a52670
AS
1850 goto err;
1851 }
2589726d
AS
1852 if (elem->st.parent) {
1853 ++elem->st.parent->branches;
1854 /* WARN_ON(branches > 2) technically makes sense here,
1855 * but
1856 * 1. speculative states will bump 'branches' for non-branch
1857 * instructions
1858 * 2. is_state_visited() heuristics may decide not to create
1859 * a new state for a sequence of branches and all such current
1860 * and cloned states will be pointing to a single parent state
1861 * which might have large 'branches' count.
1862 */
1863 }
17a52670
AS
1864 return &elem->st;
1865err:
5896351e
AS
1866 free_verifier_state(env->cur_state, true);
1867 env->cur_state = NULL;
17a52670 1868 /* pop all elements and return */
6f8a57cc 1869 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1870 return NULL;
1871}
1872
1873#define CALLER_SAVED_REGS 6
1874static const int caller_saved[CALLER_SAVED_REGS] = {
1875 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1876};
1877
e688c3db
AS
1878/* This helper doesn't clear reg->id */
1879static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1880{
b03c9f9f
EC
1881 reg->var_off = tnum_const(imm);
1882 reg->smin_value = (s64)imm;
1883 reg->smax_value = (s64)imm;
1884 reg->umin_value = imm;
1885 reg->umax_value = imm;
3f50f132
JF
1886
1887 reg->s32_min_value = (s32)imm;
1888 reg->s32_max_value = (s32)imm;
1889 reg->u32_min_value = (u32)imm;
1890 reg->u32_max_value = (u32)imm;
1891}
1892
e688c3db
AS
1893/* Mark the unknown part of a register (variable offset or scalar value) as
1894 * known to have the value @imm.
1895 */
1896static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1897{
a73bf9f2 1898 /* Clear off and union(map_ptr, range) */
e688c3db
AS
1899 memset(((u8 *)reg) + sizeof(reg->type), 0,
1900 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
a73bf9f2
AN
1901 reg->id = 0;
1902 reg->ref_obj_id = 0;
e688c3db
AS
1903 ___mark_reg_known(reg, imm);
1904}
1905
3f50f132
JF
1906static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1907{
1908 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1909 reg->s32_min_value = (s32)imm;
1910 reg->s32_max_value = (s32)imm;
1911 reg->u32_min_value = (u32)imm;
1912 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1913}
1914
f1174f77
EC
1915/* Mark the 'variable offset' part of a register as zero. This should be
1916 * used only on registers holding a pointer type.
1917 */
1918static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1919{
b03c9f9f 1920 __mark_reg_known(reg, 0);
f1174f77 1921}
a9789ef9 1922
cc2b14d5
AS
1923static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1924{
1925 __mark_reg_known(reg, 0);
cc2b14d5
AS
1926 reg->type = SCALAR_VALUE;
1927}
1928
61bd5218
JK
1929static void mark_reg_known_zero(struct bpf_verifier_env *env,
1930 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1931{
1932 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1933 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1934 /* Something bad happened, let's kill all regs */
1935 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1936 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1937 return;
1938 }
1939 __mark_reg_known_zero(regs + regno);
1940}
1941
27060531 1942static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
f8064ab9 1943 bool first_slot, int dynptr_id)
27060531
KKD
1944{
1945 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1946 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1947 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1948 */
1949 __mark_reg_known_zero(reg);
1950 reg->type = CONST_PTR_TO_DYNPTR;
f8064ab9
KKD
1951 /* Give each dynptr a unique id to uniquely associate slices to it. */
1952 reg->id = dynptr_id;
27060531
KKD
1953 reg->dynptr.type = type;
1954 reg->dynptr.first_slot = first_slot;
1955}
1956
4ddb7416
DB
1957static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1958{
c25b2ae1 1959 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
4ddb7416
DB
1960 const struct bpf_map *map = reg->map_ptr;
1961
1962 if (map->inner_map_meta) {
1963 reg->type = CONST_PTR_TO_MAP;
1964 reg->map_ptr = map->inner_map_meta;
3e8ce298
AS
1965 /* transfer reg's id which is unique for every map_lookup_elem
1966 * as UID of the inner map.
1967 */
db559117 1968 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
34d11a44 1969 reg->map_uid = reg->id;
4ddb7416
DB
1970 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1971 reg->type = PTR_TO_XDP_SOCK;
1972 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1973 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1974 reg->type = PTR_TO_SOCKET;
1975 } else {
1976 reg->type = PTR_TO_MAP_VALUE;
1977 }
c25b2ae1 1978 return;
4ddb7416 1979 }
c25b2ae1
HL
1980
1981 reg->type &= ~PTR_MAYBE_NULL;
4ddb7416
DB
1982}
1983
5d92ddc3
DM
1984static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1985 struct btf_field_graph_root *ds_head)
1986{
1987 __mark_reg_known_zero(&regs[regno]);
1988 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1989 regs[regno].btf = ds_head->btf;
1990 regs[regno].btf_id = ds_head->value_btf_id;
1991 regs[regno].off = ds_head->node_offset;
1992}
1993
de8f3a83
DB
1994static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1995{
1996 return type_is_pkt_pointer(reg->type);
1997}
1998
1999static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2000{
2001 return reg_is_pkt_pointer(reg) ||
2002 reg->type == PTR_TO_PACKET_END;
2003}
2004
66e3a13e
JK
2005static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2006{
2007 return base_type(reg->type) == PTR_TO_MEM &&
2008 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2009}
2010
de8f3a83
DB
2011/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2012static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2013 enum bpf_reg_type which)
2014{
2015 /* The register can already have a range from prior markings.
2016 * This is fine as long as it hasn't been advanced from its
2017 * origin.
2018 */
2019 return reg->type == which &&
2020 reg->id == 0 &&
2021 reg->off == 0 &&
2022 tnum_equals_const(reg->var_off, 0);
2023}
2024
3f50f132
JF
2025/* Reset the min/max bounds of a register */
2026static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2027{
2028 reg->smin_value = S64_MIN;
2029 reg->smax_value = S64_MAX;
2030 reg->umin_value = 0;
2031 reg->umax_value = U64_MAX;
2032
2033 reg->s32_min_value = S32_MIN;
2034 reg->s32_max_value = S32_MAX;
2035 reg->u32_min_value = 0;
2036 reg->u32_max_value = U32_MAX;
2037}
2038
2039static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2040{
2041 reg->smin_value = S64_MIN;
2042 reg->smax_value = S64_MAX;
2043 reg->umin_value = 0;
2044 reg->umax_value = U64_MAX;
2045}
2046
2047static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2048{
2049 reg->s32_min_value = S32_MIN;
2050 reg->s32_max_value = S32_MAX;
2051 reg->u32_min_value = 0;
2052 reg->u32_max_value = U32_MAX;
2053}
2054
2055static void __update_reg32_bounds(struct bpf_reg_state *reg)
2056{
2057 struct tnum var32_off = tnum_subreg(reg->var_off);
2058
2059 /* min signed is max(sign bit) | min(other bits) */
2060 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2061 var32_off.value | (var32_off.mask & S32_MIN));
2062 /* max signed is min(sign bit) | max(other bits) */
2063 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2064 var32_off.value | (var32_off.mask & S32_MAX));
2065 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2066 reg->u32_max_value = min(reg->u32_max_value,
2067 (u32)(var32_off.value | var32_off.mask));
2068}
2069
2070static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
2071{
2072 /* min signed is max(sign bit) | min(other bits) */
2073 reg->smin_value = max_t(s64, reg->smin_value,
2074 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2075 /* max signed is min(sign bit) | max(other bits) */
2076 reg->smax_value = min_t(s64, reg->smax_value,
2077 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2078 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2079 reg->umax_value = min(reg->umax_value,
2080 reg->var_off.value | reg->var_off.mask);
2081}
2082
3f50f132
JF
2083static void __update_reg_bounds(struct bpf_reg_state *reg)
2084{
2085 __update_reg32_bounds(reg);
2086 __update_reg64_bounds(reg);
2087}
2088
b03c9f9f 2089/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
2090static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2091{
2092 /* Learn sign from signed bounds.
2093 * If we cannot cross the sign boundary, then signed and unsigned bounds
2094 * are the same, so combine. This works even in the negative case, e.g.
2095 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2096 */
2097 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2098 reg->s32_min_value = reg->u32_min_value =
2099 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2100 reg->s32_max_value = reg->u32_max_value =
2101 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2102 return;
2103 }
2104 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2105 * boundary, so we must be careful.
2106 */
2107 if ((s32)reg->u32_max_value >= 0) {
2108 /* Positive. We can't learn anything from the smin, but smax
2109 * is positive, hence safe.
2110 */
2111 reg->s32_min_value = reg->u32_min_value;
2112 reg->s32_max_value = reg->u32_max_value =
2113 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2114 } else if ((s32)reg->u32_min_value < 0) {
2115 /* Negative. We can't learn anything from the smax, but smin
2116 * is negative, hence safe.
2117 */
2118 reg->s32_min_value = reg->u32_min_value =
2119 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2120 reg->s32_max_value = reg->u32_max_value;
2121 }
2122}
2123
2124static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
2125{
2126 /* Learn sign from signed bounds.
2127 * If we cannot cross the sign boundary, then signed and unsigned bounds
2128 * are the same, so combine. This works even in the negative case, e.g.
2129 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2130 */
2131 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2132 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2133 reg->umin_value);
2134 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2135 reg->umax_value);
2136 return;
2137 }
2138 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2139 * boundary, so we must be careful.
2140 */
2141 if ((s64)reg->umax_value >= 0) {
2142 /* Positive. We can't learn anything from the smin, but smax
2143 * is positive, hence safe.
2144 */
2145 reg->smin_value = reg->umin_value;
2146 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2147 reg->umax_value);
2148 } else if ((s64)reg->umin_value < 0) {
2149 /* Negative. We can't learn anything from the smax, but smin
2150 * is negative, hence safe.
2151 */
2152 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2153 reg->umin_value);
2154 reg->smax_value = reg->umax_value;
2155 }
2156}
2157
3f50f132
JF
2158static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2159{
2160 __reg32_deduce_bounds(reg);
2161 __reg64_deduce_bounds(reg);
2162}
2163
b03c9f9f
EC
2164/* Attempts to improve var_off based on unsigned min/max information */
2165static void __reg_bound_offset(struct bpf_reg_state *reg)
2166{
3f50f132
JF
2167 struct tnum var64_off = tnum_intersect(reg->var_off,
2168 tnum_range(reg->umin_value,
2169 reg->umax_value));
7be14c1c
DB
2170 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2171 tnum_range(reg->u32_min_value,
2172 reg->u32_max_value));
3f50f132
JF
2173
2174 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
2175}
2176
3844d153
DB
2177static void reg_bounds_sync(struct bpf_reg_state *reg)
2178{
2179 /* We might have learned new bounds from the var_off. */
2180 __update_reg_bounds(reg);
2181 /* We might have learned something about the sign bit. */
2182 __reg_deduce_bounds(reg);
2183 /* We might have learned some bits from the bounds. */
2184 __reg_bound_offset(reg);
2185 /* Intersecting with the old var_off might have improved our bounds
2186 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187 * then new var_off is (0; 0x7f...fc) which improves our umax.
2188 */
2189 __update_reg_bounds(reg);
2190}
2191
e572ff80
DB
2192static bool __reg32_bound_s64(s32 a)
2193{
2194 return a >= 0 && a <= S32_MAX;
2195}
2196
3f50f132 2197static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 2198{
3f50f132
JF
2199 reg->umin_value = reg->u32_min_value;
2200 reg->umax_value = reg->u32_max_value;
e572ff80
DB
2201
2202 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2203 * be positive otherwise set to worse case bounds and refine later
2204 * from tnum.
3f50f132 2205 */
e572ff80
DB
2206 if (__reg32_bound_s64(reg->s32_min_value) &&
2207 __reg32_bound_s64(reg->s32_max_value)) {
3a71dc36 2208 reg->smin_value = reg->s32_min_value;
e572ff80
DB
2209 reg->smax_value = reg->s32_max_value;
2210 } else {
3a71dc36 2211 reg->smin_value = 0;
e572ff80
DB
2212 reg->smax_value = U32_MAX;
2213 }
3f50f132
JF
2214}
2215
2216static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2217{
2218 /* special case when 64-bit register has upper 32-bit register
2219 * zeroed. Typically happens after zext or <<32, >>32 sequence
2220 * allowing us to use 32-bit bounds directly,
2221 */
2222 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2223 __reg_assign_32_into_64(reg);
2224 } else {
2225 /* Otherwise the best we can do is push lower 32bit known and
2226 * unknown bits into register (var_off set from jmp logic)
2227 * then learn as much as possible from the 64-bit tnum
2228 * known and unknown bits. The previous smin/smax bounds are
2229 * invalid here because of jmp32 compare so mark them unknown
2230 * so they do not impact tnum bounds calculation.
2231 */
2232 __mark_reg64_unbounded(reg);
3f50f132 2233 }
3844d153 2234 reg_bounds_sync(reg);
3f50f132
JF
2235}
2236
2237static bool __reg64_bound_s32(s64 a)
2238{
388e2c0b 2239 return a >= S32_MIN && a <= S32_MAX;
3f50f132
JF
2240}
2241
2242static bool __reg64_bound_u32(u64 a)
2243{
b9979db8 2244 return a >= U32_MIN && a <= U32_MAX;
3f50f132
JF
2245}
2246
2247static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2248{
2249 __mark_reg32_unbounded(reg);
b0270958 2250 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 2251 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 2252 reg->s32_max_value = (s32)reg->smax_value;
b0270958 2253 }
10bf4e83 2254 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 2255 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 2256 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 2257 }
3844d153 2258 reg_bounds_sync(reg);
b03c9f9f
EC
2259}
2260
f1174f77 2261/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
2262static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2263 struct bpf_reg_state *reg)
f1174f77 2264{
a9c676bc 2265 /*
a73bf9f2 2266 * Clear type, off, and union(map_ptr, range) and
a9c676bc
AS
2267 * padding between 'type' and union
2268 */
2269 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 2270 reg->type = SCALAR_VALUE;
a73bf9f2
AN
2271 reg->id = 0;
2272 reg->ref_obj_id = 0;
f1174f77 2273 reg->var_off = tnum_unknown;
f4d7e40a 2274 reg->frameno = 0;
be2ef816 2275 reg->precise = !env->bpf_capable;
b03c9f9f 2276 __mark_reg_unbounded(reg);
f1174f77
EC
2277}
2278
61bd5218
JK
2279static void mark_reg_unknown(struct bpf_verifier_env *env,
2280 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2281{
2282 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2283 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
2284 /* Something bad happened, let's kill all regs except FP */
2285 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 2286 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2287 return;
2288 }
f54c7898 2289 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
2290}
2291
f54c7898
DB
2292static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2293 struct bpf_reg_state *reg)
f1174f77 2294{
f54c7898 2295 __mark_reg_unknown(env, reg);
f1174f77
EC
2296 reg->type = NOT_INIT;
2297}
2298
61bd5218
JK
2299static void mark_reg_not_init(struct bpf_verifier_env *env,
2300 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
2301{
2302 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 2303 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
2304 /* Something bad happened, let's kill all regs except FP */
2305 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 2306 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
2307 return;
2308 }
f54c7898 2309 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
2310}
2311
41c48f3a
AI
2312static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2313 struct bpf_reg_state *regs, u32 regno,
22dc4a0f 2314 enum bpf_reg_type reg_type,
c6f1bfe8
YS
2315 struct btf *btf, u32 btf_id,
2316 enum bpf_type_flag flag)
41c48f3a
AI
2317{
2318 if (reg_type == SCALAR_VALUE) {
2319 mark_reg_unknown(env, regs, regno);
2320 return;
2321 }
2322 mark_reg_known_zero(env, regs, regno);
c6f1bfe8 2323 regs[regno].type = PTR_TO_BTF_ID | flag;
22dc4a0f 2324 regs[regno].btf = btf;
41c48f3a
AI
2325 regs[regno].btf_id = btf_id;
2326}
2327
5327ed3d 2328#define DEF_NOT_SUBREG (0)
61bd5218 2329static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 2330 struct bpf_func_state *state)
17a52670 2331{
f4d7e40a 2332 struct bpf_reg_state *regs = state->regs;
17a52670
AS
2333 int i;
2334
dc503a8a 2335 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 2336 mark_reg_not_init(env, regs, i);
dc503a8a 2337 regs[i].live = REG_LIVE_NONE;
679c782d 2338 regs[i].parent = NULL;
5327ed3d 2339 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 2340 }
17a52670
AS
2341
2342 /* frame pointer */
f1174f77 2343 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 2344 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 2345 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
2346}
2347
f4d7e40a
AS
2348#define BPF_MAIN_FUNC (-1)
2349static void init_func_state(struct bpf_verifier_env *env,
2350 struct bpf_func_state *state,
2351 int callsite, int frameno, int subprogno)
2352{
2353 state->callsite = callsite;
2354 state->frameno = frameno;
2355 state->subprogno = subprogno;
1bfe26fb 2356 state->callback_ret_range = tnum_range(0, 0);
f4d7e40a 2357 init_reg_state(env, state);
0f55f9ed 2358 mark_verifier_state_scratched(env);
f4d7e40a
AS
2359}
2360
bfc6bb74
AS
2361/* Similar to push_stack(), but for async callbacks */
2362static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2363 int insn_idx, int prev_insn_idx,
2364 int subprog)
2365{
2366 struct bpf_verifier_stack_elem *elem;
2367 struct bpf_func_state *frame;
2368
2369 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2370 if (!elem)
2371 goto err;
2372
2373 elem->insn_idx = insn_idx;
2374 elem->prev_insn_idx = prev_insn_idx;
2375 elem->next = env->head;
12166409 2376 elem->log_pos = env->log.end_pos;
bfc6bb74
AS
2377 env->head = elem;
2378 env->stack_size++;
2379 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2380 verbose(env,
2381 "The sequence of %d jumps is too complex for async cb.\n",
2382 env->stack_size);
2383 goto err;
2384 }
2385 /* Unlike push_stack() do not copy_verifier_state().
2386 * The caller state doesn't matter.
2387 * This is async callback. It starts in a fresh stack.
2388 * Initialize it similar to do_check_common().
2389 */
2390 elem->st.branches = 1;
2391 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2392 if (!frame)
2393 goto err;
2394 init_func_state(env, frame,
2395 BPF_MAIN_FUNC /* callsite */,
2396 0 /* frameno within this callchain */,
2397 subprog /* subprog number within this prog */);
2398 elem->st.frame[0] = frame;
2399 return &elem->st;
2400err:
2401 free_verifier_state(env->cur_state, true);
2402 env->cur_state = NULL;
2403 /* pop all elements and return */
2404 while (!pop_stack(env, NULL, NULL, false));
2405 return NULL;
2406}
2407
2408
17a52670
AS
2409enum reg_arg_type {
2410 SRC_OP, /* register is used as source operand */
2411 DST_OP, /* register is used as destination operand */
2412 DST_OP_NO_MARK /* same as above, check only, don't mark */
2413};
2414
cc8b0b92
AS
2415static int cmp_subprogs(const void *a, const void *b)
2416{
9c8105bd
JW
2417 return ((struct bpf_subprog_info *)a)->start -
2418 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
2419}
2420
2421static int find_subprog(struct bpf_verifier_env *env, int off)
2422{
9c8105bd 2423 struct bpf_subprog_info *p;
cc8b0b92 2424
9c8105bd
JW
2425 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2426 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
2427 if (!p)
2428 return -ENOENT;
9c8105bd 2429 return p - env->subprog_info;
cc8b0b92
AS
2430
2431}
2432
2433static int add_subprog(struct bpf_verifier_env *env, int off)
2434{
2435 int insn_cnt = env->prog->len;
2436 int ret;
2437
2438 if (off >= insn_cnt || off < 0) {
2439 verbose(env, "call to invalid destination\n");
2440 return -EINVAL;
2441 }
2442 ret = find_subprog(env, off);
2443 if (ret >= 0)
282a0f46 2444 return ret;
4cb3d99c 2445 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
2446 verbose(env, "too many subprograms\n");
2447 return -E2BIG;
2448 }
e6ac2450 2449 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
2450 env->subprog_info[env->subprog_cnt++].start = off;
2451 sort(env->subprog_info, env->subprog_cnt,
2452 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 2453 return env->subprog_cnt - 1;
cc8b0b92
AS
2454}
2455
2357672c
KKD
2456#define MAX_KFUNC_DESCS 256
2457#define MAX_KFUNC_BTFS 256
2458
e6ac2450
MKL
2459struct bpf_kfunc_desc {
2460 struct btf_func_model func_model;
2461 u32 func_id;
2462 s32 imm;
2357672c 2463 u16 offset;
1cf3bfc6 2464 unsigned long addr;
2357672c
KKD
2465};
2466
2467struct bpf_kfunc_btf {
2468 struct btf *btf;
2469 struct module *module;
2470 u16 offset;
e6ac2450
MKL
2471};
2472
e6ac2450 2473struct bpf_kfunc_desc_tab {
1cf3bfc6
IL
2474 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2475 * verification. JITs do lookups by bpf_insn, where func_id may not be
2476 * available, therefore at the end of verification do_misc_fixups()
2477 * sorts this by imm and offset.
2478 */
e6ac2450
MKL
2479 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2480 u32 nr_descs;
2481};
2482
2357672c
KKD
2483struct bpf_kfunc_btf_tab {
2484 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2485 u32 nr_descs;
2486};
2487
2488static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
e6ac2450
MKL
2489{
2490 const struct bpf_kfunc_desc *d0 = a;
2491 const struct bpf_kfunc_desc *d1 = b;
2492
2493 /* func_id is not greater than BTF_MAX_TYPE */
2357672c
KKD
2494 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2495}
2496
2497static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2498{
2499 const struct bpf_kfunc_btf *d0 = a;
2500 const struct bpf_kfunc_btf *d1 = b;
2501
2502 return d0->offset - d1->offset;
e6ac2450
MKL
2503}
2504
2505static const struct bpf_kfunc_desc *
2357672c 2506find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
e6ac2450
MKL
2507{
2508 struct bpf_kfunc_desc desc = {
2509 .func_id = func_id,
2357672c 2510 .offset = offset,
e6ac2450
MKL
2511 };
2512 struct bpf_kfunc_desc_tab *tab;
2513
2514 tab = prog->aux->kfunc_tab;
2515 return bsearch(&desc, tab->descs, tab->nr_descs,
2357672c
KKD
2516 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2517}
2518
1cf3bfc6
IL
2519int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2520 u16 btf_fd_idx, u8 **func_addr)
2521{
2522 const struct bpf_kfunc_desc *desc;
2523
2524 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2525 if (!desc)
2526 return -EFAULT;
2527
2528 *func_addr = (u8 *)desc->addr;
2529 return 0;
2530}
2531
2357672c 2532static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
b202d844 2533 s16 offset)
2357672c
KKD
2534{
2535 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2536 struct bpf_kfunc_btf_tab *tab;
2537 struct bpf_kfunc_btf *b;
2538 struct module *mod;
2539 struct btf *btf;
2540 int btf_fd;
2541
2542 tab = env->prog->aux->kfunc_btf_tab;
2543 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2544 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2545 if (!b) {
2546 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2547 verbose(env, "too many different module BTFs\n");
2548 return ERR_PTR(-E2BIG);
2549 }
2550
2551 if (bpfptr_is_null(env->fd_array)) {
2552 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2553 return ERR_PTR(-EPROTO);
2554 }
2555
2556 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2557 offset * sizeof(btf_fd),
2558 sizeof(btf_fd)))
2559 return ERR_PTR(-EFAULT);
2560
2561 btf = btf_get_by_fd(btf_fd);
588cd7ef
KKD
2562 if (IS_ERR(btf)) {
2563 verbose(env, "invalid module BTF fd specified\n");
2357672c 2564 return btf;
588cd7ef 2565 }
2357672c
KKD
2566
2567 if (!btf_is_module(btf)) {
2568 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2569 btf_put(btf);
2570 return ERR_PTR(-EINVAL);
2571 }
2572
2573 mod = btf_try_get_module(btf);
2574 if (!mod) {
2575 btf_put(btf);
2576 return ERR_PTR(-ENXIO);
2577 }
2578
2579 b = &tab->descs[tab->nr_descs++];
2580 b->btf = btf;
2581 b->module = mod;
2582 b->offset = offset;
2583
2584 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2585 kfunc_btf_cmp_by_off, NULL);
2586 }
2357672c 2587 return b->btf;
e6ac2450
MKL
2588}
2589
2357672c
KKD
2590void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2591{
2592 if (!tab)
2593 return;
2594
2595 while (tab->nr_descs--) {
2596 module_put(tab->descs[tab->nr_descs].module);
2597 btf_put(tab->descs[tab->nr_descs].btf);
2598 }
2599 kfree(tab);
2600}
2601
43bf0878 2602static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2357672c 2603{
2357672c
KKD
2604 if (offset) {
2605 if (offset < 0) {
2606 /* In the future, this can be allowed to increase limit
2607 * of fd index into fd_array, interpreted as u16.
2608 */
2609 verbose(env, "negative offset disallowed for kernel module function call\n");
2610 return ERR_PTR(-EINVAL);
2611 }
2612
b202d844 2613 return __find_kfunc_desc_btf(env, offset);
2357672c
KKD
2614 }
2615 return btf_vmlinux ?: ERR_PTR(-ENOENT);
e6ac2450
MKL
2616}
2617
2357672c 2618static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
e6ac2450
MKL
2619{
2620 const struct btf_type *func, *func_proto;
2357672c 2621 struct bpf_kfunc_btf_tab *btf_tab;
e6ac2450
MKL
2622 struct bpf_kfunc_desc_tab *tab;
2623 struct bpf_prog_aux *prog_aux;
2624 struct bpf_kfunc_desc *desc;
2625 const char *func_name;
2357672c 2626 struct btf *desc_btf;
8cbf062a 2627 unsigned long call_imm;
e6ac2450
MKL
2628 unsigned long addr;
2629 int err;
2630
2631 prog_aux = env->prog->aux;
2632 tab = prog_aux->kfunc_tab;
2357672c 2633 btf_tab = prog_aux->kfunc_btf_tab;
e6ac2450
MKL
2634 if (!tab) {
2635 if (!btf_vmlinux) {
2636 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2637 return -ENOTSUPP;
2638 }
2639
2640 if (!env->prog->jit_requested) {
2641 verbose(env, "JIT is required for calling kernel function\n");
2642 return -ENOTSUPP;
2643 }
2644
2645 if (!bpf_jit_supports_kfunc_call()) {
2646 verbose(env, "JIT does not support calling kernel function\n");
2647 return -ENOTSUPP;
2648 }
2649
2650 if (!env->prog->gpl_compatible) {
2651 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2652 return -EINVAL;
2653 }
2654
2655 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2656 if (!tab)
2657 return -ENOMEM;
2658 prog_aux->kfunc_tab = tab;
2659 }
2660
a5d82727
KKD
2661 /* func_id == 0 is always invalid, but instead of returning an error, be
2662 * conservative and wait until the code elimination pass before returning
2663 * error, so that invalid calls that get pruned out can be in BPF programs
2664 * loaded from userspace. It is also required that offset be untouched
2665 * for such calls.
2666 */
2667 if (!func_id && !offset)
2668 return 0;
2669
2357672c
KKD
2670 if (!btf_tab && offset) {
2671 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2672 if (!btf_tab)
2673 return -ENOMEM;
2674 prog_aux->kfunc_btf_tab = btf_tab;
2675 }
2676
43bf0878 2677 desc_btf = find_kfunc_desc_btf(env, offset);
2357672c
KKD
2678 if (IS_ERR(desc_btf)) {
2679 verbose(env, "failed to find BTF for kernel function\n");
2680 return PTR_ERR(desc_btf);
2681 }
2682
2683 if (find_kfunc_desc(env->prog, func_id, offset))
e6ac2450
MKL
2684 return 0;
2685
2686 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2687 verbose(env, "too many different kernel function calls\n");
2688 return -E2BIG;
2689 }
2690
2357672c 2691 func = btf_type_by_id(desc_btf, func_id);
e6ac2450
MKL
2692 if (!func || !btf_type_is_func(func)) {
2693 verbose(env, "kernel btf_id %u is not a function\n",
2694 func_id);
2695 return -EINVAL;
2696 }
2357672c 2697 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450
MKL
2698 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2699 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2700 func_id);
2701 return -EINVAL;
2702 }
2703
2357672c 2704 func_name = btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
2705 addr = kallsyms_lookup_name(func_name);
2706 if (!addr) {
2707 verbose(env, "cannot find address for kernel function %s\n",
2708 func_name);
2709 return -EINVAL;
2710 }
1cf3bfc6 2711 specialize_kfunc(env, func_id, offset, &addr);
e6ac2450 2712
1cf3bfc6
IL
2713 if (bpf_jit_supports_far_kfunc_call()) {
2714 call_imm = func_id;
2715 } else {
2716 call_imm = BPF_CALL_IMM(addr);
2717 /* Check whether the relative offset overflows desc->imm */
2718 if ((unsigned long)(s32)call_imm != call_imm) {
2719 verbose(env, "address of kernel function %s is out of range\n",
2720 func_name);
2721 return -EINVAL;
2722 }
8cbf062a
HT
2723 }
2724
3d76a4d3
SF
2725 if (bpf_dev_bound_kfunc_id(func_id)) {
2726 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2727 if (err)
2728 return err;
2729 }
2730
e6ac2450
MKL
2731 desc = &tab->descs[tab->nr_descs++];
2732 desc->func_id = func_id;
8cbf062a 2733 desc->imm = call_imm;
2357672c 2734 desc->offset = offset;
1cf3bfc6 2735 desc->addr = addr;
2357672c 2736 err = btf_distill_func_proto(&env->log, desc_btf,
e6ac2450
MKL
2737 func_proto, func_name,
2738 &desc->func_model);
2739 if (!err)
2740 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2357672c 2741 kfunc_desc_cmp_by_id_off, NULL);
e6ac2450
MKL
2742 return err;
2743}
2744
1cf3bfc6 2745static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
e6ac2450
MKL
2746{
2747 const struct bpf_kfunc_desc *d0 = a;
2748 const struct bpf_kfunc_desc *d1 = b;
2749
1cf3bfc6
IL
2750 if (d0->imm != d1->imm)
2751 return d0->imm < d1->imm ? -1 : 1;
2752 if (d0->offset != d1->offset)
2753 return d0->offset < d1->offset ? -1 : 1;
e6ac2450
MKL
2754 return 0;
2755}
2756
1cf3bfc6 2757static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
e6ac2450
MKL
2758{
2759 struct bpf_kfunc_desc_tab *tab;
2760
2761 tab = prog->aux->kfunc_tab;
2762 if (!tab)
2763 return;
2764
2765 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1cf3bfc6 2766 kfunc_desc_cmp_by_imm_off, NULL);
e6ac2450
MKL
2767}
2768
2769bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2770{
2771 return !!prog->aux->kfunc_tab;
2772}
2773
2774const struct btf_func_model *
2775bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2776 const struct bpf_insn *insn)
2777{
2778 const struct bpf_kfunc_desc desc = {
2779 .imm = insn->imm,
1cf3bfc6 2780 .offset = insn->off,
e6ac2450
MKL
2781 };
2782 const struct bpf_kfunc_desc *res;
2783 struct bpf_kfunc_desc_tab *tab;
2784
2785 tab = prog->aux->kfunc_tab;
2786 res = bsearch(&desc, tab->descs, tab->nr_descs,
1cf3bfc6 2787 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
e6ac2450
MKL
2788
2789 return res ? &res->func_model : NULL;
2790}
2791
2792static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 2793{
9c8105bd 2794 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 2795 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 2796 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 2797
f910cefa
JW
2798 /* Add entry function. */
2799 ret = add_subprog(env, 0);
e6ac2450 2800 if (ret)
f910cefa
JW
2801 return ret;
2802
e6ac2450
MKL
2803 for (i = 0; i < insn_cnt; i++, insn++) {
2804 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2805 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 2806 continue;
e6ac2450 2807
2c78ee89 2808 if (!env->bpf_capable) {
e6ac2450 2809 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
2810 return -EPERM;
2811 }
e6ac2450 2812
3990ed4c 2813 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
e6ac2450 2814 ret = add_subprog(env, i + insn->imm + 1);
3990ed4c 2815 else
2357672c 2816 ret = add_kfunc_call(env, insn->imm, insn->off);
e6ac2450 2817
cc8b0b92
AS
2818 if (ret < 0)
2819 return ret;
2820 }
2821
4cb3d99c
JW
2822 /* Add a fake 'exit' subprog which could simplify subprog iteration
2823 * logic. 'subprog_cnt' should not be increased.
2824 */
2825 subprog[env->subprog_cnt].start = insn_cnt;
2826
06ee7115 2827 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 2828 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 2829 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 2830
e6ac2450
MKL
2831 return 0;
2832}
2833
2834static int check_subprogs(struct bpf_verifier_env *env)
2835{
2836 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2837 struct bpf_subprog_info *subprog = env->subprog_info;
2838 struct bpf_insn *insn = env->prog->insnsi;
2839 int insn_cnt = env->prog->len;
2840
cc8b0b92 2841 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
2842 subprog_start = subprog[cur_subprog].start;
2843 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2844 for (i = 0; i < insn_cnt; i++) {
2845 u8 code = insn[i].code;
2846
7f6e4312 2847 if (code == (BPF_JMP | BPF_CALL) &&
df2ccc18
IL
2848 insn[i].src_reg == 0 &&
2849 insn[i].imm == BPF_FUNC_tail_call)
7f6e4312 2850 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
2851 if (BPF_CLASS(code) == BPF_LD &&
2852 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2853 subprog[cur_subprog].has_ld_abs = true;
092ed096 2854 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
2855 goto next;
2856 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2857 goto next;
2858 off = i + insn[i].off + 1;
2859 if (off < subprog_start || off >= subprog_end) {
2860 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2861 return -EINVAL;
2862 }
2863next:
2864 if (i == subprog_end - 1) {
2865 /* to avoid fall-through from one subprog into another
2866 * the last insn of the subprog should be either exit
2867 * or unconditional jump back
2868 */
2869 if (code != (BPF_JMP | BPF_EXIT) &&
2870 code != (BPF_JMP | BPF_JA)) {
2871 verbose(env, "last insn is not an exit or jmp\n");
2872 return -EINVAL;
2873 }
2874 subprog_start = subprog_end;
4cb3d99c
JW
2875 cur_subprog++;
2876 if (cur_subprog < env->subprog_cnt)
9c8105bd 2877 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2878 }
2879 }
2880 return 0;
2881}
2882
679c782d
EC
2883/* Parentage chain of this register (or stack slot) should take care of all
2884 * issues like callee-saved registers, stack slot allocation time, etc.
2885 */
f4d7e40a 2886static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 2887 const struct bpf_reg_state *state,
5327ed3d 2888 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
2889{
2890 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 2891 int cnt = 0;
dc503a8a
EC
2892
2893 while (parent) {
2894 /* if read wasn't screened by an earlier write ... */
679c782d 2895 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 2896 break;
9242b5f5
AS
2897 if (parent->live & REG_LIVE_DONE) {
2898 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
c25b2ae1 2899 reg_type_str(env, parent->type),
9242b5f5
AS
2900 parent->var_off.value, parent->off);
2901 return -EFAULT;
2902 }
5327ed3d
JW
2903 /* The first condition is more likely to be true than the
2904 * second, checked it first.
2905 */
2906 if ((parent->live & REG_LIVE_READ) == flag ||
2907 parent->live & REG_LIVE_READ64)
25af32da
AS
2908 /* The parentage chain never changes and
2909 * this parent was already marked as LIVE_READ.
2910 * There is no need to keep walking the chain again and
2911 * keep re-marking all parents as LIVE_READ.
2912 * This case happens when the same register is read
2913 * multiple times without writes into it in-between.
5327ed3d
JW
2914 * Also, if parent has the stronger REG_LIVE_READ64 set,
2915 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
2916 */
2917 break;
dc503a8a 2918 /* ... then we depend on parent's value */
5327ed3d
JW
2919 parent->live |= flag;
2920 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2921 if (flag == REG_LIVE_READ64)
2922 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
2923 state = parent;
2924 parent = state->parent;
f4d7e40a 2925 writes = true;
06ee7115 2926 cnt++;
dc503a8a 2927 }
06ee7115
AS
2928
2929 if (env->longest_mark_read_walk < cnt)
2930 env->longest_mark_read_walk = cnt;
f4d7e40a 2931 return 0;
dc503a8a
EC
2932}
2933
d6fefa11
KKD
2934static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2935{
2936 struct bpf_func_state *state = func(env, reg);
2937 int spi, ret;
2938
2939 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2940 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2941 * check_kfunc_call.
2942 */
2943 if (reg->type == CONST_PTR_TO_DYNPTR)
2944 return 0;
79168a66
KKD
2945 spi = dynptr_get_spi(env, reg);
2946 if (spi < 0)
2947 return spi;
d6fefa11
KKD
2948 /* Caller ensures dynptr is valid and initialized, which means spi is in
2949 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2950 * read.
2951 */
2952 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2953 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2954 if (ret)
2955 return ret;
2956 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2957 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2958}
2959
06accc87
AN
2960static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2961 int spi, int nr_slots)
2962{
2963 struct bpf_func_state *state = func(env, reg);
2964 int err, i;
2965
2966 for (i = 0; i < nr_slots; i++) {
2967 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2968
2969 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2970 if (err)
2971 return err;
2972
2973 mark_stack_slot_scratched(env, spi - i);
2974 }
2975
2976 return 0;
2977}
2978
5327ed3d
JW
2979/* This function is supposed to be used by the following 32-bit optimization
2980 * code only. It returns TRUE if the source or destination register operates
2981 * on 64-bit, otherwise return FALSE.
2982 */
2983static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2984 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2985{
2986 u8 code, class, op;
2987
2988 code = insn->code;
2989 class = BPF_CLASS(code);
2990 op = BPF_OP(code);
2991 if (class == BPF_JMP) {
2992 /* BPF_EXIT for "main" will reach here. Return TRUE
2993 * conservatively.
2994 */
2995 if (op == BPF_EXIT)
2996 return true;
2997 if (op == BPF_CALL) {
2998 /* BPF to BPF call will reach here because of marking
2999 * caller saved clobber with DST_OP_NO_MARK for which we
3000 * don't care the register def because they are anyway
3001 * marked as NOT_INIT already.
3002 */
3003 if (insn->src_reg == BPF_PSEUDO_CALL)
3004 return false;
3005 /* Helper call will reach here because of arg type
3006 * check, conservatively return TRUE.
3007 */
3008 if (t == SRC_OP)
3009 return true;
3010
3011 return false;
3012 }
3013 }
3014
3015 if (class == BPF_ALU64 || class == BPF_JMP ||
3016 /* BPF_END always use BPF_ALU class. */
3017 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3018 return true;
3019
3020 if (class == BPF_ALU || class == BPF_JMP32)
3021 return false;
3022
3023 if (class == BPF_LDX) {
3024 if (t != SRC_OP)
3025 return BPF_SIZE(code) == BPF_DW;
3026 /* LDX source must be ptr. */
3027 return true;
3028 }
3029
3030 if (class == BPF_STX) {
83a28819
IL
3031 /* BPF_STX (including atomic variants) has multiple source
3032 * operands, one of which is a ptr. Check whether the caller is
3033 * asking about it.
3034 */
3035 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
3036 return true;
3037 return BPF_SIZE(code) == BPF_DW;
3038 }
3039
3040 if (class == BPF_LD) {
3041 u8 mode = BPF_MODE(code);
3042
3043 /* LD_IMM64 */
3044 if (mode == BPF_IMM)
3045 return true;
3046
3047 /* Both LD_IND and LD_ABS return 32-bit data. */
3048 if (t != SRC_OP)
3049 return false;
3050
3051 /* Implicit ctx ptr. */
3052 if (regno == BPF_REG_6)
3053 return true;
3054
3055 /* Explicit source could be any width. */
3056 return true;
3057 }
3058
3059 if (class == BPF_ST)
3060 /* The only source register for BPF_ST is a ptr. */
3061 return true;
3062
3063 /* Conservatively return true at default. */
3064 return true;
3065}
3066
83a28819
IL
3067/* Return the regno defined by the insn, or -1. */
3068static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 3069{
83a28819
IL
3070 switch (BPF_CLASS(insn->code)) {
3071 case BPF_JMP:
3072 case BPF_JMP32:
3073 case BPF_ST:
3074 return -1;
3075 case BPF_STX:
3076 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3077 (insn->imm & BPF_FETCH)) {
3078 if (insn->imm == BPF_CMPXCHG)
3079 return BPF_REG_0;
3080 else
3081 return insn->src_reg;
3082 } else {
3083 return -1;
3084 }
3085 default:
3086 return insn->dst_reg;
3087 }
b325fbca
JW
3088}
3089
3090/* Return TRUE if INSN has defined any 32-bit value explicitly. */
3091static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3092{
83a28819
IL
3093 int dst_reg = insn_def_regno(insn);
3094
3095 if (dst_reg == -1)
b325fbca
JW
3096 return false;
3097
83a28819 3098 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
3099}
3100
5327ed3d
JW
3101static void mark_insn_zext(struct bpf_verifier_env *env,
3102 struct bpf_reg_state *reg)
3103{
3104 s32 def_idx = reg->subreg_def;
3105
3106 if (def_idx == DEF_NOT_SUBREG)
3107 return;
3108
3109 env->insn_aux_data[def_idx - 1].zext_dst = true;
3110 /* The dst will be zero extended, so won't be sub-register anymore. */
3111 reg->subreg_def = DEF_NOT_SUBREG;
3112}
3113
dc503a8a 3114static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
3115 enum reg_arg_type t)
3116{
f4d7e40a
AS
3117 struct bpf_verifier_state *vstate = env->cur_state;
3118 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 3119 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 3120 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 3121 bool rw64;
dc503a8a 3122
17a52670 3123 if (regno >= MAX_BPF_REG) {
61bd5218 3124 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
3125 return -EINVAL;
3126 }
3127
0f55f9ed
CL
3128 mark_reg_scratched(env, regno);
3129
c342dc10 3130 reg = &regs[regno];
5327ed3d 3131 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
3132 if (t == SRC_OP) {
3133 /* check whether register used as source operand can be read */
c342dc10 3134 if (reg->type == NOT_INIT) {
61bd5218 3135 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
3136 return -EACCES;
3137 }
679c782d 3138 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
3139 if (regno == BPF_REG_FP)
3140 return 0;
3141
5327ed3d
JW
3142 if (rw64)
3143 mark_insn_zext(env, reg);
3144
3145 return mark_reg_read(env, reg, reg->parent,
3146 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
3147 } else {
3148 /* check whether register used as dest operand can be written to */
3149 if (regno == BPF_REG_FP) {
61bd5218 3150 verbose(env, "frame pointer is read only\n");
17a52670
AS
3151 return -EACCES;
3152 }
c342dc10 3153 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 3154 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 3155 if (t == DST_OP)
61bd5218 3156 mark_reg_unknown(env, regs, regno);
17a52670
AS
3157 }
3158 return 0;
3159}
3160
bffdeaa8
AN
3161static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3162{
3163 env->insn_aux_data[idx].jmp_point = true;
3164}
3165
3166static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3167{
3168 return env->insn_aux_data[insn_idx].jmp_point;
3169}
3170
b5dc0163
AS
3171/* for any branch, call, exit record the history of jmps in the given state */
3172static int push_jmp_history(struct bpf_verifier_env *env,
3173 struct bpf_verifier_state *cur)
3174{
3175 u32 cnt = cur->jmp_history_cnt;
3176 struct bpf_idx_pair *p;
ceb35b66 3177 size_t alloc_size;
b5dc0163 3178
bffdeaa8
AN
3179 if (!is_jmp_point(env, env->insn_idx))
3180 return 0;
3181
b5dc0163 3182 cnt++;
ceb35b66
KC
3183 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3184 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
b5dc0163
AS
3185 if (!p)
3186 return -ENOMEM;
3187 p[cnt - 1].idx = env->insn_idx;
3188 p[cnt - 1].prev_idx = env->prev_insn_idx;
3189 cur->jmp_history = p;
3190 cur->jmp_history_cnt = cnt;
3191 return 0;
3192}
3193
3194/* Backtrack one insn at a time. If idx is not at the top of recorded
3195 * history then previous instruction came from straight line execution.
3196 */
3197static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3198 u32 *history)
3199{
3200 u32 cnt = *history;
3201
3202 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3203 i = st->jmp_history[cnt - 1].prev_idx;
3204 (*history)--;
3205 } else {
3206 i--;
3207 }
3208 return i;
3209}
3210
e6ac2450
MKL
3211static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3212{
3213 const struct btf_type *func;
2357672c 3214 struct btf *desc_btf;
e6ac2450
MKL
3215
3216 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3217 return NULL;
3218
43bf0878 3219 desc_btf = find_kfunc_desc_btf(data, insn->off);
2357672c
KKD
3220 if (IS_ERR(desc_btf))
3221 return "<error>";
3222
3223 func = btf_type_by_id(desc_btf, insn->imm);
3224 return btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
3225}
3226
407958a0
AN
3227static inline void bt_init(struct backtrack_state *bt, u32 frame)
3228{
3229 bt->frame = frame;
3230}
3231
3232static inline void bt_reset(struct backtrack_state *bt)
3233{
3234 struct bpf_verifier_env *env = bt->env;
3235
3236 memset(bt, 0, sizeof(*bt));
3237 bt->env = env;
3238}
3239
3240static inline u32 bt_empty(struct backtrack_state *bt)
3241{
3242 u64 mask = 0;
3243 int i;
3244
3245 for (i = 0; i <= bt->frame; i++)
3246 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3247
3248 return mask == 0;
3249}
3250
3251static inline int bt_subprog_enter(struct backtrack_state *bt)
3252{
3253 if (bt->frame == MAX_CALL_FRAMES - 1) {
3254 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3255 WARN_ONCE(1, "verifier backtracking bug");
3256 return -EFAULT;
3257 }
3258 bt->frame++;
3259 return 0;
3260}
3261
3262static inline int bt_subprog_exit(struct backtrack_state *bt)
3263{
3264 if (bt->frame == 0) {
3265 verbose(bt->env, "BUG subprog exit from frame 0\n");
3266 WARN_ONCE(1, "verifier backtracking bug");
3267 return -EFAULT;
3268 }
3269 bt->frame--;
3270 return 0;
3271}
3272
3273static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3274{
3275 bt->reg_masks[frame] |= 1 << reg;
3276}
3277
3278static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3279{
3280 bt->reg_masks[frame] &= ~(1 << reg);
3281}
3282
3283static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3284{
3285 bt_set_frame_reg(bt, bt->frame, reg);
3286}
3287
3288static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3289{
3290 bt_clear_frame_reg(bt, bt->frame, reg);
3291}
3292
3293static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3294{
3295 bt->stack_masks[frame] |= 1ull << slot;
3296}
3297
3298static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3299{
3300 bt->stack_masks[frame] &= ~(1ull << slot);
3301}
3302
3303static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3304{
3305 bt_set_frame_slot(bt, bt->frame, slot);
3306}
3307
3308static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3309{
3310 bt_clear_frame_slot(bt, bt->frame, slot);
3311}
3312
3313static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3314{
3315 return bt->reg_masks[frame];
3316}
3317
3318static inline u32 bt_reg_mask(struct backtrack_state *bt)
3319{
3320 return bt->reg_masks[bt->frame];
3321}
3322
3323static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3324{
3325 return bt->stack_masks[frame];
3326}
3327
3328static inline u64 bt_stack_mask(struct backtrack_state *bt)
3329{
3330 return bt->stack_masks[bt->frame];
3331}
3332
3333static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3334{
3335 return bt->reg_masks[bt->frame] & (1 << reg);
3336}
3337
3338static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3339{
3340 return bt->stack_masks[bt->frame] & (1ull << slot);
3341}
3342
d9439c21
AN
3343/* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3344static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3345{
3346 DECLARE_BITMAP(mask, 64);
3347 bool first = true;
3348 int i, n;
3349
3350 buf[0] = '\0';
3351
3352 bitmap_from_u64(mask, reg_mask);
3353 for_each_set_bit(i, mask, 32) {
3354 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3355 first = false;
3356 buf += n;
3357 buf_sz -= n;
3358 if (buf_sz < 0)
3359 break;
3360 }
3361}
3362/* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3363static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3364{
3365 DECLARE_BITMAP(mask, 64);
3366 bool first = true;
3367 int i, n;
3368
3369 buf[0] = '\0';
3370
3371 bitmap_from_u64(mask, stack_mask);
3372 for_each_set_bit(i, mask, 64) {
3373 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3374 first = false;
3375 buf += n;
3376 buf_sz -= n;
3377 if (buf_sz < 0)
3378 break;
3379 }
3380}
3381
b5dc0163
AS
3382/* For given verifier state backtrack_insn() is called from the last insn to
3383 * the first insn. Its purpose is to compute a bitmask of registers and
3384 * stack slots that needs precision in the parent verifier state.
fde2a388
AN
3385 *
3386 * @idx is an index of the instruction we are currently processing;
3387 * @subseq_idx is an index of the subsequent instruction that:
3388 * - *would be* executed next, if jump history is viewed in forward order;
3389 * - *was* processed previously during backtracking.
b5dc0163 3390 */
fde2a388 3391static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
407958a0 3392 struct backtrack_state *bt)
b5dc0163
AS
3393{
3394 const struct bpf_insn_cbs cbs = {
e6ac2450 3395 .cb_call = disasm_kfunc_name,
b5dc0163
AS
3396 .cb_print = verbose,
3397 .private_data = env,
3398 };
3399 struct bpf_insn *insn = env->prog->insnsi + idx;
3400 u8 class = BPF_CLASS(insn->code);
3401 u8 opcode = BPF_OP(insn->code);
3402 u8 mode = BPF_MODE(insn->code);
407958a0
AN
3403 u32 dreg = insn->dst_reg;
3404 u32 sreg = insn->src_reg;
fde2a388 3405 u32 spi, i;
b5dc0163
AS
3406
3407 if (insn->code == 0)
3408 return 0;
496f3324 3409 if (env->log.level & BPF_LOG_LEVEL2) {
d9439c21
AN
3410 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3411 verbose(env, "mark_precise: frame%d: regs=%s ",
3412 bt->frame, env->tmp_str_buf);
3413 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3414 verbose(env, "stack=%s before ", env->tmp_str_buf);
b5dc0163
AS
3415 verbose(env, "%d: ", idx);
3416 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3417 }
3418
3419 if (class == BPF_ALU || class == BPF_ALU64) {
407958a0 3420 if (!bt_is_reg_set(bt, dreg))
b5dc0163
AS
3421 return 0;
3422 if (opcode == BPF_MOV) {
3423 if (BPF_SRC(insn->code) == BPF_X) {
3424 /* dreg = sreg
3425 * dreg needs precision after this insn
3426 * sreg needs precision before this insn
3427 */
407958a0
AN
3428 bt_clear_reg(bt, dreg);
3429 bt_set_reg(bt, sreg);
b5dc0163
AS
3430 } else {
3431 /* dreg = K
3432 * dreg needs precision after this insn.
3433 * Corresponding register is already marked
3434 * as precise=true in this verifier state.
3435 * No further markings in parent are necessary
3436 */
407958a0 3437 bt_clear_reg(bt, dreg);
b5dc0163
AS
3438 }
3439 } else {
3440 if (BPF_SRC(insn->code) == BPF_X) {
3441 /* dreg += sreg
3442 * both dreg and sreg need precision
3443 * before this insn
3444 */
407958a0 3445 bt_set_reg(bt, sreg);
b5dc0163
AS
3446 } /* else dreg += K
3447 * dreg still needs precision before this insn
3448 */
3449 }
3450 } else if (class == BPF_LDX) {
407958a0 3451 if (!bt_is_reg_set(bt, dreg))
b5dc0163 3452 return 0;
407958a0 3453 bt_clear_reg(bt, dreg);
b5dc0163
AS
3454
3455 /* scalars can only be spilled into stack w/o losing precision.
3456 * Load from any other memory can be zero extended.
3457 * The desire to keep that precision is already indicated
3458 * by 'precise' mark in corresponding register of this state.
3459 * No further tracking necessary.
3460 */
3461 if (insn->src_reg != BPF_REG_FP)
3462 return 0;
b5dc0163
AS
3463
3464 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3465 * that [fp - off] slot contains scalar that needs to be
3466 * tracked with precision
3467 */
3468 spi = (-insn->off - 1) / BPF_REG_SIZE;
3469 if (spi >= 64) {
3470 verbose(env, "BUG spi %d\n", spi);
3471 WARN_ONCE(1, "verifier backtracking bug");
3472 return -EFAULT;
3473 }
407958a0 3474 bt_set_slot(bt, spi);
b3b50f05 3475 } else if (class == BPF_STX || class == BPF_ST) {
407958a0 3476 if (bt_is_reg_set(bt, dreg))
b3b50f05 3477 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
3478 * to access memory. It means backtracking
3479 * encountered a case of pointer subtraction.
3480 */
3481 return -ENOTSUPP;
3482 /* scalars can only be spilled into stack */
3483 if (insn->dst_reg != BPF_REG_FP)
3484 return 0;
b5dc0163
AS
3485 spi = (-insn->off - 1) / BPF_REG_SIZE;
3486 if (spi >= 64) {
3487 verbose(env, "BUG spi %d\n", spi);
3488 WARN_ONCE(1, "verifier backtracking bug");
3489 return -EFAULT;
3490 }
407958a0 3491 if (!bt_is_slot_set(bt, spi))
b5dc0163 3492 return 0;
407958a0 3493 bt_clear_slot(bt, spi);
b3b50f05 3494 if (class == BPF_STX)
407958a0 3495 bt_set_reg(bt, sreg);
b5dc0163 3496 } else if (class == BPF_JMP || class == BPF_JMP32) {
fde2a388
AN
3497 if (bpf_pseudo_call(insn)) {
3498 int subprog_insn_idx, subprog;
3499
3500 subprog_insn_idx = idx + insn->imm + 1;
3501 subprog = find_subprog(env, subprog_insn_idx);
3502 if (subprog < 0)
3503 return -EFAULT;
3504
3505 if (subprog_is_global(env, subprog)) {
3506 /* check that jump history doesn't have any
3507 * extra instructions from subprog; the next
3508 * instruction after call to global subprog
3509 * should be literally next instruction in
3510 * caller program
3511 */
3512 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3513 /* r1-r5 are invalidated after subprog call,
3514 * so for global func call it shouldn't be set
3515 * anymore
3516 */
3517 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3518 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3519 WARN_ONCE(1, "verifier backtracking bug");
3520 return -EFAULT;
3521 }
3522 /* global subprog always sets R0 */
3523 bt_clear_reg(bt, BPF_REG_0);
3524 return 0;
3525 } else {
3526 /* static subprog call instruction, which
3527 * means that we are exiting current subprog,
3528 * so only r1-r5 could be still requested as
3529 * precise, r0 and r6-r10 or any stack slot in
3530 * the current frame should be zero by now
3531 */
3532 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3533 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3534 WARN_ONCE(1, "verifier backtracking bug");
3535 return -EFAULT;
3536 }
3537 /* we don't track register spills perfectly,
3538 * so fallback to force-precise instead of failing */
3539 if (bt_stack_mask(bt) != 0)
3540 return -ENOTSUPP;
3541 /* propagate r1-r5 to the caller */
3542 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3543 if (bt_is_reg_set(bt, i)) {
3544 bt_clear_reg(bt, i);
3545 bt_set_frame_reg(bt, bt->frame - 1, i);
3546 }
3547 }
3548 if (bt_subprog_exit(bt))
3549 return -EFAULT;
3550 return 0;
3551 }
3552 } else if ((bpf_helper_call(insn) &&
3553 is_callback_calling_function(insn->imm) &&
3554 !is_async_callback_calling_function(insn->imm)) ||
3555 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3556 /* callback-calling helper or kfunc call, which means
3557 * we are exiting from subprog, but unlike the subprog
3558 * call handling above, we shouldn't propagate
3559 * precision of r1-r5 (if any requested), as they are
3560 * not actually arguments passed directly to callback
3561 * subprogs
be2ef816 3562 */
fde2a388
AN
3563 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3564 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3565 WARN_ONCE(1, "verifier backtracking bug");
3566 return -EFAULT;
3567 }
3568 if (bt_stack_mask(bt) != 0)
be2ef816 3569 return -ENOTSUPP;
fde2a388
AN
3570 /* clear r1-r5 in callback subprog's mask */
3571 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3572 bt_clear_reg(bt, i);
3573 if (bt_subprog_exit(bt))
3574 return -EFAULT;
3575 return 0;
3576 } else if (opcode == BPF_CALL) {
d3178e8a
HS
3577 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3578 * catch this error later. Make backtracking conservative
3579 * with ENOTSUPP.
3580 */
3581 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3582 return -ENOTSUPP;
b5dc0163 3583 /* regular helper call sets R0 */
407958a0
AN
3584 bt_clear_reg(bt, BPF_REG_0);
3585 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
b5dc0163
AS
3586 /* if backtracing was looking for registers R1-R5
3587 * they should have been found already.
3588 */
407958a0 3589 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
b5dc0163
AS
3590 WARN_ONCE(1, "verifier backtracking bug");
3591 return -EFAULT;
3592 }
3593 } else if (opcode == BPF_EXIT) {
fde2a388
AN
3594 bool r0_precise;
3595
3596 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3597 /* if backtracing was looking for registers R1-R5
3598 * they should have been found already.
3599 */
3600 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3601 WARN_ONCE(1, "verifier backtracking bug");
3602 return -EFAULT;
3603 }
3604
3605 /* BPF_EXIT in subprog or callback always returns
3606 * right after the call instruction, so by checking
3607 * whether the instruction at subseq_idx-1 is subprog
3608 * call or not we can distinguish actual exit from
3609 * *subprog* from exit from *callback*. In the former
3610 * case, we need to propagate r0 precision, if
3611 * necessary. In the former we never do that.
3612 */
3613 r0_precise = subseq_idx - 1 >= 0 &&
3614 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3615 bt_is_reg_set(bt, BPF_REG_0);
3616
3617 bt_clear_reg(bt, BPF_REG_0);
3618 if (bt_subprog_enter(bt))
3619 return -EFAULT;
3620
3621 if (r0_precise)
3622 bt_set_reg(bt, BPF_REG_0);
3623 /* r6-r9 and stack slots will stay set in caller frame
3624 * bitmasks until we return back from callee(s)
3625 */
3626 return 0;
71b547f5 3627 } else if (BPF_SRC(insn->code) == BPF_X) {
407958a0 3628 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
71b547f5
DB
3629 return 0;
3630 /* dreg <cond> sreg
3631 * Both dreg and sreg need precision before
3632 * this insn. If only sreg was marked precise
3633 * before it would be equally necessary to
3634 * propagate it to dreg.
3635 */
407958a0
AN
3636 bt_set_reg(bt, dreg);
3637 bt_set_reg(bt, sreg);
71b547f5
DB
3638 /* else dreg <cond> K
3639 * Only dreg still needs precision before
3640 * this insn, so for the K-based conditional
3641 * there is nothing new to be marked.
3642 */
b5dc0163
AS
3643 }
3644 } else if (class == BPF_LD) {
407958a0 3645 if (!bt_is_reg_set(bt, dreg))
b5dc0163 3646 return 0;
407958a0 3647 bt_clear_reg(bt, dreg);
b5dc0163
AS
3648 /* It's ld_imm64 or ld_abs or ld_ind.
3649 * For ld_imm64 no further tracking of precision
3650 * into parent is necessary
3651 */
3652 if (mode == BPF_IND || mode == BPF_ABS)
3653 /* to be analyzed */
3654 return -ENOTSUPP;
b5dc0163
AS
3655 }
3656 return 0;
3657}
3658
3659/* the scalar precision tracking algorithm:
3660 * . at the start all registers have precise=false.
3661 * . scalar ranges are tracked as normal through alu and jmp insns.
3662 * . once precise value of the scalar register is used in:
3663 * . ptr + scalar alu
3664 * . if (scalar cond K|scalar)
3665 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3666 * backtrack through the verifier states and mark all registers and
3667 * stack slots with spilled constants that these scalar regisers
3668 * should be precise.
3669 * . during state pruning two registers (or spilled stack slots)
3670 * are equivalent if both are not precise.
3671 *
3672 * Note the verifier cannot simply walk register parentage chain,
3673 * since many different registers and stack slots could have been
3674 * used to compute single precise scalar.
3675 *
3676 * The approach of starting with precise=true for all registers and then
3677 * backtrack to mark a register as not precise when the verifier detects
3678 * that program doesn't care about specific value (e.g., when helper
3679 * takes register as ARG_ANYTHING parameter) is not safe.
3680 *
3681 * It's ok to walk single parentage chain of the verifier states.
3682 * It's possible that this backtracking will go all the way till 1st insn.
3683 * All other branches will be explored for needing precision later.
3684 *
3685 * The backtracking needs to deal with cases like:
3686 * 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)
3687 * r9 -= r8
3688 * r5 = r9
3689 * if r5 > 0x79f goto pc+7
3690 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3691 * r5 += 1
3692 * ...
3693 * call bpf_perf_event_output#25
3694 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3695 *
3696 * and this case:
3697 * r6 = 1
3698 * call foo // uses callee's r6 inside to compute r0
3699 * r0 += r6
3700 * if r0 == 0 goto
3701 *
3702 * to track above reg_mask/stack_mask needs to be independent for each frame.
3703 *
3704 * Also if parent's curframe > frame where backtracking started,
3705 * the verifier need to mark registers in both frames, otherwise callees
3706 * may incorrectly prune callers. This is similar to
3707 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3708 *
3709 * For now backtracking falls back into conservative marking.
3710 */
3711static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3712 struct bpf_verifier_state *st)
3713{
3714 struct bpf_func_state *func;
3715 struct bpf_reg_state *reg;
3716 int i, j;
3717
d9439c21
AN
3718 if (env->log.level & BPF_LOG_LEVEL2) {
3719 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3720 st->curframe);
3721 }
3722
b5dc0163
AS
3723 /* big hammer: mark all scalars precise in this path.
3724 * pop_stack may still get !precise scalars.
f63181b6
AN
3725 * We also skip current state and go straight to first parent state,
3726 * because precision markings in current non-checkpointed state are
3727 * not needed. See why in the comment in __mark_chain_precision below.
b5dc0163 3728 */
f63181b6 3729 for (st = st->parent; st; st = st->parent) {
b5dc0163
AS
3730 for (i = 0; i <= st->curframe; i++) {
3731 func = st->frame[i];
3732 for (j = 0; j < BPF_REG_FP; j++) {
3733 reg = &func->regs[j];
d9439c21 3734 if (reg->type != SCALAR_VALUE || reg->precise)
b5dc0163
AS
3735 continue;
3736 reg->precise = true;
d9439c21
AN
3737 if (env->log.level & BPF_LOG_LEVEL2) {
3738 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3739 i, j);
3740 }
b5dc0163
AS
3741 }
3742 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
27113c59 3743 if (!is_spilled_reg(&func->stack[j]))
b5dc0163
AS
3744 continue;
3745 reg = &func->stack[j].spilled_ptr;
d9439c21 3746 if (reg->type != SCALAR_VALUE || reg->precise)
b5dc0163
AS
3747 continue;
3748 reg->precise = true;
d9439c21
AN
3749 if (env->log.level & BPF_LOG_LEVEL2) {
3750 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3751 i, -(j + 1) * 8);
3752 }
b5dc0163
AS
3753 }
3754 }
f63181b6 3755 }
b5dc0163
AS
3756}
3757
7a830b53
AN
3758static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3759{
3760 struct bpf_func_state *func;
3761 struct bpf_reg_state *reg;
3762 int i, j;
3763
3764 for (i = 0; i <= st->curframe; i++) {
3765 func = st->frame[i];
3766 for (j = 0; j < BPF_REG_FP; j++) {
3767 reg = &func->regs[j];
3768 if (reg->type != SCALAR_VALUE)
3769 continue;
3770 reg->precise = false;
3771 }
3772 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3773 if (!is_spilled_reg(&func->stack[j]))
3774 continue;
3775 reg = &func->stack[j].spilled_ptr;
3776 if (reg->type != SCALAR_VALUE)
3777 continue;
3778 reg->precise = false;
3779 }
3780 }
3781}
3782
904e6ddf
EZ
3783static bool idset_contains(struct bpf_idset *s, u32 id)
3784{
3785 u32 i;
3786
3787 for (i = 0; i < s->count; ++i)
3788 if (s->ids[i] == id)
3789 return true;
3790
3791 return false;
3792}
3793
3794static int idset_push(struct bpf_idset *s, u32 id)
3795{
3796 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3797 return -EFAULT;
3798 s->ids[s->count++] = id;
3799 return 0;
3800}
3801
3802static void idset_reset(struct bpf_idset *s)
3803{
3804 s->count = 0;
3805}
3806
3807/* Collect a set of IDs for all registers currently marked as precise in env->bt.
3808 * Mark all registers with these IDs as precise.
3809 */
3810static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3811{
3812 struct bpf_idset *precise_ids = &env->idset_scratch;
3813 struct backtrack_state *bt = &env->bt;
3814 struct bpf_func_state *func;
3815 struct bpf_reg_state *reg;
3816 DECLARE_BITMAP(mask, 64);
3817 int i, fr;
3818
3819 idset_reset(precise_ids);
3820
3821 for (fr = bt->frame; fr >= 0; fr--) {
3822 func = st->frame[fr];
3823
3824 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3825 for_each_set_bit(i, mask, 32) {
3826 reg = &func->regs[i];
3827 if (!reg->id || reg->type != SCALAR_VALUE)
3828 continue;
3829 if (idset_push(precise_ids, reg->id))
3830 return -EFAULT;
3831 }
3832
3833 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3834 for_each_set_bit(i, mask, 64) {
3835 if (i >= func->allocated_stack / BPF_REG_SIZE)
3836 break;
3837 if (!is_spilled_scalar_reg(&func->stack[i]))
3838 continue;
3839 reg = &func->stack[i].spilled_ptr;
3840 if (!reg->id)
3841 continue;
3842 if (idset_push(precise_ids, reg->id))
3843 return -EFAULT;
3844 }
3845 }
3846
3847 for (fr = 0; fr <= st->curframe; ++fr) {
3848 func = st->frame[fr];
3849
3850 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3851 reg = &func->regs[i];
3852 if (!reg->id)
3853 continue;
3854 if (!idset_contains(precise_ids, reg->id))
3855 continue;
3856 bt_set_frame_reg(bt, fr, i);
3857 }
3858 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3859 if (!is_spilled_scalar_reg(&func->stack[i]))
3860 continue;
3861 reg = &func->stack[i].spilled_ptr;
3862 if (!reg->id)
3863 continue;
3864 if (!idset_contains(precise_ids, reg->id))
3865 continue;
3866 bt_set_frame_slot(bt, fr, i);
3867 }
3868 }
3869
3870 return 0;
3871}
3872
f63181b6
AN
3873/*
3874 * __mark_chain_precision() backtracks BPF program instruction sequence and
3875 * chain of verifier states making sure that register *regno* (if regno >= 0)
3876 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3877 * SCALARS, as well as any other registers and slots that contribute to
3878 * a tracked state of given registers/stack slots, depending on specific BPF
3879 * assembly instructions (see backtrack_insns() for exact instruction handling
3880 * logic). This backtracking relies on recorded jmp_history and is able to
3881 * traverse entire chain of parent states. This process ends only when all the
3882 * necessary registers/slots and their transitive dependencies are marked as
3883 * precise.
3884 *
3885 * One important and subtle aspect is that precise marks *do not matter* in
3886 * the currently verified state (current state). It is important to understand
3887 * why this is the case.
3888 *
3889 * First, note that current state is the state that is not yet "checkpointed",
3890 * i.e., it is not yet put into env->explored_states, and it has no children
3891 * states as well. It's ephemeral, and can end up either a) being discarded if
3892 * compatible explored state is found at some point or BPF_EXIT instruction is
3893 * reached or b) checkpointed and put into env->explored_states, branching out
3894 * into one or more children states.
3895 *
3896 * In the former case, precise markings in current state are completely
3897 * ignored by state comparison code (see regsafe() for details). Only
3898 * checkpointed ("old") state precise markings are important, and if old
3899 * state's register/slot is precise, regsafe() assumes current state's
3900 * register/slot as precise and checks value ranges exactly and precisely. If
3901 * states turn out to be compatible, current state's necessary precise
3902 * markings and any required parent states' precise markings are enforced
3903 * after the fact with propagate_precision() logic, after the fact. But it's
3904 * important to realize that in this case, even after marking current state
3905 * registers/slots as precise, we immediately discard current state. So what
3906 * actually matters is any of the precise markings propagated into current
3907 * state's parent states, which are always checkpointed (due to b) case above).
3908 * As such, for scenario a) it doesn't matter if current state has precise
3909 * markings set or not.
3910 *
3911 * Now, for the scenario b), checkpointing and forking into child(ren)
3912 * state(s). Note that before current state gets to checkpointing step, any
3913 * processed instruction always assumes precise SCALAR register/slot
3914 * knowledge: if precise value or range is useful to prune jump branch, BPF
3915 * verifier takes this opportunity enthusiastically. Similarly, when
3916 * register's value is used to calculate offset or memory address, exact
3917 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3918 * what we mentioned above about state comparison ignoring precise markings
3919 * during state comparison, BPF verifier ignores and also assumes precise
3920 * markings *at will* during instruction verification process. But as verifier
3921 * assumes precision, it also propagates any precision dependencies across
3922 * parent states, which are not yet finalized, so can be further restricted
3923 * based on new knowledge gained from restrictions enforced by their children
3924 * states. This is so that once those parent states are finalized, i.e., when
3925 * they have no more active children state, state comparison logic in
3926 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3927 * required for correctness.
3928 *
3929 * To build a bit more intuition, note also that once a state is checkpointed,
3930 * the path we took to get to that state is not important. This is crucial
3931 * property for state pruning. When state is checkpointed and finalized at
3932 * some instruction index, it can be correctly and safely used to "short
3933 * circuit" any *compatible* state that reaches exactly the same instruction
3934 * index. I.e., if we jumped to that instruction from a completely different
3935 * code path than original finalized state was derived from, it doesn't
3936 * matter, current state can be discarded because from that instruction
3937 * forward having a compatible state will ensure we will safely reach the
3938 * exit. States describe preconditions for further exploration, but completely
3939 * forget the history of how we got here.
3940 *
3941 * This also means that even if we needed precise SCALAR range to get to
3942 * finalized state, but from that point forward *that same* SCALAR register is
3943 * never used in a precise context (i.e., it's precise value is not needed for
3944 * correctness), it's correct and safe to mark such register as "imprecise"
3945 * (i.e., precise marking set to false). This is what we rely on when we do
3946 * not set precise marking in current state. If no child state requires
3947 * precision for any given SCALAR register, it's safe to dictate that it can
3948 * be imprecise. If any child state does require this register to be precise,
3949 * we'll mark it precise later retroactively during precise markings
3950 * propagation from child state to parent states.
7a830b53
AN
3951 *
3952 * Skipping precise marking setting in current state is a mild version of
3953 * relying on the above observation. But we can utilize this property even
3954 * more aggressively by proactively forgetting any precise marking in the
3955 * current state (which we inherited from the parent state), right before we
3956 * checkpoint it and branch off into new child state. This is done by
3957 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3958 * finalized states which help in short circuiting more future states.
f63181b6 3959 */
f655badf 3960static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
b5dc0163 3961{
407958a0 3962 struct backtrack_state *bt = &env->bt;
b5dc0163
AS
3963 struct bpf_verifier_state *st = env->cur_state;
3964 int first_idx = st->first_insn_idx;
3965 int last_idx = env->insn_idx;
d84b1a67 3966 int subseq_idx = -1;
b5dc0163
AS
3967 struct bpf_func_state *func;
3968 struct bpf_reg_state *reg;
b5dc0163 3969 bool skip_first = true;
d84b1a67 3970 int i, fr, err;
b5dc0163 3971
2c78ee89 3972 if (!env->bpf_capable)
b5dc0163
AS
3973 return 0;
3974
407958a0 3975 /* set frame number from which we are starting to backtrack */
f655badf 3976 bt_init(bt, env->cur_state->curframe);
407958a0 3977
f63181b6
AN
3978 /* Do sanity checks against current state of register and/or stack
3979 * slot, but don't set precise flag in current state, as precision
3980 * tracking in the current state is unnecessary.
3981 */
f655badf 3982 func = st->frame[bt->frame];
a3ce685d
AS
3983 if (regno >= 0) {
3984 reg = &func->regs[regno];
3985 if (reg->type != SCALAR_VALUE) {
3986 WARN_ONCE(1, "backtracing misuse");
3987 return -EFAULT;
3988 }
407958a0 3989 bt_set_reg(bt, regno);
b5dc0163 3990 }
b5dc0163 3991
407958a0 3992 if (bt_empty(bt))
a3ce685d 3993 return 0;
be2ef816 3994
b5dc0163
AS
3995 for (;;) {
3996 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
3997 u32 history = st->jmp_history_cnt;
3998
d9439c21 3999 if (env->log.level & BPF_LOG_LEVEL2) {
d84b1a67
AN
4000 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4001 bt->frame, last_idx, first_idx, subseq_idx);
d9439c21 4002 }
be2ef816 4003
904e6ddf
EZ
4004 /* If some register with scalar ID is marked as precise,
4005 * make sure that all registers sharing this ID are also precise.
4006 * This is needed to estimate effect of find_equal_scalars().
4007 * Do this at the last instruction of each state,
4008 * bpf_reg_state::id fields are valid for these instructions.
4009 *
4010 * Allows to track precision in situation like below:
4011 *
4012 * r2 = unknown value
4013 * ...
4014 * --- state #0 ---
4015 * ...
4016 * r1 = r2 // r1 and r2 now share the same ID
4017 * ...
4018 * --- state #1 {r1.id = A, r2.id = A} ---
4019 * ...
4020 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4021 * ...
4022 * --- state #2 {r1.id = A, r2.id = A} ---
4023 * r3 = r10
4024 * r3 += r1 // need to mark both r1 and r2
4025 */
4026 if (mark_precise_scalar_ids(env, st))
4027 return -EFAULT;
4028
be2ef816
AN
4029 if (last_idx < 0) {
4030 /* we are at the entry into subprog, which
4031 * is expected for global funcs, but only if
4032 * requested precise registers are R1-R5
4033 * (which are global func's input arguments)
4034 */
4035 if (st->curframe == 0 &&
4036 st->frame[0]->subprogno > 0 &&
4037 st->frame[0]->callsite == BPF_MAIN_FUNC &&
407958a0
AN
4038 bt_stack_mask(bt) == 0 &&
4039 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4040 bitmap_from_u64(mask, bt_reg_mask(bt));
be2ef816
AN
4041 for_each_set_bit(i, mask, 32) {
4042 reg = &st->frame[0]->regs[i];
4043 if (reg->type != SCALAR_VALUE) {
407958a0 4044 bt_clear_reg(bt, i);
be2ef816
AN
4045 continue;
4046 }
4047 reg->precise = true;
4048 }
4049 return 0;
4050 }
4051
407958a0
AN
4052 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4053 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
be2ef816
AN
4054 WARN_ONCE(1, "verifier backtracking bug");
4055 return -EFAULT;
4056 }
4057
d84b1a67 4058 for (i = last_idx;;) {
b5dc0163
AS
4059 if (skip_first) {
4060 err = 0;
4061 skip_first = false;
4062 } else {
d84b1a67 4063 err = backtrack_insn(env, i, subseq_idx, bt);
b5dc0163
AS
4064 }
4065 if (err == -ENOTSUPP) {
c50c0b57 4066 mark_all_scalars_precise(env, env->cur_state);
407958a0 4067 bt_reset(bt);
b5dc0163
AS
4068 return 0;
4069 } else if (err) {
4070 return err;
4071 }
407958a0 4072 if (bt_empty(bt))
b5dc0163
AS
4073 /* Found assignment(s) into tracked register in this state.
4074 * Since this state is already marked, just return.
4075 * Nothing to be tracked further in the parent state.
4076 */
4077 return 0;
4078 if (i == first_idx)
4079 break;
d84b1a67 4080 subseq_idx = i;
b5dc0163
AS
4081 i = get_prev_insn_idx(st, i, &history);
4082 if (i >= env->prog->len) {
4083 /* This can happen if backtracking reached insn 0
4084 * and there are still reg_mask or stack_mask
4085 * to backtrack.
4086 * It means the backtracking missed the spot where
4087 * particular register was initialized with a constant.
4088 */
4089 verbose(env, "BUG backtracking idx %d\n", i);
4090 WARN_ONCE(1, "verifier backtracking bug");
4091 return -EFAULT;
4092 }
4093 }
4094 st = st->parent;
4095 if (!st)
4096 break;
4097
1ef22b68
AN
4098 for (fr = bt->frame; fr >= 0; fr--) {
4099 func = st->frame[fr];
4100 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4101 for_each_set_bit(i, mask, 32) {
4102 reg = &func->regs[i];
4103 if (reg->type != SCALAR_VALUE) {
4104 bt_clear_frame_reg(bt, fr, i);
4105 continue;
4106 }
4107 if (reg->precise)
4108 bt_clear_frame_reg(bt, fr, i);
4109 else
4110 reg->precise = true;
a3ce685d 4111 }
b5dc0163 4112
1ef22b68
AN
4113 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4114 for_each_set_bit(i, mask, 64) {
4115 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4116 /* the sequence of instructions:
4117 * 2: (bf) r3 = r10
4118 * 3: (7b) *(u64 *)(r3 -8) = r0
4119 * 4: (79) r4 = *(u64 *)(r10 -8)
4120 * doesn't contain jmps. It's backtracked
4121 * as a single block.
4122 * During backtracking insn 3 is not recognized as
4123 * stack access, so at the end of backtracking
4124 * stack slot fp-8 is still marked in stack_mask.
4125 * However the parent state may not have accessed
4126 * fp-8 and it's "unallocated" stack space.
4127 * In such case fallback to conservative.
4128 */
c50c0b57 4129 mark_all_scalars_precise(env, env->cur_state);
1ef22b68
AN
4130 bt_reset(bt);
4131 return 0;
4132 }
b5dc0163 4133
1ef22b68
AN
4134 if (!is_spilled_scalar_reg(&func->stack[i])) {
4135 bt_clear_frame_slot(bt, fr, i);
4136 continue;
4137 }
4138 reg = &func->stack[i].spilled_ptr;
4139 if (reg->precise)
4140 bt_clear_frame_slot(bt, fr, i);
4141 else
4142 reg->precise = true;
4143 }
4144 if (env->log.level & BPF_LOG_LEVEL2) {
4145 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4146 bt_frame_reg_mask(bt, fr));
4147 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4148 fr, env->tmp_str_buf);
4149 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4150 bt_frame_stack_mask(bt, fr));
4151 verbose(env, "stack=%s: ", env->tmp_str_buf);
4152 print_verifier_state(env, func, true);
a3ce685d 4153 }
b5dc0163
AS
4154 }
4155
407958a0 4156 if (bt_empty(bt))
c50c0b57 4157 return 0;
b5dc0163 4158
d84b1a67 4159 subseq_idx = first_idx;
b5dc0163
AS
4160 last_idx = st->last_insn_idx;
4161 first_idx = st->first_insn_idx;
4162 }
c50c0b57
AN
4163
4164 /* if we still have requested precise regs or slots, we missed
4165 * something (e.g., stack access through non-r10 register), so
4166 * fallback to marking all precise
4167 */
4168 if (!bt_empty(bt)) {
4169 mark_all_scalars_precise(env, env->cur_state);
4170 bt_reset(bt);
4171 }
4172
b5dc0163
AS
4173 return 0;
4174}
4175
eb1f7f71 4176int mark_chain_precision(struct bpf_verifier_env *env, int regno)
a3ce685d 4177{
f655badf 4178 return __mark_chain_precision(env, regno);
a3ce685d
AS
4179}
4180
f655badf
AN
4181/* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4182 * desired reg and stack masks across all relevant frames
4183 */
4184static int mark_chain_precision_batch(struct bpf_verifier_env *env)
a3ce685d 4185{
f655badf 4186 return __mark_chain_precision(env, -1);
a3ce685d 4187}
b5dc0163 4188
1be7f75d
AS
4189static bool is_spillable_regtype(enum bpf_reg_type type)
4190{
c25b2ae1 4191 switch (base_type(type)) {
1be7f75d 4192 case PTR_TO_MAP_VALUE:
1be7f75d
AS
4193 case PTR_TO_STACK:
4194 case PTR_TO_CTX:
969bf05e 4195 case PTR_TO_PACKET:
de8f3a83 4196 case PTR_TO_PACKET_META:
969bf05e 4197 case PTR_TO_PACKET_END:
d58e468b 4198 case PTR_TO_FLOW_KEYS:
1be7f75d 4199 case CONST_PTR_TO_MAP:
c64b7983 4200 case PTR_TO_SOCKET:
46f8bc92 4201 case PTR_TO_SOCK_COMMON:
655a51e5 4202 case PTR_TO_TCP_SOCK:
fada7fdc 4203 case PTR_TO_XDP_SOCK:
65726b5b 4204 case PTR_TO_BTF_ID:
20b2aff4 4205 case PTR_TO_BUF:
744ea4e3 4206 case PTR_TO_MEM:
69c087ba
YS
4207 case PTR_TO_FUNC:
4208 case PTR_TO_MAP_KEY:
1be7f75d
AS
4209 return true;
4210 default:
4211 return false;
4212 }
4213}
4214
cc2b14d5
AS
4215/* Does this register contain a constant zero? */
4216static bool register_is_null(struct bpf_reg_state *reg)
4217{
4218 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4219}
4220
f7cf25b2
AS
4221static bool register_is_const(struct bpf_reg_state *reg)
4222{
4223 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4224}
4225
5689d49b
YS
4226static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4227{
4228 return tnum_is_unknown(reg->var_off) &&
4229 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4230 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4231 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4232 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4233}
4234
4235static bool register_is_bounded(struct bpf_reg_state *reg)
4236{
4237 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4238}
4239
6e7e63cb
JH
4240static bool __is_pointer_value(bool allow_ptr_leaks,
4241 const struct bpf_reg_state *reg)
4242{
4243 if (allow_ptr_leaks)
4244 return false;
4245
4246 return reg->type != SCALAR_VALUE;
4247}
4248
71f656a5
EZ
4249/* Copy src state preserving dst->parent and dst->live fields */
4250static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4251{
4252 struct bpf_reg_state *parent = dst->parent;
4253 enum bpf_reg_liveness live = dst->live;
4254
4255 *dst = *src;
4256 dst->parent = parent;
4257 dst->live = live;
4258}
4259
f7cf25b2 4260static void save_register_state(struct bpf_func_state *state,
354e8f19
MKL
4261 int spi, struct bpf_reg_state *reg,
4262 int size)
f7cf25b2
AS
4263{
4264 int i;
4265
71f656a5 4266 copy_register_state(&state->stack[spi].spilled_ptr, reg);
354e8f19
MKL
4267 if (size == BPF_REG_SIZE)
4268 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
f7cf25b2 4269
354e8f19
MKL
4270 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4271 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
f7cf25b2 4272
354e8f19
MKL
4273 /* size < 8 bytes spill */
4274 for (; i; i--)
4275 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
f7cf25b2
AS
4276}
4277
ecdf985d
EZ
4278static bool is_bpf_st_mem(struct bpf_insn *insn)
4279{
4280 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4281}
4282
01f810ac 4283/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
4284 * stack boundary and alignment are checked in check_mem_access()
4285 */
01f810ac
AM
4286static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4287 /* stack frame we're writing to */
4288 struct bpf_func_state *state,
4289 int off, int size, int value_regno,
4290 int insn_idx)
17a52670 4291{
f4d7e40a 4292 struct bpf_func_state *cur; /* state of the current function */
638f5b90 4293 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
ecdf985d 4294 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
f7cf25b2 4295 struct bpf_reg_state *reg = NULL;
ecdf985d 4296 u32 dst_reg = insn->dst_reg;
638f5b90 4297
c69431aa 4298 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
4299 if (err)
4300 return err;
9c399760
AS
4301 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4302 * so it's aligned access and [off, off + size) are within stack limits
4303 */
638f5b90
AS
4304 if (!env->allow_ptr_leaks &&
4305 state->stack[spi].slot_type[0] == STACK_SPILL &&
4306 size != BPF_REG_SIZE) {
4307 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4308 return -EACCES;
4309 }
17a52670 4310
f4d7e40a 4311 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
4312 if (value_regno >= 0)
4313 reg = &cur->regs[value_regno];
2039f26f
DB
4314 if (!env->bypass_spec_v4) {
4315 bool sanitize = reg && is_spillable_regtype(reg->type);
4316
4317 for (i = 0; i < size; i++) {
e4f4db47
LG
4318 u8 type = state->stack[spi].slot_type[i];
4319
4320 if (type != STACK_MISC && type != STACK_ZERO) {
2039f26f
DB
4321 sanitize = true;
4322 break;
4323 }
4324 }
4325
4326 if (sanitize)
4327 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4328 }
17a52670 4329
ef8fc7a0
KKD
4330 err = destroy_if_dynptr_stack_slot(env, state, spi);
4331 if (err)
4332 return err;
4333
0f55f9ed 4334 mark_stack_slot_scratched(env, spi);
354e8f19 4335 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2c78ee89 4336 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
4337 if (dst_reg != BPF_REG_FP) {
4338 /* The backtracking logic can only recognize explicit
4339 * stack slot address like [fp - 8]. Other spill of
8fb33b60 4340 * scalar via different register has to be conservative.
b5dc0163
AS
4341 * Backtrack from here and mark all registers as precise
4342 * that contributed into 'reg' being a constant.
4343 */
4344 err = mark_chain_precision(env, value_regno);
4345 if (err)
4346 return err;
4347 }
354e8f19 4348 save_register_state(state, spi, reg, size);
713274f1
MM
4349 /* Break the relation on a narrowing spill. */
4350 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4351 state->stack[spi].spilled_ptr.id = 0;
ecdf985d
EZ
4352 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4353 insn->imm != 0 && env->bpf_capable) {
4354 struct bpf_reg_state fake_reg = {};
4355
4356 __mark_reg_known(&fake_reg, (u32)insn->imm);
4357 fake_reg.type = SCALAR_VALUE;
4358 save_register_state(state, spi, &fake_reg, size);
f7cf25b2 4359 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 4360 /* register containing pointer is being spilled into stack */
9c399760 4361 if (size != BPF_REG_SIZE) {
f7cf25b2 4362 verbose_linfo(env, insn_idx, "; ");
61bd5218 4363 verbose(env, "invalid size of register spill\n");
17a52670
AS
4364 return -EACCES;
4365 }
f7cf25b2 4366 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
4367 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4368 return -EINVAL;
4369 }
354e8f19 4370 save_register_state(state, spi, reg, size);
9c399760 4371 } else {
cc2b14d5
AS
4372 u8 type = STACK_MISC;
4373
679c782d
EC
4374 /* regular write of data into stack destroys any spilled ptr */
4375 state->stack[spi].spilled_ptr.type = NOT_INIT;
06accc87
AN
4376 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4377 if (is_stack_slot_special(&state->stack[spi]))
0bae2d4d 4378 for (i = 0; i < BPF_REG_SIZE; i++)
354e8f19 4379 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
9c399760 4380
cc2b14d5
AS
4381 /* only mark the slot as written if all 8 bytes were written
4382 * otherwise read propagation may incorrectly stop too soon
4383 * when stack slots are partially written.
4384 * This heuristic means that read propagation will be
4385 * conservative, since it will add reg_live_read marks
4386 * to stack slots all the way to first state when programs
4387 * writes+reads less than 8 bytes
4388 */
4389 if (size == BPF_REG_SIZE)
4390 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4391
4392 /* when we zero initialize stack slots mark them as such */
ecdf985d
EZ
4393 if ((reg && register_is_null(reg)) ||
4394 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
b5dc0163
AS
4395 /* backtracking doesn't work for STACK_ZERO yet. */
4396 err = mark_chain_precision(env, value_regno);
4397 if (err)
4398 return err;
cc2b14d5 4399 type = STACK_ZERO;
b5dc0163 4400 }
cc2b14d5 4401
0bae2d4d 4402 /* Mark slots affected by this stack write. */
9c399760 4403 for (i = 0; i < size; i++)
638f5b90 4404 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 4405 type;
17a52670
AS
4406 }
4407 return 0;
4408}
4409
01f810ac
AM
4410/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4411 * known to contain a variable offset.
4412 * This function checks whether the write is permitted and conservatively
4413 * tracks the effects of the write, considering that each stack slot in the
4414 * dynamic range is potentially written to.
4415 *
4416 * 'off' includes 'regno->off'.
4417 * 'value_regno' can be -1, meaning that an unknown value is being written to
4418 * the stack.
4419 *
4420 * Spilled pointers in range are not marked as written because we don't know
4421 * what's going to be actually written. This means that read propagation for
4422 * future reads cannot be terminated by this write.
4423 *
4424 * For privileged programs, uninitialized stack slots are considered
4425 * initialized by this write (even though we don't know exactly what offsets
4426 * are going to be written to). The idea is that we don't want the verifier to
4427 * reject future reads that access slots written to through variable offsets.
4428 */
4429static int check_stack_write_var_off(struct bpf_verifier_env *env,
4430 /* func where register points to */
4431 struct bpf_func_state *state,
4432 int ptr_regno, int off, int size,
4433 int value_regno, int insn_idx)
4434{
4435 struct bpf_func_state *cur; /* state of the current function */
4436 int min_off, max_off;
4437 int i, err;
4438 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
31ff2135 4439 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
01f810ac
AM
4440 bool writing_zero = false;
4441 /* set if the fact that we're writing a zero is used to let any
4442 * stack slots remain STACK_ZERO
4443 */
4444 bool zero_used = false;
4445
4446 cur = env->cur_state->frame[env->cur_state->curframe];
4447 ptr_reg = &cur->regs[ptr_regno];
4448 min_off = ptr_reg->smin_value + off;
4449 max_off = ptr_reg->smax_value + off + size;
4450 if (value_regno >= 0)
4451 value_reg = &cur->regs[value_regno];
31ff2135
EZ
4452 if ((value_reg && register_is_null(value_reg)) ||
4453 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
01f810ac
AM
4454 writing_zero = true;
4455
c69431aa 4456 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
4457 if (err)
4458 return err;
4459
ef8fc7a0
KKD
4460 for (i = min_off; i < max_off; i++) {
4461 int spi;
4462
4463 spi = __get_spi(i);
4464 err = destroy_if_dynptr_stack_slot(env, state, spi);
4465 if (err)
4466 return err;
4467 }
01f810ac
AM
4468
4469 /* Variable offset writes destroy any spilled pointers in range. */
4470 for (i = min_off; i < max_off; i++) {
4471 u8 new_type, *stype;
4472 int slot, spi;
4473
4474 slot = -i - 1;
4475 spi = slot / BPF_REG_SIZE;
4476 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
0f55f9ed 4477 mark_stack_slot_scratched(env, spi);
01f810ac 4478
f5e477a8
KKD
4479 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4480 /* Reject the write if range we may write to has not
4481 * been initialized beforehand. If we didn't reject
4482 * here, the ptr status would be erased below (even
4483 * though not all slots are actually overwritten),
4484 * possibly opening the door to leaks.
4485 *
4486 * We do however catch STACK_INVALID case below, and
4487 * only allow reading possibly uninitialized memory
4488 * later for CAP_PERFMON, as the write may not happen to
4489 * that slot.
01f810ac
AM
4490 */
4491 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4492 insn_idx, i);
4493 return -EINVAL;
4494 }
4495
4496 /* Erase all spilled pointers. */
4497 state->stack[spi].spilled_ptr.type = NOT_INIT;
4498
4499 /* Update the slot type. */
4500 new_type = STACK_MISC;
4501 if (writing_zero && *stype == STACK_ZERO) {
4502 new_type = STACK_ZERO;
4503 zero_used = true;
4504 }
4505 /* If the slot is STACK_INVALID, we check whether it's OK to
4506 * pretend that it will be initialized by this write. The slot
4507 * might not actually be written to, and so if we mark it as
4508 * initialized future reads might leak uninitialized memory.
4509 * For privileged programs, we will accept such reads to slots
4510 * that may or may not be written because, if we're reject
4511 * them, the error would be too confusing.
4512 */
4513 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4514 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4515 insn_idx, i);
4516 return -EINVAL;
4517 }
4518 *stype = new_type;
4519 }
4520 if (zero_used) {
4521 /* backtracking doesn't work for STACK_ZERO yet. */
4522 err = mark_chain_precision(env, value_regno);
4523 if (err)
4524 return err;
4525 }
4526 return 0;
4527}
4528
4529/* When register 'dst_regno' is assigned some values from stack[min_off,
4530 * max_off), we set the register's type according to the types of the
4531 * respective stack slots. If all the stack values are known to be zeros, then
4532 * so is the destination reg. Otherwise, the register is considered to be
4533 * SCALAR. This function does not deal with register filling; the caller must
4534 * ensure that all spilled registers in the stack range have been marked as
4535 * read.
4536 */
4537static void mark_reg_stack_read(struct bpf_verifier_env *env,
4538 /* func where src register points to */
4539 struct bpf_func_state *ptr_state,
4540 int min_off, int max_off, int dst_regno)
4541{
4542 struct bpf_verifier_state *vstate = env->cur_state;
4543 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4544 int i, slot, spi;
4545 u8 *stype;
4546 int zeros = 0;
4547
4548 for (i = min_off; i < max_off; i++) {
4549 slot = -i - 1;
4550 spi = slot / BPF_REG_SIZE;
e0bf4622 4551 mark_stack_slot_scratched(env, spi);
01f810ac
AM
4552 stype = ptr_state->stack[spi].slot_type;
4553 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4554 break;
4555 zeros++;
4556 }
4557 if (zeros == max_off - min_off) {
4558 /* any access_size read into register is zero extended,
4559 * so the whole register == const_zero
4560 */
4561 __mark_reg_const_zero(&state->regs[dst_regno]);
4562 /* backtracking doesn't support STACK_ZERO yet,
4563 * so mark it precise here, so that later
4564 * backtracking can stop here.
4565 * Backtracking may not need this if this register
4566 * doesn't participate in pointer adjustment.
4567 * Forward propagation of precise flag is not
4568 * necessary either. This mark is only to stop
4569 * backtracking. Any register that contributed
4570 * to const 0 was marked precise before spill.
4571 */
4572 state->regs[dst_regno].precise = true;
4573 } else {
4574 /* have read misc data from the stack */
4575 mark_reg_unknown(env, state->regs, dst_regno);
4576 }
4577 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4578}
4579
4580/* Read the stack at 'off' and put the results into the register indicated by
4581 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4582 * spilled reg.
4583 *
4584 * 'dst_regno' can be -1, meaning that the read value is not going to a
4585 * register.
4586 *
4587 * The access is assumed to be within the current stack bounds.
4588 */
4589static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4590 /* func where src register points to */
4591 struct bpf_func_state *reg_state,
4592 int off, int size, int dst_regno)
17a52670 4593{
f4d7e40a
AS
4594 struct bpf_verifier_state *vstate = env->cur_state;
4595 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 4596 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 4597 struct bpf_reg_state *reg;
354e8f19 4598 u8 *stype, type;
17a52670 4599
f4d7e40a 4600 stype = reg_state->stack[spi].slot_type;
f7cf25b2 4601 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 4602
e0bf4622
AN
4603 mark_stack_slot_scratched(env, spi);
4604
27113c59 4605 if (is_spilled_reg(&reg_state->stack[spi])) {
f30d4968
MKL
4606 u8 spill_size = 1;
4607
4608 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4609 spill_size++;
354e8f19 4610
f30d4968 4611 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
f7cf25b2
AS
4612 if (reg->type != SCALAR_VALUE) {
4613 verbose_linfo(env, env->insn_idx, "; ");
4614 verbose(env, "invalid size of register fill\n");
4615 return -EACCES;
4616 }
354e8f19
MKL
4617
4618 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4619 if (dst_regno < 0)
4620 return 0;
4621
f30d4968 4622 if (!(off % BPF_REG_SIZE) && size == spill_size) {
354e8f19
MKL
4623 /* The earlier check_reg_arg() has decided the
4624 * subreg_def for this insn. Save it first.
4625 */
4626 s32 subreg_def = state->regs[dst_regno].subreg_def;
4627
71f656a5 4628 copy_register_state(&state->regs[dst_regno], reg);
354e8f19
MKL
4629 state->regs[dst_regno].subreg_def = subreg_def;
4630 } else {
4631 for (i = 0; i < size; i++) {
4632 type = stype[(slot - i) % BPF_REG_SIZE];
4633 if (type == STACK_SPILL)
4634 continue;
4635 if (type == STACK_MISC)
4636 continue;
6715df8d
EZ
4637 if (type == STACK_INVALID && env->allow_uninit_stack)
4638 continue;
354e8f19
MKL
4639 verbose(env, "invalid read from stack off %d+%d size %d\n",
4640 off, i, size);
4641 return -EACCES;
4642 }
01f810ac 4643 mark_reg_unknown(env, state->regs, dst_regno);
f7cf25b2 4644 }
354e8f19 4645 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2 4646 return 0;
17a52670 4647 }
17a52670 4648
01f810ac 4649 if (dst_regno >= 0) {
17a52670 4650 /* restore register state from stack */
71f656a5 4651 copy_register_state(&state->regs[dst_regno], reg);
2f18f62e
AS
4652 /* mark reg as written since spilled pointer state likely
4653 * has its liveness marks cleared by is_state_visited()
4654 * which resets stack/reg liveness for state transitions
4655 */
01f810ac 4656 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 4657 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 4658 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
4659 * it is acceptable to use this value as a SCALAR_VALUE
4660 * (e.g. for XADD).
4661 * We must not allow unprivileged callers to do that
4662 * with spilled pointers.
4663 */
4664 verbose(env, "leaking pointer from stack off %d\n",
4665 off);
4666 return -EACCES;
dc503a8a 4667 }
f7cf25b2 4668 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670
AS
4669 } else {
4670 for (i = 0; i < size; i++) {
01f810ac
AM
4671 type = stype[(slot - i) % BPF_REG_SIZE];
4672 if (type == STACK_MISC)
cc2b14d5 4673 continue;
01f810ac 4674 if (type == STACK_ZERO)
cc2b14d5 4675 continue;
6715df8d
EZ
4676 if (type == STACK_INVALID && env->allow_uninit_stack)
4677 continue;
cc2b14d5
AS
4678 verbose(env, "invalid read from stack off %d+%d size %d\n",
4679 off, i, size);
4680 return -EACCES;
4681 }
f7cf25b2 4682 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
4683 if (dst_regno >= 0)
4684 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 4685 }
f7cf25b2 4686 return 0;
17a52670
AS
4687}
4688
61df10c7 4689enum bpf_access_src {
01f810ac
AM
4690 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4691 ACCESS_HELPER = 2, /* the access is performed by a helper */
4692};
4693
4694static int check_stack_range_initialized(struct bpf_verifier_env *env,
4695 int regno, int off, int access_size,
4696 bool zero_size_allowed,
61df10c7 4697 enum bpf_access_src type,
01f810ac
AM
4698 struct bpf_call_arg_meta *meta);
4699
4700static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4701{
4702 return cur_regs(env) + regno;
4703}
4704
4705/* Read the stack at 'ptr_regno + off' and put the result into the register
4706 * 'dst_regno'.
4707 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4708 * but not its variable offset.
4709 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4710 *
4711 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4712 * filling registers (i.e. reads of spilled register cannot be detected when
4713 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4714 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4715 * offset; for a fixed offset check_stack_read_fixed_off should be used
4716 * instead.
4717 */
4718static int check_stack_read_var_off(struct bpf_verifier_env *env,
4719 int ptr_regno, int off, int size, int dst_regno)
e4298d25 4720{
01f810ac
AM
4721 /* The state of the source register. */
4722 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4723 struct bpf_func_state *ptr_state = func(env, reg);
4724 int err;
4725 int min_off, max_off;
4726
4727 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 4728 */
01f810ac
AM
4729 err = check_stack_range_initialized(env, ptr_regno, off, size,
4730 false, ACCESS_DIRECT, NULL);
4731 if (err)
4732 return err;
4733
4734 min_off = reg->smin_value + off;
4735 max_off = reg->smax_value + off;
4736 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4737 return 0;
4738}
4739
4740/* check_stack_read dispatches to check_stack_read_fixed_off or
4741 * check_stack_read_var_off.
4742 *
4743 * The caller must ensure that the offset falls within the allocated stack
4744 * bounds.
4745 *
4746 * 'dst_regno' is a register which will receive the value from the stack. It
4747 * can be -1, meaning that the read value is not going to a register.
4748 */
4749static int check_stack_read(struct bpf_verifier_env *env,
4750 int ptr_regno, int off, int size,
4751 int dst_regno)
4752{
4753 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4754 struct bpf_func_state *state = func(env, reg);
4755 int err;
4756 /* Some accesses are only permitted with a static offset. */
4757 bool var_off = !tnum_is_const(reg->var_off);
4758
4759 /* The offset is required to be static when reads don't go to a
4760 * register, in order to not leak pointers (see
4761 * check_stack_read_fixed_off).
4762 */
4763 if (dst_regno < 0 && var_off) {
e4298d25
DB
4764 char tn_buf[48];
4765
4766 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 4767 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
4768 tn_buf, off, size);
4769 return -EACCES;
4770 }
01f810ac
AM
4771 /* Variable offset is prohibited for unprivileged mode for simplicity
4772 * since it requires corresponding support in Spectre masking for stack
082cdc69
LG
4773 * ALU. See also retrieve_ptr_limit(). The check in
4774 * check_stack_access_for_ptr_arithmetic() called by
4775 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4776 * with variable offsets, therefore no check is required here. Further,
4777 * just checking it here would be insufficient as speculative stack
4778 * writes could still lead to unsafe speculative behaviour.
01f810ac 4779 */
01f810ac
AM
4780 if (!var_off) {
4781 off += reg->var_off.value;
4782 err = check_stack_read_fixed_off(env, state, off, size,
4783 dst_regno);
4784 } else {
4785 /* Variable offset stack reads need more conservative handling
4786 * than fixed offset ones. Note that dst_regno >= 0 on this
4787 * branch.
4788 */
4789 err = check_stack_read_var_off(env, ptr_regno, off, size,
4790 dst_regno);
4791 }
4792 return err;
4793}
4794
4795
4796/* check_stack_write dispatches to check_stack_write_fixed_off or
4797 * check_stack_write_var_off.
4798 *
4799 * 'ptr_regno' is the register used as a pointer into the stack.
4800 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4801 * 'value_regno' is the register whose value we're writing to the stack. It can
4802 * be -1, meaning that we're not writing from a register.
4803 *
4804 * The caller must ensure that the offset falls within the maximum stack size.
4805 */
4806static int check_stack_write(struct bpf_verifier_env *env,
4807 int ptr_regno, int off, int size,
4808 int value_regno, int insn_idx)
4809{
4810 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4811 struct bpf_func_state *state = func(env, reg);
4812 int err;
4813
4814 if (tnum_is_const(reg->var_off)) {
4815 off += reg->var_off.value;
4816 err = check_stack_write_fixed_off(env, state, off, size,
4817 value_regno, insn_idx);
4818 } else {
4819 /* Variable offset stack reads need more conservative handling
4820 * than fixed offset ones.
4821 */
4822 err = check_stack_write_var_off(env, state,
4823 ptr_regno, off, size,
4824 value_regno, insn_idx);
4825 }
4826 return err;
e4298d25
DB
4827}
4828
591fe988
DB
4829static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4830 int off, int size, enum bpf_access_type type)
4831{
4832 struct bpf_reg_state *regs = cur_regs(env);
4833 struct bpf_map *map = regs[regno].map_ptr;
4834 u32 cap = bpf_map_flags_to_cap(map);
4835
4836 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4837 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4838 map->value_size, off, size);
4839 return -EACCES;
4840 }
4841
4842 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4843 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4844 map->value_size, off, size);
4845 return -EACCES;
4846 }
4847
4848 return 0;
4849}
4850
457f4436
AN
4851/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4852static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4853 int off, int size, u32 mem_size,
4854 bool zero_size_allowed)
17a52670 4855{
457f4436
AN
4856 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4857 struct bpf_reg_state *reg;
4858
4859 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4860 return 0;
17a52670 4861
457f4436
AN
4862 reg = &cur_regs(env)[regno];
4863 switch (reg->type) {
69c087ba
YS
4864 case PTR_TO_MAP_KEY:
4865 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4866 mem_size, off, size);
4867 break;
457f4436 4868 case PTR_TO_MAP_VALUE:
61bd5218 4869 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
4870 mem_size, off, size);
4871 break;
4872 case PTR_TO_PACKET:
4873 case PTR_TO_PACKET_META:
4874 case PTR_TO_PACKET_END:
4875 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4876 off, size, regno, reg->id, off, mem_size);
4877 break;
4878 case PTR_TO_MEM:
4879 default:
4880 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4881 mem_size, off, size);
17a52670 4882 }
457f4436
AN
4883
4884 return -EACCES;
17a52670
AS
4885}
4886
457f4436
AN
4887/* check read/write into a memory region with possible variable offset */
4888static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4889 int off, int size, u32 mem_size,
4890 bool zero_size_allowed)
dbcfe5f7 4891{
f4d7e40a
AS
4892 struct bpf_verifier_state *vstate = env->cur_state;
4893 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
4894 struct bpf_reg_state *reg = &state->regs[regno];
4895 int err;
4896
457f4436 4897 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
4898 * need to try adding each of min_value and max_value to off
4899 * to make sure our theoretical access will be safe.
2e576648
CL
4900 *
4901 * The minimum value is only important with signed
dbcfe5f7
GB
4902 * comparisons where we can't assume the floor of a
4903 * value is 0. If we are using signed variables for our
4904 * index'es we need to make sure that whatever we use
4905 * will have a set floor within our range.
4906 */
b7137c4e
DB
4907 if (reg->smin_value < 0 &&
4908 (reg->smin_value == S64_MIN ||
4909 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4910 reg->smin_value + off < 0)) {
61bd5218 4911 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
4912 regno);
4913 return -EACCES;
4914 }
457f4436
AN
4915 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4916 mem_size, zero_size_allowed);
dbcfe5f7 4917 if (err) {
457f4436 4918 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 4919 regno);
dbcfe5f7
GB
4920 return err;
4921 }
4922
b03c9f9f
EC
4923 /* If we haven't set a max value then we need to bail since we can't be
4924 * sure we won't do bad things.
4925 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 4926 */
b03c9f9f 4927 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 4928 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
4929 regno);
4930 return -EACCES;
4931 }
457f4436
AN
4932 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4933 mem_size, zero_size_allowed);
4934 if (err) {
4935 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 4936 regno);
457f4436
AN
4937 return err;
4938 }
4939
4940 return 0;
4941}
d83525ca 4942
e9147b44
KKD
4943static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4944 const struct bpf_reg_state *reg, int regno,
4945 bool fixed_off_ok)
4946{
4947 /* Access to this pointer-typed register or passing it to a helper
4948 * is only allowed in its original, unmodified form.
4949 */
4950
4951 if (reg->off < 0) {
4952 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4953 reg_type_str(env, reg->type), regno, reg->off);
4954 return -EACCES;
4955 }
4956
4957 if (!fixed_off_ok && reg->off) {
4958 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4959 reg_type_str(env, reg->type), regno, reg->off);
4960 return -EACCES;
4961 }
4962
4963 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4964 char tn_buf[48];
4965
4966 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4967 verbose(env, "variable %s access var_off=%s disallowed\n",
4968 reg_type_str(env, reg->type), tn_buf);
4969 return -EACCES;
4970 }
4971
4972 return 0;
4973}
4974
4975int check_ptr_off_reg(struct bpf_verifier_env *env,
4976 const struct bpf_reg_state *reg, int regno)
4977{
4978 return __check_ptr_off_reg(env, reg, regno, false);
4979}
4980
61df10c7 4981static int map_kptr_match_type(struct bpf_verifier_env *env,
aa3496ac 4982 struct btf_field *kptr_field,
61df10c7
KKD
4983 struct bpf_reg_state *reg, u32 regno)
4984{
b32a5dae 4985 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
20c09d92 4986 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
61df10c7
KKD
4987 const char *reg_name = "";
4988
6efe152d 4989 /* Only unreferenced case accepts untrusted pointers */
aa3496ac 4990 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
4991 perm_flags |= PTR_UNTRUSTED;
4992
4993 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
61df10c7
KKD
4994 goto bad_type;
4995
4996 if (!btf_is_kernel(reg->btf)) {
4997 verbose(env, "R%d must point to kernel BTF\n", regno);
4998 return -EINVAL;
4999 }
5000 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
b32a5dae 5001 reg_name = btf_type_name(reg->btf, reg->btf_id);
61df10c7 5002
c0a5a21c
KKD
5003 /* For ref_ptr case, release function check should ensure we get one
5004 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5005 * normal store of unreferenced kptr, we must ensure var_off is zero.
5006 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5007 * reg->off and reg->ref_obj_id are not needed here.
5008 */
61df10c7
KKD
5009 if (__check_ptr_off_reg(env, reg, regno, true))
5010 return -EACCES;
5011
5012 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5013 * we also need to take into account the reg->off.
5014 *
5015 * We want to support cases like:
5016 *
5017 * struct foo {
5018 * struct bar br;
5019 * struct baz bz;
5020 * };
5021 *
5022 * struct foo *v;
5023 * v = func(); // PTR_TO_BTF_ID
5024 * val->foo = v; // reg->off is zero, btf and btf_id match type
5025 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5026 * // first member type of struct after comparison fails
5027 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5028 * // to match type
5029 *
5030 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
2ab3b380
KKD
5031 * is zero. We must also ensure that btf_struct_ids_match does not walk
5032 * the struct to match type against first member of struct, i.e. reject
5033 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5034 * strict mode to true for type match.
61df10c7
KKD
5035 */
5036 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
aa3496ac
KKD
5037 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5038 kptr_field->type == BPF_KPTR_REF))
61df10c7
KKD
5039 goto bad_type;
5040 return 0;
5041bad_type:
5042 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5043 reg_type_str(env, reg->type), reg_name);
6efe152d 5044 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
aa3496ac 5045 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
5046 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5047 targ_name);
5048 else
5049 verbose(env, "\n");
61df10c7
KKD
5050 return -EINVAL;
5051}
5052
20c09d92
AS
5053/* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5054 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5055 */
5056static bool in_rcu_cs(struct bpf_verifier_env *env)
5057{
5058 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5059}
5060
5061/* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5062BTF_SET_START(rcu_protected_types)
5063BTF_ID(struct, prog_test_ref_kfunc)
5064BTF_ID(struct, cgroup)
63d2d83d 5065BTF_ID(struct, bpf_cpumask)
d02c48fa 5066BTF_ID(struct, task_struct)
20c09d92
AS
5067BTF_SET_END(rcu_protected_types)
5068
5069static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5070{
5071 if (!btf_is_kernel(btf))
5072 return false;
5073 return btf_id_set_contains(&rcu_protected_types, btf_id);
5074}
5075
5076static bool rcu_safe_kptr(const struct btf_field *field)
5077{
5078 const struct btf_field_kptr *kptr = &field->kptr;
5079
5080 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5081}
5082
61df10c7
KKD
5083static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5084 int value_regno, int insn_idx,
aa3496ac 5085 struct btf_field *kptr_field)
61df10c7
KKD
5086{
5087 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5088 int class = BPF_CLASS(insn->code);
5089 struct bpf_reg_state *val_reg;
5090
5091 /* Things we already checked for in check_map_access and caller:
5092 * - Reject cases where variable offset may touch kptr
5093 * - size of access (must be BPF_DW)
5094 * - tnum_is_const(reg->var_off)
aa3496ac 5095 * - kptr_field->offset == off + reg->var_off.value
61df10c7
KKD
5096 */
5097 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5098 if (BPF_MODE(insn->code) != BPF_MEM) {
5099 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5100 return -EACCES;
5101 }
5102
6efe152d
KKD
5103 /* We only allow loading referenced kptr, since it will be marked as
5104 * untrusted, similar to unreferenced kptr.
5105 */
aa3496ac 5106 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
6efe152d 5107 verbose(env, "store to referenced kptr disallowed\n");
c0a5a21c
KKD
5108 return -EACCES;
5109 }
5110
61df10c7
KKD
5111 if (class == BPF_LDX) {
5112 val_reg = reg_state(env, value_regno);
5113 /* We can simply mark the value_regno receiving the pointer
5114 * value from map as PTR_TO_BTF_ID, with the correct type.
5115 */
aa3496ac 5116 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
20c09d92
AS
5117 kptr_field->kptr.btf_id,
5118 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5119 PTR_MAYBE_NULL | MEM_RCU :
5120 PTR_MAYBE_NULL | PTR_UNTRUSTED);
61df10c7
KKD
5121 /* For mark_ptr_or_null_reg */
5122 val_reg->id = ++env->id_gen;
5123 } else if (class == BPF_STX) {
5124 val_reg = reg_state(env, value_regno);
5125 if (!register_is_null(val_reg) &&
aa3496ac 5126 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
61df10c7
KKD
5127 return -EACCES;
5128 } else if (class == BPF_ST) {
5129 if (insn->imm) {
5130 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
aa3496ac 5131 kptr_field->offset);
61df10c7
KKD
5132 return -EACCES;
5133 }
5134 } else {
5135 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5136 return -EACCES;
5137 }
5138 return 0;
5139}
5140
457f4436
AN
5141/* check read/write into a map element with possible variable offset */
5142static int check_map_access(struct bpf_verifier_env *env, u32 regno,
61df10c7
KKD
5143 int off, int size, bool zero_size_allowed,
5144 enum bpf_access_src src)
457f4436
AN
5145{
5146 struct bpf_verifier_state *vstate = env->cur_state;
5147 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5148 struct bpf_reg_state *reg = &state->regs[regno];
5149 struct bpf_map *map = reg->map_ptr;
aa3496ac
KKD
5150 struct btf_record *rec;
5151 int err, i;
457f4436
AN
5152
5153 err = check_mem_region_access(env, regno, off, size, map->value_size,
5154 zero_size_allowed);
5155 if (err)
5156 return err;
5157
aa3496ac
KKD
5158 if (IS_ERR_OR_NULL(map->record))
5159 return 0;
5160 rec = map->record;
5161 for (i = 0; i < rec->cnt; i++) {
5162 struct btf_field *field = &rec->fields[i];
5163 u32 p = field->offset;
d83525ca 5164
db559117
KKD
5165 /* If any part of a field can be touched by load/store, reject
5166 * this program. To check that [x1, x2) overlaps with [y1, y2),
d83525ca
AS
5167 * it is sufficient to check x1 < y2 && y1 < x2.
5168 */
aa3496ac
KKD
5169 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5170 p < reg->umax_value + off + size) {
5171 switch (field->type) {
5172 case BPF_KPTR_UNREF:
5173 case BPF_KPTR_REF:
61df10c7
KKD
5174 if (src != ACCESS_DIRECT) {
5175 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5176 return -EACCES;
5177 }
5178 if (!tnum_is_const(reg->var_off)) {
5179 verbose(env, "kptr access cannot have variable offset\n");
5180 return -EACCES;
5181 }
5182 if (p != off + reg->var_off.value) {
5183 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5184 p, off + reg->var_off.value);
5185 return -EACCES;
5186 }
5187 if (size != bpf_size_to_bytes(BPF_DW)) {
5188 verbose(env, "kptr access size must be BPF_DW\n");
5189 return -EACCES;
5190 }
5191 break;
aa3496ac 5192 default:
db559117
KKD
5193 verbose(env, "%s cannot be accessed directly by load/store\n",
5194 btf_field_type_name(field->type));
aa3496ac 5195 return -EACCES;
61df10c7
KKD
5196 }
5197 }
5198 }
aa3496ac 5199 return 0;
dbcfe5f7
GB
5200}
5201
969bf05e
AS
5202#define MAX_PACKET_OFF 0xffff
5203
58e2af8b 5204static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
5205 const struct bpf_call_arg_meta *meta,
5206 enum bpf_access_type t)
4acf6c0b 5207{
7e40781c
UP
5208 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5209
5210 switch (prog_type) {
5d66fa7d 5211 /* Program types only with direct read access go here! */
3a0af8fd
TG
5212 case BPF_PROG_TYPE_LWT_IN:
5213 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 5214 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 5215 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 5216 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 5217 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
5218 if (t == BPF_WRITE)
5219 return false;
8731745e 5220 fallthrough;
5d66fa7d
DB
5221
5222 /* Program types with direct read + write access go here! */
36bbef52
DB
5223 case BPF_PROG_TYPE_SCHED_CLS:
5224 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 5225 case BPF_PROG_TYPE_XDP:
3a0af8fd 5226 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 5227 case BPF_PROG_TYPE_SK_SKB:
4f738adb 5228 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
5229 if (meta)
5230 return meta->pkt_access;
5231
5232 env->seen_direct_write = true;
4acf6c0b 5233 return true;
0d01da6a
SF
5234
5235 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5236 if (t == BPF_WRITE)
5237 env->seen_direct_write = true;
5238
5239 return true;
5240
4acf6c0b
BB
5241 default:
5242 return false;
5243 }
5244}
5245
f1174f77 5246static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 5247 int size, bool zero_size_allowed)
f1174f77 5248{
638f5b90 5249 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
5250 struct bpf_reg_state *reg = &regs[regno];
5251 int err;
5252
5253 /* We may have added a variable offset to the packet pointer; but any
5254 * reg->range we have comes after that. We are only checking the fixed
5255 * offset.
5256 */
5257
5258 /* We don't allow negative numbers, because we aren't tracking enough
5259 * detail to prove they're safe.
5260 */
b03c9f9f 5261 if (reg->smin_value < 0) {
61bd5218 5262 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
5263 regno);
5264 return -EACCES;
5265 }
6d94e741
AS
5266
5267 err = reg->range < 0 ? -EINVAL :
5268 __check_mem_access(env, regno, off, size, reg->range,
457f4436 5269 zero_size_allowed);
f1174f77 5270 if (err) {
61bd5218 5271 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
5272 return err;
5273 }
e647815a 5274
457f4436 5275 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
5276 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5277 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 5278 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
5279 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5280 */
5281 env->prog->aux->max_pkt_offset =
5282 max_t(u32, env->prog->aux->max_pkt_offset,
5283 off + reg->umax_value + size - 1);
5284
f1174f77
EC
5285 return err;
5286}
5287
5288/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 5289static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 5290 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 5291 struct btf **btf, u32 *btf_id)
17a52670 5292{
f96da094
DB
5293 struct bpf_insn_access_aux info = {
5294 .reg_type = *reg_type,
9e15db66 5295 .log = &env->log,
f96da094 5296 };
31fd8581 5297
4f9218aa 5298 if (env->ops->is_valid_access &&
5e43f899 5299 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
5300 /* A non zero info.ctx_field_size indicates that this field is a
5301 * candidate for later verifier transformation to load the whole
5302 * field and then apply a mask when accessed with a narrower
5303 * access than actual ctx access size. A zero info.ctx_field_size
5304 * will only allow for whole field access and rejects any other
5305 * type of narrower access.
31fd8581 5306 */
23994631 5307 *reg_type = info.reg_type;
31fd8581 5308
c25b2ae1 5309 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 5310 *btf = info.btf;
9e15db66 5311 *btf_id = info.btf_id;
22dc4a0f 5312 } else {
9e15db66 5313 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 5314 }
32bbe007
AS
5315 /* remember the offset of last byte accessed in ctx */
5316 if (env->prog->aux->max_ctx_offset < off + size)
5317 env->prog->aux->max_ctx_offset = off + size;
17a52670 5318 return 0;
32bbe007 5319 }
17a52670 5320
61bd5218 5321 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
5322 return -EACCES;
5323}
5324
d58e468b
PP
5325static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5326 int size)
5327{
5328 if (size < 0 || off < 0 ||
5329 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5330 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5331 off, size);
5332 return -EACCES;
5333 }
5334 return 0;
5335}
5336
5f456649
MKL
5337static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5338 u32 regno, int off, int size,
5339 enum bpf_access_type t)
c64b7983
JS
5340{
5341 struct bpf_reg_state *regs = cur_regs(env);
5342 struct bpf_reg_state *reg = &regs[regno];
5f456649 5343 struct bpf_insn_access_aux info = {};
46f8bc92 5344 bool valid;
c64b7983
JS
5345
5346 if (reg->smin_value < 0) {
5347 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5348 regno);
5349 return -EACCES;
5350 }
5351
46f8bc92
MKL
5352 switch (reg->type) {
5353 case PTR_TO_SOCK_COMMON:
5354 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5355 break;
5356 case PTR_TO_SOCKET:
5357 valid = bpf_sock_is_valid_access(off, size, t, &info);
5358 break;
655a51e5
MKL
5359 case PTR_TO_TCP_SOCK:
5360 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5361 break;
fada7fdc
JL
5362 case PTR_TO_XDP_SOCK:
5363 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5364 break;
46f8bc92
MKL
5365 default:
5366 valid = false;
c64b7983
JS
5367 }
5368
5f456649 5369
46f8bc92
MKL
5370 if (valid) {
5371 env->insn_aux_data[insn_idx].ctx_field_size =
5372 info.ctx_field_size;
5373 return 0;
5374 }
5375
5376 verbose(env, "R%d invalid %s access off=%d size=%d\n",
c25b2ae1 5377 regno, reg_type_str(env, reg->type), off, size);
46f8bc92
MKL
5378
5379 return -EACCES;
c64b7983
JS
5380}
5381
4cabc5b1
DB
5382static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5383{
2a159c6f 5384 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
5385}
5386
f37a8cb8
DB
5387static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5388{
2a159c6f 5389 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 5390
46f8bc92
MKL
5391 return reg->type == PTR_TO_CTX;
5392}
5393
5394static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5395{
5396 const struct bpf_reg_state *reg = reg_state(env, regno);
5397
5398 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
5399}
5400
ca369602
DB
5401static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5402{
2a159c6f 5403 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
5404
5405 return type_is_pkt_pointer(reg->type);
5406}
5407
4b5defde
DB
5408static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5409{
5410 const struct bpf_reg_state *reg = reg_state(env, regno);
5411
5412 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5413 return reg->type == PTR_TO_FLOW_KEYS;
5414}
5415
831deb29
AP
5416static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5417#ifdef CONFIG_NET
5418 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5419 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5420 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5421#endif
5ba190c2 5422 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
831deb29
AP
5423};
5424
9bb00b28
YS
5425static bool is_trusted_reg(const struct bpf_reg_state *reg)
5426{
5427 /* A referenced register is always trusted. */
5428 if (reg->ref_obj_id)
5429 return true;
5430
831deb29
AP
5431 /* Types listed in the reg2btf_ids are always trusted */
5432 if (reg2btf_ids[base_type(reg->type)])
5433 return true;
5434
9bb00b28 5435 /* If a register is not referenced, it is trusted if it has the
fca1aa75 5436 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
9bb00b28
YS
5437 * other type modifiers may be safe, but we elect to take an opt-in
5438 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5439 * not.
5440 *
5441 * Eventually, we should make PTR_TRUSTED the single source of truth
5442 * for whether a register is trusted.
5443 */
5444 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5445 !bpf_type_has_unsafe_modifiers(reg->type);
5446}
5447
fca1aa75
YS
5448static bool is_rcu_reg(const struct bpf_reg_state *reg)
5449{
5450 return reg->type & MEM_RCU;
5451}
5452
afeebf9f
AS
5453static void clear_trusted_flags(enum bpf_type_flag *flag)
5454{
5455 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5456}
5457
61bd5218
JK
5458static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5459 const struct bpf_reg_state *reg,
d1174416 5460 int off, int size, bool strict)
969bf05e 5461{
f1174f77 5462 struct tnum reg_off;
e07b98d9 5463 int ip_align;
d1174416
DM
5464
5465 /* Byte size accesses are always allowed. */
5466 if (!strict || size == 1)
5467 return 0;
5468
e4eda884
DM
5469 /* For platforms that do not have a Kconfig enabling
5470 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5471 * NET_IP_ALIGN is universally set to '2'. And on platforms
5472 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5473 * to this code only in strict mode where we want to emulate
5474 * the NET_IP_ALIGN==2 checking. Therefore use an
5475 * unconditional IP align value of '2'.
e07b98d9 5476 */
e4eda884 5477 ip_align = 2;
f1174f77
EC
5478
5479 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5480 if (!tnum_is_aligned(reg_off, size)) {
5481 char tn_buf[48];
5482
5483 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
5484 verbose(env,
5485 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 5486 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
5487 return -EACCES;
5488 }
79adffcd 5489
969bf05e
AS
5490 return 0;
5491}
5492
61bd5218
JK
5493static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5494 const struct bpf_reg_state *reg,
f1174f77
EC
5495 const char *pointer_desc,
5496 int off, int size, bool strict)
79adffcd 5497{
f1174f77
EC
5498 struct tnum reg_off;
5499
5500 /* Byte size accesses are always allowed. */
5501 if (!strict || size == 1)
5502 return 0;
5503
5504 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5505 if (!tnum_is_aligned(reg_off, size)) {
5506 char tn_buf[48];
5507
5508 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 5509 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 5510 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
5511 return -EACCES;
5512 }
5513
969bf05e
AS
5514 return 0;
5515}
5516
e07b98d9 5517static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
5518 const struct bpf_reg_state *reg, int off,
5519 int size, bool strict_alignment_once)
79adffcd 5520{
ca369602 5521 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 5522 const char *pointer_desc = "";
d1174416 5523
79adffcd
DB
5524 switch (reg->type) {
5525 case PTR_TO_PACKET:
de8f3a83
DB
5526 case PTR_TO_PACKET_META:
5527 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5528 * right in front, treat it the very same way.
5529 */
61bd5218 5530 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
5531 case PTR_TO_FLOW_KEYS:
5532 pointer_desc = "flow keys ";
5533 break;
69c087ba
YS
5534 case PTR_TO_MAP_KEY:
5535 pointer_desc = "key ";
5536 break;
f1174f77
EC
5537 case PTR_TO_MAP_VALUE:
5538 pointer_desc = "value ";
5539 break;
5540 case PTR_TO_CTX:
5541 pointer_desc = "context ";
5542 break;
5543 case PTR_TO_STACK:
5544 pointer_desc = "stack ";
01f810ac
AM
5545 /* The stack spill tracking logic in check_stack_write_fixed_off()
5546 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
5547 * aligned.
5548 */
5549 strict = true;
f1174f77 5550 break;
c64b7983
JS
5551 case PTR_TO_SOCKET:
5552 pointer_desc = "sock ";
5553 break;
46f8bc92
MKL
5554 case PTR_TO_SOCK_COMMON:
5555 pointer_desc = "sock_common ";
5556 break;
655a51e5
MKL
5557 case PTR_TO_TCP_SOCK:
5558 pointer_desc = "tcp_sock ";
5559 break;
fada7fdc
JL
5560 case PTR_TO_XDP_SOCK:
5561 pointer_desc = "xdp_sock ";
5562 break;
79adffcd 5563 default:
f1174f77 5564 break;
79adffcd 5565 }
61bd5218
JK
5566 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5567 strict);
79adffcd
DB
5568}
5569
f4d7e40a
AS
5570static int update_stack_depth(struct bpf_verifier_env *env,
5571 const struct bpf_func_state *func,
5572 int off)
5573{
9c8105bd 5574 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
5575
5576 if (stack >= -off)
5577 return 0;
5578
5579 /* update known max for given subprogram */
9c8105bd 5580 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
5581 return 0;
5582}
f4d7e40a 5583
70a87ffe
AS
5584/* starting from main bpf function walk all instructions of the function
5585 * and recursively walk all callees that given function can call.
5586 * Ignore jump and exit insns.
5587 * Since recursion is prevented by check_cfg() this algorithm
5588 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5589 */
b5e9ad52 5590static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
70a87ffe 5591{
9c8105bd 5592 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 5593 struct bpf_insn *insn = env->prog->insnsi;
b5e9ad52 5594 int depth = 0, frame = 0, i, subprog_end;
ebf7d1f5 5595 bool tail_call_reachable = false;
70a87ffe
AS
5596 int ret_insn[MAX_CALL_FRAMES];
5597 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 5598 int j;
f4d7e40a 5599
b5e9ad52 5600 i = subprog[idx].start;
70a87ffe 5601process_func:
7f6e4312
MF
5602 /* protect against potential stack overflow that might happen when
5603 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5604 * depth for such case down to 256 so that the worst case scenario
5605 * would result in 8k stack size (32 which is tailcall limit * 256 =
5606 * 8k).
5607 *
5608 * To get the idea what might happen, see an example:
5609 * func1 -> sub rsp, 128
5610 * subfunc1 -> sub rsp, 256
5611 * tailcall1 -> add rsp, 256
5612 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5613 * subfunc2 -> sub rsp, 64
5614 * subfunc22 -> sub rsp, 128
5615 * tailcall2 -> add rsp, 128
5616 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5617 *
5618 * tailcall will unwind the current stack frame but it will not get rid
5619 * of caller's stack as shown on the example above.
5620 */
5621 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5622 verbose(env,
5623 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5624 depth);
5625 return -EACCES;
5626 }
70a87ffe
AS
5627 /* round up to 32-bytes, since this is granularity
5628 * of interpreter stack size
5629 */
9c8105bd 5630 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 5631 if (depth > MAX_BPF_STACK) {
f4d7e40a 5632 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 5633 frame + 1, depth);
f4d7e40a
AS
5634 return -EACCES;
5635 }
70a87ffe 5636continue_func:
4cb3d99c 5637 subprog_end = subprog[idx + 1].start;
70a87ffe 5638 for (; i < subprog_end; i++) {
ba7b3e7d 5639 int next_insn, sidx;
7ddc80a4 5640
69c087ba 5641 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
5642 continue;
5643 /* remember insn and function to return to */
5644 ret_insn[frame] = i + 1;
9c8105bd 5645 ret_prog[frame] = idx;
70a87ffe
AS
5646
5647 /* find the callee */
7ddc80a4 5648 next_insn = i + insn[i].imm + 1;
ba7b3e7d
KKD
5649 sidx = find_subprog(env, next_insn);
5650 if (sidx < 0) {
70a87ffe 5651 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7ddc80a4 5652 next_insn);
70a87ffe
AS
5653 return -EFAULT;
5654 }
ba7b3e7d
KKD
5655 if (subprog[sidx].is_async_cb) {
5656 if (subprog[sidx].has_tail_call) {
7ddc80a4
AS
5657 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5658 return -EFAULT;
5659 }
5415ccd5
KKD
5660 /* async callbacks don't increase bpf prog stack size unless called directly */
5661 if (!bpf_pseudo_call(insn + i))
5662 continue;
7ddc80a4
AS
5663 }
5664 i = next_insn;
ba7b3e7d 5665 idx = sidx;
ebf7d1f5
MF
5666
5667 if (subprog[idx].has_tail_call)
5668 tail_call_reachable = true;
5669
70a87ffe
AS
5670 frame++;
5671 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
5672 verbose(env, "the call stack of %d frames is too deep !\n",
5673 frame);
5674 return -E2BIG;
70a87ffe
AS
5675 }
5676 goto process_func;
5677 }
ebf7d1f5
MF
5678 /* if tail call got detected across bpf2bpf calls then mark each of the
5679 * currently present subprog frames as tail call reachable subprogs;
5680 * this info will be utilized by JIT so that we will be preserving the
5681 * tail call counter throughout bpf2bpf calls combined with tailcalls
5682 */
5683 if (tail_call_reachable)
5684 for (j = 0; j < frame; j++)
5685 subprog[ret_prog[j]].tail_call_reachable = true;
5dd0a6b8
DB
5686 if (subprog[0].tail_call_reachable)
5687 env->prog->aux->tail_call_reachable = true;
ebf7d1f5 5688
70a87ffe
AS
5689 /* end of for() loop means the last insn of the 'subprog'
5690 * was reached. Doesn't matter whether it was JA or EXIT
5691 */
5692 if (frame == 0)
5693 return 0;
9c8105bd 5694 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
5695 frame--;
5696 i = ret_insn[frame];
9c8105bd 5697 idx = ret_prog[frame];
70a87ffe 5698 goto continue_func;
f4d7e40a
AS
5699}
5700
b5e9ad52
KKD
5701static int check_max_stack_depth(struct bpf_verifier_env *env)
5702{
5703 struct bpf_subprog_info *si = env->subprog_info;
5704 int ret;
5705
5706 for (int i = 0; i < env->subprog_cnt; i++) {
5707 if (!i || si[i].is_async_cb) {
5708 ret = check_max_stack_depth_subprog(env, i);
5709 if (ret < 0)
5710 return ret;
5711 }
5712 continue;
5713 }
5714 return 0;
5715}
5716
19d28fbd 5717#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
5718static int get_callee_stack_depth(struct bpf_verifier_env *env,
5719 const struct bpf_insn *insn, int idx)
5720{
5721 int start = idx + insn->imm + 1, subprog;
5722
5723 subprog = find_subprog(env, start);
5724 if (subprog < 0) {
5725 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5726 start);
5727 return -EFAULT;
5728 }
9c8105bd 5729 return env->subprog_info[subprog].stack_depth;
1ea47e01 5730}
19d28fbd 5731#endif
1ea47e01 5732
afbf21dc
YS
5733static int __check_buffer_access(struct bpf_verifier_env *env,
5734 const char *buf_info,
5735 const struct bpf_reg_state *reg,
5736 int regno, int off, int size)
9df1c28b
MM
5737{
5738 if (off < 0) {
5739 verbose(env,
4fc00b79 5740 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 5741 regno, buf_info, off, size);
9df1c28b
MM
5742 return -EACCES;
5743 }
5744 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5745 char tn_buf[48];
5746
5747 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5748 verbose(env,
4fc00b79 5749 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
5750 regno, off, tn_buf);
5751 return -EACCES;
5752 }
afbf21dc
YS
5753
5754 return 0;
5755}
5756
5757static int check_tp_buffer_access(struct bpf_verifier_env *env,
5758 const struct bpf_reg_state *reg,
5759 int regno, int off, int size)
5760{
5761 int err;
5762
5763 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5764 if (err)
5765 return err;
5766
9df1c28b
MM
5767 if (off + size > env->prog->aux->max_tp_access)
5768 env->prog->aux->max_tp_access = off + size;
5769
5770 return 0;
5771}
5772
afbf21dc
YS
5773static int check_buffer_access(struct bpf_verifier_env *env,
5774 const struct bpf_reg_state *reg,
5775 int regno, int off, int size,
5776 bool zero_size_allowed,
afbf21dc
YS
5777 u32 *max_access)
5778{
44e9a741 5779 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
afbf21dc
YS
5780 int err;
5781
5782 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5783 if (err)
5784 return err;
5785
5786 if (off + size > *max_access)
5787 *max_access = off + size;
5788
5789 return 0;
5790}
5791
3f50f132
JF
5792/* BPF architecture zero extends alu32 ops into 64-bit registesr */
5793static void zext_32_to_64(struct bpf_reg_state *reg)
5794{
5795 reg->var_off = tnum_subreg(reg->var_off);
5796 __reg_assign_32_into_64(reg);
5797}
9df1c28b 5798
0c17d1d2
JH
5799/* truncate register to smaller size (in bytes)
5800 * must be called with size < BPF_REG_SIZE
5801 */
5802static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5803{
5804 u64 mask;
5805
5806 /* clear high bits in bit representation */
5807 reg->var_off = tnum_cast(reg->var_off, size);
5808
5809 /* fix arithmetic bounds */
5810 mask = ((u64)1 << (size * 8)) - 1;
5811 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5812 reg->umin_value &= mask;
5813 reg->umax_value &= mask;
5814 } else {
5815 reg->umin_value = 0;
5816 reg->umax_value = mask;
5817 }
5818 reg->smin_value = reg->umin_value;
5819 reg->smax_value = reg->umax_value;
3f50f132
JF
5820
5821 /* If size is smaller than 32bit register the 32bit register
5822 * values are also truncated so we push 64-bit bounds into
5823 * 32-bit bounds. Above were truncated < 32-bits already.
5824 */
5825 if (size >= 4)
5826 return;
5827 __reg_combine_64_into_32(reg);
0c17d1d2
JH
5828}
5829
1f9a1ea8
YS
5830static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5831{
5832 if (size == 1) {
5833 reg->smin_value = reg->s32_min_value = S8_MIN;
5834 reg->smax_value = reg->s32_max_value = S8_MAX;
5835 } else if (size == 2) {
5836 reg->smin_value = reg->s32_min_value = S16_MIN;
5837 reg->smax_value = reg->s32_max_value = S16_MAX;
5838 } else {
5839 /* size == 4 */
5840 reg->smin_value = reg->s32_min_value = S32_MIN;
5841 reg->smax_value = reg->s32_max_value = S32_MAX;
5842 }
5843 reg->umin_value = reg->u32_min_value = 0;
5844 reg->umax_value = U64_MAX;
5845 reg->u32_max_value = U32_MAX;
5846 reg->var_off = tnum_unknown;
5847}
5848
5849static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5850{
5851 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5852 u64 top_smax_value, top_smin_value;
5853 u64 num_bits = size * 8;
5854
5855 if (tnum_is_const(reg->var_off)) {
5856 u64_cval = reg->var_off.value;
5857 if (size == 1)
5858 reg->var_off = tnum_const((s8)u64_cval);
5859 else if (size == 2)
5860 reg->var_off = tnum_const((s16)u64_cval);
5861 else
5862 /* size == 4 */
5863 reg->var_off = tnum_const((s32)u64_cval);
5864
5865 u64_cval = reg->var_off.value;
5866 reg->smax_value = reg->smin_value = u64_cval;
5867 reg->umax_value = reg->umin_value = u64_cval;
5868 reg->s32_max_value = reg->s32_min_value = u64_cval;
5869 reg->u32_max_value = reg->u32_min_value = u64_cval;
5870 return;
5871 }
5872
5873 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5874 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5875
5876 if (top_smax_value != top_smin_value)
5877 goto out;
5878
5879 /* find the s64_min and s64_min after sign extension */
5880 if (size == 1) {
5881 init_s64_max = (s8)reg->smax_value;
5882 init_s64_min = (s8)reg->smin_value;
5883 } else if (size == 2) {
5884 init_s64_max = (s16)reg->smax_value;
5885 init_s64_min = (s16)reg->smin_value;
5886 } else {
5887 init_s64_max = (s32)reg->smax_value;
5888 init_s64_min = (s32)reg->smin_value;
5889 }
5890
5891 s64_max = max(init_s64_max, init_s64_min);
5892 s64_min = min(init_s64_max, init_s64_min);
5893
5894 /* both of s64_max/s64_min positive or negative */
5895 if (s64_max >= 0 == s64_min >= 0) {
5896 reg->smin_value = reg->s32_min_value = s64_min;
5897 reg->smax_value = reg->s32_max_value = s64_max;
5898 reg->umin_value = reg->u32_min_value = s64_min;
5899 reg->umax_value = reg->u32_max_value = s64_max;
5900 reg->var_off = tnum_range(s64_min, s64_max);
5901 return;
5902 }
5903
5904out:
5905 set_sext64_default_val(reg, size);
5906}
5907
a23740ec
AN
5908static bool bpf_map_is_rdonly(const struct bpf_map *map)
5909{
353050be
DB
5910 /* A map is considered read-only if the following condition are true:
5911 *
5912 * 1) BPF program side cannot change any of the map content. The
5913 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5914 * and was set at map creation time.
5915 * 2) The map value(s) have been initialized from user space by a
5916 * loader and then "frozen", such that no new map update/delete
5917 * operations from syscall side are possible for the rest of
5918 * the map's lifetime from that point onwards.
5919 * 3) Any parallel/pending map update/delete operations from syscall
5920 * side have been completed. Only after that point, it's safe to
5921 * assume that map value(s) are immutable.
5922 */
5923 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5924 READ_ONCE(map->frozen) &&
5925 !bpf_map_write_active(map);
a23740ec
AN
5926}
5927
1f9a1ea8
YS
5928static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5929 bool is_ldsx)
a23740ec
AN
5930{
5931 void *ptr;
5932 u64 addr;
5933 int err;
5934
5935 err = map->ops->map_direct_value_addr(map, &addr, off);
5936 if (err)
5937 return err;
2dedd7d2 5938 ptr = (void *)(long)addr + off;
a23740ec
AN
5939
5940 switch (size) {
5941 case sizeof(u8):
1f9a1ea8 5942 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
a23740ec
AN
5943 break;
5944 case sizeof(u16):
1f9a1ea8 5945 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
a23740ec
AN
5946 break;
5947 case sizeof(u32):
1f9a1ea8 5948 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
a23740ec
AN
5949 break;
5950 case sizeof(u64):
5951 *val = *(u64 *)ptr;
5952 break;
5953 default:
5954 return -EINVAL;
5955 }
5956 return 0;
5957}
5958
6fcd486b 5959#define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
30ee9821 5960#define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6fcd486b 5961#define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
57539b1c 5962
6fcd486b
AS
5963/*
5964 * Allow list few fields as RCU trusted or full trusted.
5965 * This logic doesn't allow mix tagging and will be removed once GCC supports
5966 * btf_type_tag.
5967 */
5968
5969/* RCU trusted: these fields are trusted in RCU CS and never NULL */
5970BTF_TYPE_SAFE_RCU(struct task_struct) {
57539b1c 5971 const cpumask_t *cpus_ptr;
8d093b4e 5972 struct css_set __rcu *cgroups;
6fcd486b
AS
5973 struct task_struct __rcu *real_parent;
5974 struct task_struct *group_leader;
8d093b4e
AS
5975};
5976
30ee9821
AS
5977BTF_TYPE_SAFE_RCU(struct cgroup) {
5978 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5979 struct kernfs_node *kn;
5980};
5981
6fcd486b 5982BTF_TYPE_SAFE_RCU(struct css_set) {
8d093b4e 5983 struct cgroup *dfl_cgrp;
57539b1c
DV
5984};
5985
30ee9821
AS
5986/* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5987BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5988 struct file __rcu *exe_file;
5989};
5990
5991/* skb->sk, req->sk are not RCU protected, but we mark them as such
5992 * because bpf prog accessible sockets are SOCK_RCU_FREE.
5993 */
5994BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5995 struct sock *sk;
5996};
5997
5998BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5999 struct sock *sk;
6000};
6001
6fcd486b
AS
6002/* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6003BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
63260df1 6004 struct seq_file *seq;
6fcd486b
AS
6005};
6006
6007BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
63260df1
AS
6008 struct bpf_iter_meta *meta;
6009 struct task_struct *task;
6fcd486b
AS
6010};
6011
6012BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6013 struct file *file;
6014};
6015
6016BTF_TYPE_SAFE_TRUSTED(struct file) {
6017 struct inode *f_inode;
6018};
6019
6020BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6021 /* no negative dentry-s in places where bpf can see it */
6022 struct inode *d_inode;
6023};
6024
6025BTF_TYPE_SAFE_TRUSTED(struct socket) {
6026 struct sock *sk;
6027};
6028
6029static bool type_is_rcu(struct bpf_verifier_env *env,
6030 struct bpf_reg_state *reg,
63260df1 6031 const char *field_name, u32 btf_id)
57539b1c 6032{
6fcd486b 6033 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
30ee9821 6034 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6fcd486b 6035 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
57539b1c 6036
63260df1 6037 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6fcd486b 6038}
57539b1c 6039
30ee9821
AS
6040static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6041 struct bpf_reg_state *reg,
6042 const char *field_name, u32 btf_id)
6043{
6044 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6045 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6046 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6047
6048 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6049}
6050
6fcd486b
AS
6051static bool type_is_trusted(struct bpf_verifier_env *env,
6052 struct bpf_reg_state *reg,
63260df1 6053 const char *field_name, u32 btf_id)
6fcd486b
AS
6054{
6055 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6056 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6057 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6058 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6059 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6060 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6061
63260df1 6062 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
57539b1c
DV
6063}
6064
9e15db66
AS
6065static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6066 struct bpf_reg_state *regs,
6067 int regno, int off, int size,
6068 enum bpf_access_type atype,
6069 int value_regno)
6070{
6071 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
6072 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6073 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
63260df1 6074 const char *field_name = NULL;
c6f1bfe8 6075 enum bpf_type_flag flag = 0;
b7e852a9 6076 u32 btf_id = 0;
9e15db66
AS
6077 int ret;
6078
c67cae55
AS
6079 if (!env->allow_ptr_leaks) {
6080 verbose(env,
6081 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6082 tname);
6083 return -EPERM;
6084 }
6085 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6086 verbose(env,
6087 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6088 tname);
6089 return -EINVAL;
6090 }
9e15db66
AS
6091 if (off < 0) {
6092 verbose(env,
6093 "R%d is ptr_%s invalid negative access: off=%d\n",
6094 regno, tname, off);
6095 return -EACCES;
6096 }
6097 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6098 char tn_buf[48];
6099
6100 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6101 verbose(env,
6102 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6103 regno, tname, off, tn_buf);
6104 return -EACCES;
6105 }
6106
c6f1bfe8
YS
6107 if (reg->type & MEM_USER) {
6108 verbose(env,
6109 "R%d is ptr_%s access user memory: off=%d\n",
6110 regno, tname, off);
6111 return -EACCES;
6112 }
6113
5844101a
HL
6114 if (reg->type & MEM_PERCPU) {
6115 verbose(env,
6116 "R%d is ptr_%s access percpu memory: off=%d\n",
6117 regno, tname, off);
6118 return -EACCES;
6119 }
6120
7d64c513 6121 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
282de143
KKD
6122 if (!btf_is_kernel(reg->btf)) {
6123 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6124 return -EFAULT;
6125 }
b7e852a9 6126 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
27ae7997 6127 } else {
282de143
KKD
6128 /* Writes are permitted with default btf_struct_access for
6129 * program allocated objects (which always have ref_obj_id > 0),
6130 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6131 */
503e4def 6132 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
27ae7997
MKL
6133 verbose(env, "only read is supported\n");
6134 return -EACCES;
6135 }
6136
6a3cd331
DM
6137 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6138 !reg->ref_obj_id) {
282de143
KKD
6139 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6140 return -EFAULT;
6141 }
6142
63260df1 6143 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
27ae7997
MKL
6144 }
6145
9e15db66
AS
6146 if (ret < 0)
6147 return ret;
6148
6fcd486b
AS
6149 if (ret != PTR_TO_BTF_ID) {
6150 /* just mark; */
6efe152d 6151
6fcd486b
AS
6152 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6153 /* If this is an untrusted pointer, all pointers formed by walking it
6154 * also inherit the untrusted flag.
6155 */
6156 flag = PTR_UNTRUSTED;
6157
6158 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6159 /* By default any pointer obtained from walking a trusted pointer is no
6160 * longer trusted, unless the field being accessed has explicitly been
6161 * marked as inheriting its parent's state of trust (either full or RCU).
6162 * For example:
6163 * 'cgroups' pointer is untrusted if task->cgroups dereference
6164 * happened in a sleepable program outside of bpf_rcu_read_lock()
6165 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6166 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6167 *
6168 * A regular RCU-protected pointer with __rcu tag can also be deemed
6169 * trusted if we are in an RCU CS. Such pointer can be NULL.
20c09d92 6170 */
63260df1 6171 if (type_is_trusted(env, reg, field_name, btf_id)) {
6fcd486b
AS
6172 flag |= PTR_TRUSTED;
6173 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
63260df1 6174 if (type_is_rcu(env, reg, field_name, btf_id)) {
6fcd486b
AS
6175 /* ignore __rcu tag and mark it MEM_RCU */
6176 flag |= MEM_RCU;
30ee9821
AS
6177 } else if (flag & MEM_RCU ||
6178 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6fcd486b 6179 /* __rcu tagged pointers can be NULL */
30ee9821 6180 flag |= MEM_RCU | PTR_MAYBE_NULL;
7ce4dc3e
YS
6181
6182 /* We always trust them */
6183 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6184 flag & PTR_UNTRUSTED)
6185 flag &= ~PTR_UNTRUSTED;
6fcd486b
AS
6186 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6187 /* keep as-is */
6188 } else {
afeebf9f
AS
6189 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6190 clear_trusted_flags(&flag);
6fcd486b
AS
6191 }
6192 } else {
6193 /*
6194 * If not in RCU CS or MEM_RCU pointer can be NULL then
6195 * aggressively mark as untrusted otherwise such
6196 * pointers will be plain PTR_TO_BTF_ID without flags
6197 * and will be allowed to be passed into helpers for
6198 * compat reasons.
6199 */
6200 flag = PTR_UNTRUSTED;
6201 }
20c09d92 6202 } else {
6fcd486b 6203 /* Old compat. Deprecated */
afeebf9f 6204 clear_trusted_flags(&flag);
20c09d92 6205 }
3f00c523 6206
41c48f3a 6207 if (atype == BPF_READ && value_regno >= 0)
c6f1bfe8 6208 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
41c48f3a
AI
6209
6210 return 0;
6211}
6212
6213static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6214 struct bpf_reg_state *regs,
6215 int regno, int off, int size,
6216 enum bpf_access_type atype,
6217 int value_regno)
6218{
6219 struct bpf_reg_state *reg = regs + regno;
6220 struct bpf_map *map = reg->map_ptr;
6728aea7 6221 struct bpf_reg_state map_reg;
c6f1bfe8 6222 enum bpf_type_flag flag = 0;
41c48f3a
AI
6223 const struct btf_type *t;
6224 const char *tname;
6225 u32 btf_id;
6226 int ret;
6227
6228 if (!btf_vmlinux) {
6229 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6230 return -ENOTSUPP;
6231 }
6232
6233 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6234 verbose(env, "map_ptr access not supported for map type %d\n",
6235 map->map_type);
6236 return -ENOTSUPP;
6237 }
6238
6239 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6240 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6241
c67cae55 6242 if (!env->allow_ptr_leaks) {
41c48f3a 6243 verbose(env,
c67cae55 6244 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
41c48f3a
AI
6245 tname);
6246 return -EPERM;
9e15db66 6247 }
27ae7997 6248
41c48f3a
AI
6249 if (off < 0) {
6250 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6251 regno, tname, off);
6252 return -EACCES;
6253 }
6254
6255 if (atype != BPF_READ) {
6256 verbose(env, "only read from %s is supported\n", tname);
6257 return -EACCES;
6258 }
6259
6728aea7
KKD
6260 /* Simulate access to a PTR_TO_BTF_ID */
6261 memset(&map_reg, 0, sizeof(map_reg));
6262 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
63260df1 6263 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
41c48f3a
AI
6264 if (ret < 0)
6265 return ret;
6266
6267 if (value_regno >= 0)
c6f1bfe8 6268 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
41c48f3a 6269
9e15db66
AS
6270 return 0;
6271}
6272
01f810ac
AM
6273/* Check that the stack access at the given offset is within bounds. The
6274 * maximum valid offset is -1.
6275 *
6276 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6277 * -state->allocated_stack for reads.
6278 */
6279static int check_stack_slot_within_bounds(int off,
6280 struct bpf_func_state *state,
6281 enum bpf_access_type t)
6282{
6283 int min_valid_off;
6284
6285 if (t == BPF_WRITE)
6286 min_valid_off = -MAX_BPF_STACK;
6287 else
6288 min_valid_off = -state->allocated_stack;
6289
6290 if (off < min_valid_off || off > -1)
6291 return -EACCES;
6292 return 0;
6293}
6294
6295/* Check that the stack access at 'regno + off' falls within the maximum stack
6296 * bounds.
6297 *
6298 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6299 */
6300static int check_stack_access_within_bounds(
6301 struct bpf_verifier_env *env,
6302 int regno, int off, int access_size,
61df10c7 6303 enum bpf_access_src src, enum bpf_access_type type)
01f810ac
AM
6304{
6305 struct bpf_reg_state *regs = cur_regs(env);
6306 struct bpf_reg_state *reg = regs + regno;
6307 struct bpf_func_state *state = func(env, reg);
6308 int min_off, max_off;
6309 int err;
6310 char *err_extra;
6311
6312 if (src == ACCESS_HELPER)
6313 /* We don't know if helpers are reading or writing (or both). */
6314 err_extra = " indirect access to";
6315 else if (type == BPF_READ)
6316 err_extra = " read from";
6317 else
6318 err_extra = " write to";
6319
6320 if (tnum_is_const(reg->var_off)) {
6321 min_off = reg->var_off.value + off;
6322 if (access_size > 0)
6323 max_off = min_off + access_size - 1;
6324 else
6325 max_off = min_off;
6326 } else {
6327 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6328 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6329 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6330 err_extra, regno);
6331 return -EACCES;
6332 }
6333 min_off = reg->smin_value + off;
6334 if (access_size > 0)
6335 max_off = reg->smax_value + off + access_size - 1;
6336 else
6337 max_off = min_off;
6338 }
6339
6340 err = check_stack_slot_within_bounds(min_off, state, type);
6341 if (!err)
6342 err = check_stack_slot_within_bounds(max_off, state, type);
6343
6344 if (err) {
6345 if (tnum_is_const(reg->var_off)) {
6346 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6347 err_extra, regno, off, access_size);
6348 } else {
6349 char tn_buf[48];
6350
6351 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6352 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6353 err_extra, regno, tn_buf, access_size);
6354 }
6355 }
6356 return err;
6357}
41c48f3a 6358
17a52670
AS
6359/* check whether memory at (regno + off) is accessible for t = (read | write)
6360 * if t==write, value_regno is a register which value is stored into memory
6361 * if t==read, value_regno is a register which will receive the value from memory
6362 * if t==write && value_regno==-1, some unknown value is stored into memory
6363 * if t==read && value_regno==-1, don't care what we read from memory
6364 */
ca369602
DB
6365static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6366 int off, int bpf_size, enum bpf_access_type t,
1f9a1ea8 6367 int value_regno, bool strict_alignment_once, bool is_ldsx)
17a52670 6368{
638f5b90
AS
6369 struct bpf_reg_state *regs = cur_regs(env);
6370 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 6371 struct bpf_func_state *state;
17a52670
AS
6372 int size, err = 0;
6373
6374 size = bpf_size_to_bytes(bpf_size);
6375 if (size < 0)
6376 return size;
6377
f1174f77 6378 /* alignment checks will add in reg->off themselves */
ca369602 6379 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
6380 if (err)
6381 return err;
17a52670 6382
f1174f77
EC
6383 /* for access checks, reg->off is just part of off */
6384 off += reg->off;
6385
69c087ba
YS
6386 if (reg->type == PTR_TO_MAP_KEY) {
6387 if (t == BPF_WRITE) {
6388 verbose(env, "write to change key R%d not allowed\n", regno);
6389 return -EACCES;
6390 }
6391
6392 err = check_mem_region_access(env, regno, off, size,
6393 reg->map_ptr->key_size, false);
6394 if (err)
6395 return err;
6396 if (value_regno >= 0)
6397 mark_reg_unknown(env, regs, value_regno);
6398 } else if (reg->type == PTR_TO_MAP_VALUE) {
aa3496ac 6399 struct btf_field *kptr_field = NULL;
61df10c7 6400
1be7f75d
AS
6401 if (t == BPF_WRITE && value_regno >= 0 &&
6402 is_pointer_value(env, value_regno)) {
61bd5218 6403 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
6404 return -EACCES;
6405 }
591fe988
DB
6406 err = check_map_access_type(env, regno, off, size, t);
6407 if (err)
6408 return err;
61df10c7
KKD
6409 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6410 if (err)
6411 return err;
6412 if (tnum_is_const(reg->var_off))
aa3496ac
KKD
6413 kptr_field = btf_record_find(reg->map_ptr->record,
6414 off + reg->var_off.value, BPF_KPTR);
6415 if (kptr_field) {
6416 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
61df10c7 6417 } else if (t == BPF_READ && value_regno >= 0) {
a23740ec
AN
6418 struct bpf_map *map = reg->map_ptr;
6419
6420 /* if map is read-only, track its contents as scalars */
6421 if (tnum_is_const(reg->var_off) &&
6422 bpf_map_is_rdonly(map) &&
6423 map->ops->map_direct_value_addr) {
6424 int map_off = off + reg->var_off.value;
6425 u64 val = 0;
6426
6427 err = bpf_map_direct_read(map, map_off, size,
1f9a1ea8 6428 &val, is_ldsx);
a23740ec
AN
6429 if (err)
6430 return err;
6431
6432 regs[value_regno].type = SCALAR_VALUE;
6433 __mark_reg_known(&regs[value_regno], val);
6434 } else {
6435 mark_reg_unknown(env, regs, value_regno);
6436 }
6437 }
34d3a78c
HL
6438 } else if (base_type(reg->type) == PTR_TO_MEM) {
6439 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6440
6441 if (type_may_be_null(reg->type)) {
6442 verbose(env, "R%d invalid mem access '%s'\n", regno,
6443 reg_type_str(env, reg->type));
6444 return -EACCES;
6445 }
6446
6447 if (t == BPF_WRITE && rdonly_mem) {
6448 verbose(env, "R%d cannot write into %s\n",
6449 regno, reg_type_str(env, reg->type));
6450 return -EACCES;
6451 }
6452
457f4436
AN
6453 if (t == BPF_WRITE && value_regno >= 0 &&
6454 is_pointer_value(env, value_regno)) {
6455 verbose(env, "R%d leaks addr into mem\n", value_regno);
6456 return -EACCES;
6457 }
34d3a78c 6458
457f4436
AN
6459 err = check_mem_region_access(env, regno, off, size,
6460 reg->mem_size, false);
34d3a78c 6461 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
457f4436 6462 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 6463 } else if (reg->type == PTR_TO_CTX) {
f1174f77 6464 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 6465 struct btf *btf = NULL;
9e15db66 6466 u32 btf_id = 0;
19de99f7 6467
1be7f75d
AS
6468 if (t == BPF_WRITE && value_regno >= 0 &&
6469 is_pointer_value(env, value_regno)) {
61bd5218 6470 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
6471 return -EACCES;
6472 }
f1174f77 6473
be80a1d3 6474 err = check_ptr_off_reg(env, reg, regno);
58990d1f
DB
6475 if (err < 0)
6476 return err;
6477
c6f1bfe8
YS
6478 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6479 &btf_id);
9e15db66
AS
6480 if (err)
6481 verbose_linfo(env, insn_idx, "; ");
969bf05e 6482 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 6483 /* ctx access returns either a scalar, or a
de8f3a83
DB
6484 * PTR_TO_PACKET[_META,_END]. In the latter
6485 * case, we know the offset is zero.
f1174f77 6486 */
46f8bc92 6487 if (reg_type == SCALAR_VALUE) {
638f5b90 6488 mark_reg_unknown(env, regs, value_regno);
46f8bc92 6489 } else {
638f5b90 6490 mark_reg_known_zero(env, regs,
61bd5218 6491 value_regno);
c25b2ae1 6492 if (type_may_be_null(reg_type))
46f8bc92 6493 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
6494 /* A load of ctx field could have different
6495 * actual load size with the one encoded in the
6496 * insn. When the dst is PTR, it is for sure not
6497 * a sub-register.
6498 */
6499 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
c25b2ae1 6500 if (base_type(reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 6501 regs[value_regno].btf = btf;
9e15db66 6502 regs[value_regno].btf_id = btf_id;
22dc4a0f 6503 }
46f8bc92 6504 }
638f5b90 6505 regs[value_regno].type = reg_type;
969bf05e 6506 }
17a52670 6507
f1174f77 6508 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
6509 /* Basic bounds checks. */
6510 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
6511 if (err)
6512 return err;
8726679a 6513
f4d7e40a
AS
6514 state = func(env, reg);
6515 err = update_stack_depth(env, state, off);
6516 if (err)
6517 return err;
8726679a 6518
01f810ac
AM
6519 if (t == BPF_READ)
6520 err = check_stack_read(env, regno, off, size,
61bd5218 6521 value_regno);
01f810ac
AM
6522 else
6523 err = check_stack_write(env, regno, off, size,
6524 value_regno, insn_idx);
de8f3a83 6525 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 6526 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 6527 verbose(env, "cannot write into packet\n");
969bf05e
AS
6528 return -EACCES;
6529 }
4acf6c0b
BB
6530 if (t == BPF_WRITE && value_regno >= 0 &&
6531 is_pointer_value(env, value_regno)) {
61bd5218
JK
6532 verbose(env, "R%d leaks addr into packet\n",
6533 value_regno);
4acf6c0b
BB
6534 return -EACCES;
6535 }
9fd29c08 6536 err = check_packet_access(env, regno, off, size, false);
969bf05e 6537 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 6538 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
6539 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6540 if (t == BPF_WRITE && value_regno >= 0 &&
6541 is_pointer_value(env, value_regno)) {
6542 verbose(env, "R%d leaks addr into flow keys\n",
6543 value_regno);
6544 return -EACCES;
6545 }
6546
6547 err = check_flow_keys_access(env, off, size);
6548 if (!err && t == BPF_READ && value_regno >= 0)
6549 mark_reg_unknown(env, regs, value_regno);
46f8bc92 6550 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 6551 if (t == BPF_WRITE) {
46f8bc92 6552 verbose(env, "R%d cannot write into %s\n",
c25b2ae1 6553 regno, reg_type_str(env, reg->type));
c64b7983
JS
6554 return -EACCES;
6555 }
5f456649 6556 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
6557 if (!err && value_regno >= 0)
6558 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
6559 } else if (reg->type == PTR_TO_TP_BUFFER) {
6560 err = check_tp_buffer_access(env, reg, regno, off, size);
6561 if (!err && t == BPF_READ && value_regno >= 0)
6562 mark_reg_unknown(env, regs, value_regno);
bff61f6f
HL
6563 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6564 !type_may_be_null(reg->type)) {
9e15db66
AS
6565 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6566 value_regno);
41c48f3a
AI
6567 } else if (reg->type == CONST_PTR_TO_MAP) {
6568 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6569 value_regno);
20b2aff4
HL
6570 } else if (base_type(reg->type) == PTR_TO_BUF) {
6571 bool rdonly_mem = type_is_rdonly_mem(reg->type);
20b2aff4
HL
6572 u32 *max_access;
6573
6574 if (rdonly_mem) {
6575 if (t == BPF_WRITE) {
6576 verbose(env, "R%d cannot write into %s\n",
6577 regno, reg_type_str(env, reg->type));
6578 return -EACCES;
6579 }
20b2aff4
HL
6580 max_access = &env->prog->aux->max_rdonly_access;
6581 } else {
20b2aff4 6582 max_access = &env->prog->aux->max_rdwr_access;
afbf21dc 6583 }
20b2aff4 6584
f6dfbe31 6585 err = check_buffer_access(env, reg, regno, off, size, false,
44e9a741 6586 max_access);
20b2aff4
HL
6587
6588 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
afbf21dc 6589 mark_reg_unknown(env, regs, value_regno);
17a52670 6590 } else {
61bd5218 6591 verbose(env, "R%d invalid mem access '%s'\n", regno,
c25b2ae1 6592 reg_type_str(env, reg->type));
17a52670
AS
6593 return -EACCES;
6594 }
969bf05e 6595
f1174f77 6596 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 6597 regs[value_regno].type == SCALAR_VALUE) {
1f9a1ea8
YS
6598 if (!is_ldsx)
6599 /* b/h/w load zero-extends, mark upper bits as known 0 */
6600 coerce_reg_to_size(&regs[value_regno], size);
6601 else
6602 coerce_reg_to_size_sx(&regs[value_regno], size);
969bf05e 6603 }
17a52670
AS
6604 return err;
6605}
6606
91c960b0 6607static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 6608{
5ffa2550 6609 int load_reg;
17a52670
AS
6610 int err;
6611
5ca419f2
BJ
6612 switch (insn->imm) {
6613 case BPF_ADD:
6614 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
6615 case BPF_AND:
6616 case BPF_AND | BPF_FETCH:
6617 case BPF_OR:
6618 case BPF_OR | BPF_FETCH:
6619 case BPF_XOR:
6620 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
6621 case BPF_XCHG:
6622 case BPF_CMPXCHG:
5ca419f2
BJ
6623 break;
6624 default:
91c960b0
BJ
6625 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6626 return -EINVAL;
6627 }
6628
6629 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6630 verbose(env, "invalid atomic operand size\n");
17a52670
AS
6631 return -EINVAL;
6632 }
6633
6634 /* check src1 operand */
dc503a8a 6635 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6636 if (err)
6637 return err;
6638
6639 /* check src2 operand */
dc503a8a 6640 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6641 if (err)
6642 return err;
6643
5ffa2550
BJ
6644 if (insn->imm == BPF_CMPXCHG) {
6645 /* Check comparison of R0 with memory location */
a82fe085
DB
6646 const u32 aux_reg = BPF_REG_0;
6647
6648 err = check_reg_arg(env, aux_reg, SRC_OP);
5ffa2550
BJ
6649 if (err)
6650 return err;
a82fe085
DB
6651
6652 if (is_pointer_value(env, aux_reg)) {
6653 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6654 return -EACCES;
6655 }
5ffa2550
BJ
6656 }
6657
6bdf6abc 6658 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 6659 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
6660 return -EACCES;
6661 }
6662
ca369602 6663 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 6664 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
6665 is_flow_key_reg(env, insn->dst_reg) ||
6666 is_sk_reg(env, insn->dst_reg)) {
91c960b0 6667 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f 6668 insn->dst_reg,
c25b2ae1 6669 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
6670 return -EACCES;
6671 }
6672
37086bfd
BJ
6673 if (insn->imm & BPF_FETCH) {
6674 if (insn->imm == BPF_CMPXCHG)
6675 load_reg = BPF_REG_0;
6676 else
6677 load_reg = insn->src_reg;
6678
6679 /* check and record load of old value */
6680 err = check_reg_arg(env, load_reg, DST_OP);
6681 if (err)
6682 return err;
6683 } else {
6684 /* This instruction accesses a memory location but doesn't
6685 * actually load it into a register.
6686 */
6687 load_reg = -1;
6688 }
6689
7d3baf0a
DB
6690 /* Check whether we can read the memory, with second call for fetch
6691 * case to simulate the register fill.
6692 */
31fd8581 6693 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1f9a1ea8 6694 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7d3baf0a
DB
6695 if (!err && load_reg >= 0)
6696 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6697 BPF_SIZE(insn->code), BPF_READ, load_reg,
1f9a1ea8 6698 true, false);
17a52670
AS
6699 if (err)
6700 return err;
6701
7d3baf0a 6702 /* Check whether we can write into the same memory. */
5ca419f2 6703 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1f9a1ea8 6704 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
5ca419f2
BJ
6705 if (err)
6706 return err;
6707
5ca419f2 6708 return 0;
17a52670
AS
6709}
6710
01f810ac
AM
6711/* When register 'regno' is used to read the stack (either directly or through
6712 * a helper function) make sure that it's within stack boundary and, depending
6713 * on the access type, that all elements of the stack are initialized.
6714 *
6715 * 'off' includes 'regno->off', but not its dynamic part (if any).
6716 *
6717 * All registers that have been spilled on the stack in the slots within the
6718 * read offsets are marked as read.
6719 */
6720static int check_stack_range_initialized(
6721 struct bpf_verifier_env *env, int regno, int off,
6722 int access_size, bool zero_size_allowed,
61df10c7 6723 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
6724{
6725 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
6726 struct bpf_func_state *state = func(env, reg);
6727 int err, min_off, max_off, i, j, slot, spi;
6728 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6729 enum bpf_access_type bounds_check_type;
6730 /* Some accesses can write anything into the stack, others are
6731 * read-only.
6732 */
6733 bool clobber = false;
2011fccf 6734
01f810ac
AM
6735 if (access_size == 0 && !zero_size_allowed) {
6736 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
6737 return -EACCES;
6738 }
2011fccf 6739
01f810ac
AM
6740 if (type == ACCESS_HELPER) {
6741 /* The bounds checks for writes are more permissive than for
6742 * reads. However, if raw_mode is not set, we'll do extra
6743 * checks below.
6744 */
6745 bounds_check_type = BPF_WRITE;
6746 clobber = true;
6747 } else {
6748 bounds_check_type = BPF_READ;
6749 }
6750 err = check_stack_access_within_bounds(env, regno, off, access_size,
6751 type, bounds_check_type);
6752 if (err)
6753 return err;
6754
17a52670 6755
2011fccf 6756 if (tnum_is_const(reg->var_off)) {
01f810ac 6757 min_off = max_off = reg->var_off.value + off;
2011fccf 6758 } else {
088ec26d
AI
6759 /* Variable offset is prohibited for unprivileged mode for
6760 * simplicity since it requires corresponding support in
6761 * Spectre masking for stack ALU.
6762 * See also retrieve_ptr_limit().
6763 */
2c78ee89 6764 if (!env->bypass_spec_v1) {
088ec26d 6765 char tn_buf[48];
f1174f77 6766
088ec26d 6767 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
6768 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6769 regno, err_extra, tn_buf);
088ec26d
AI
6770 return -EACCES;
6771 }
f2bcd05e
AI
6772 /* Only initialized buffer on stack is allowed to be accessed
6773 * with variable offset. With uninitialized buffer it's hard to
6774 * guarantee that whole memory is marked as initialized on
6775 * helper return since specific bounds are unknown what may
6776 * cause uninitialized stack leaking.
6777 */
6778 if (meta && meta->raw_mode)
6779 meta = NULL;
6780
01f810ac
AM
6781 min_off = reg->smin_value + off;
6782 max_off = reg->smax_value + off;
17a52670
AS
6783 }
6784
435faee1 6785 if (meta && meta->raw_mode) {
ef8fc7a0
KKD
6786 /* Ensure we won't be overwriting dynptrs when simulating byte
6787 * by byte access in check_helper_call using meta.access_size.
6788 * This would be a problem if we have a helper in the future
6789 * which takes:
6790 *
6791 * helper(uninit_mem, len, dynptr)
6792 *
6793 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6794 * may end up writing to dynptr itself when touching memory from
6795 * arg 1. This can be relaxed on a case by case basis for known
6796 * safe cases, but reject due to the possibilitiy of aliasing by
6797 * default.
6798 */
6799 for (i = min_off; i < max_off + access_size; i++) {
6800 int stack_off = -i - 1;
6801
6802 spi = __get_spi(i);
6803 /* raw_mode may write past allocated_stack */
6804 if (state->allocated_stack <= stack_off)
6805 continue;
6806 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6807 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6808 return -EACCES;
6809 }
6810 }
435faee1
DB
6811 meta->access_size = access_size;
6812 meta->regno = regno;
6813 return 0;
6814 }
6815
2011fccf 6816 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
6817 u8 *stype;
6818
2011fccf 6819 slot = -i - 1;
638f5b90 6820 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
6821 if (state->allocated_stack <= slot)
6822 goto err;
6823 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6824 if (*stype == STACK_MISC)
6825 goto mark;
6715df8d
EZ
6826 if ((*stype == STACK_ZERO) ||
6827 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
01f810ac
AM
6828 if (clobber) {
6829 /* helper can write anything into the stack */
6830 *stype = STACK_MISC;
6831 }
cc2b14d5 6832 goto mark;
17a52670 6833 }
1d68f22b 6834
27113c59 6835 if (is_spilled_reg(&state->stack[spi]) &&
cd17d38f
YS
6836 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6837 env->allow_ptr_leaks)) {
01f810ac
AM
6838 if (clobber) {
6839 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6840 for (j = 0; j < BPF_REG_SIZE; j++)
354e8f19 6841 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
01f810ac 6842 }
f7cf25b2
AS
6843 goto mark;
6844 }
6845
cc2b14d5 6846err:
2011fccf 6847 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
6848 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6849 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
6850 } else {
6851 char tn_buf[48];
6852
6853 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
6854 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6855 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 6856 }
cc2b14d5
AS
6857 return -EACCES;
6858mark:
6859 /* reading any byte out of 8-byte 'spill_slot' will cause
6860 * the whole slot to be marked as 'read'
6861 */
679c782d 6862 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
6863 state->stack[spi].spilled_ptr.parent,
6864 REG_LIVE_READ64);
261f4664
KKD
6865 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6866 * be sure that whether stack slot is written to or not. Hence,
6867 * we must still conservatively propagate reads upwards even if
6868 * helper may write to the entire memory range.
6869 */
17a52670 6870 }
2011fccf 6871 return update_stack_depth(env, state, min_off);
17a52670
AS
6872}
6873
06c1c049
GB
6874static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6875 int access_size, bool zero_size_allowed,
6876 struct bpf_call_arg_meta *meta)
6877{
638f5b90 6878 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
20b2aff4 6879 u32 *max_access;
06c1c049 6880
20b2aff4 6881 switch (base_type(reg->type)) {
06c1c049 6882 case PTR_TO_PACKET:
de8f3a83 6883 case PTR_TO_PACKET_META:
9fd29c08
YS
6884 return check_packet_access(env, regno, reg->off, access_size,
6885 zero_size_allowed);
69c087ba 6886 case PTR_TO_MAP_KEY:
7b3552d3
KKD
6887 if (meta && meta->raw_mode) {
6888 verbose(env, "R%d cannot write into %s\n", regno,
6889 reg_type_str(env, reg->type));
6890 return -EACCES;
6891 }
69c087ba
YS
6892 return check_mem_region_access(env, regno, reg->off, access_size,
6893 reg->map_ptr->key_size, false);
06c1c049 6894 case PTR_TO_MAP_VALUE:
591fe988
DB
6895 if (check_map_access_type(env, regno, reg->off, access_size,
6896 meta && meta->raw_mode ? BPF_WRITE :
6897 BPF_READ))
6898 return -EACCES;
9fd29c08 6899 return check_map_access(env, regno, reg->off, access_size,
61df10c7 6900 zero_size_allowed, ACCESS_HELPER);
457f4436 6901 case PTR_TO_MEM:
97e6d7da
KKD
6902 if (type_is_rdonly_mem(reg->type)) {
6903 if (meta && meta->raw_mode) {
6904 verbose(env, "R%d cannot write into %s\n", regno,
6905 reg_type_str(env, reg->type));
6906 return -EACCES;
6907 }
6908 }
457f4436
AN
6909 return check_mem_region_access(env, regno, reg->off,
6910 access_size, reg->mem_size,
6911 zero_size_allowed);
20b2aff4
HL
6912 case PTR_TO_BUF:
6913 if (type_is_rdonly_mem(reg->type)) {
97e6d7da
KKD
6914 if (meta && meta->raw_mode) {
6915 verbose(env, "R%d cannot write into %s\n", regno,
6916 reg_type_str(env, reg->type));
20b2aff4 6917 return -EACCES;
97e6d7da 6918 }
20b2aff4 6919
20b2aff4
HL
6920 max_access = &env->prog->aux->max_rdonly_access;
6921 } else {
20b2aff4
HL
6922 max_access = &env->prog->aux->max_rdwr_access;
6923 }
afbf21dc
YS
6924 return check_buffer_access(env, reg, regno, reg->off,
6925 access_size, zero_size_allowed,
44e9a741 6926 max_access);
0d004c02 6927 case PTR_TO_STACK:
01f810ac
AM
6928 return check_stack_range_initialized(
6929 env,
6930 regno, reg->off, access_size,
6931 zero_size_allowed, ACCESS_HELPER, meta);
3e30be42
AS
6932 case PTR_TO_BTF_ID:
6933 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6934 access_size, BPF_READ, -1);
15baa55f
BT
6935 case PTR_TO_CTX:
6936 /* in case the function doesn't know how to access the context,
6937 * (because we are in a program of type SYSCALL for example), we
6938 * can not statically check its size.
6939 * Dynamically check it now.
6940 */
6941 if (!env->ops->convert_ctx_access) {
6942 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6943 int offset = access_size - 1;
6944
6945 /* Allow zero-byte read from PTR_TO_CTX */
6946 if (access_size == 0)
6947 return zero_size_allowed ? 0 : -EACCES;
6948
6949 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
1f9a1ea8 6950 atype, -1, false, false);
15baa55f
BT
6951 }
6952
6953 fallthrough;
0d004c02
LB
6954 default: /* scalar_value or invalid ptr */
6955 /* Allow zero-byte read from NULL, regardless of pointer type */
6956 if (zero_size_allowed && access_size == 0 &&
6957 register_is_null(reg))
6958 return 0;
6959
c25b2ae1
HL
6960 verbose(env, "R%d type=%s ", regno,
6961 reg_type_str(env, reg->type));
6962 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
0d004c02 6963 return -EACCES;
06c1c049
GB
6964 }
6965}
6966
d583691c
KKD
6967static int check_mem_size_reg(struct bpf_verifier_env *env,
6968 struct bpf_reg_state *reg, u32 regno,
6969 bool zero_size_allowed,
6970 struct bpf_call_arg_meta *meta)
6971{
6972 int err;
6973
6974 /* This is used to refine r0 return value bounds for helpers
6975 * that enforce this value as an upper bound on return values.
6976 * See do_refine_retval_range() for helpers that can refine
6977 * the return value. C type of helper is u32 so we pull register
6978 * bound from umax_value however, if negative verifier errors
6979 * out. Only upper bounds can be learned because retval is an
6980 * int type and negative retvals are allowed.
6981 */
be77354a 6982 meta->msize_max_value = reg->umax_value;
d583691c
KKD
6983
6984 /* The register is SCALAR_VALUE; the access check
6985 * happens using its boundaries.
6986 */
6987 if (!tnum_is_const(reg->var_off))
6988 /* For unprivileged variable accesses, disable raw
6989 * mode so that the program is required to
6990 * initialize all the memory that the helper could
6991 * just partially fill up.
6992 */
6993 meta = NULL;
6994
6995 if (reg->smin_value < 0) {
6996 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6997 regno);
6998 return -EACCES;
6999 }
7000
7001 if (reg->umin_value == 0) {
7002 err = check_helper_mem_access(env, regno - 1, 0,
7003 zero_size_allowed,
7004 meta);
7005 if (err)
7006 return err;
7007 }
7008
7009 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7010 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7011 regno);
7012 return -EACCES;
7013 }
7014 err = check_helper_mem_access(env, regno - 1,
7015 reg->umax_value,
7016 zero_size_allowed, meta);
7017 if (!err)
7018 err = mark_chain_precision(env, regno);
7019 return err;
7020}
7021
e5069b9c
DB
7022int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7023 u32 regno, u32 mem_size)
7024{
be77354a
KKD
7025 bool may_be_null = type_may_be_null(reg->type);
7026 struct bpf_reg_state saved_reg;
7027 struct bpf_call_arg_meta meta;
7028 int err;
7029
e5069b9c
DB
7030 if (register_is_null(reg))
7031 return 0;
7032
be77354a
KKD
7033 memset(&meta, 0, sizeof(meta));
7034 /* Assuming that the register contains a value check if the memory
7035 * access is safe. Temporarily save and restore the register's state as
7036 * the conversion shouldn't be visible to a caller.
7037 */
7038 if (may_be_null) {
7039 saved_reg = *reg;
e5069b9c 7040 mark_ptr_not_null_reg(reg);
e5069b9c
DB
7041 }
7042
be77354a
KKD
7043 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7044 /* Check access for BPF_WRITE */
7045 meta.raw_mode = true;
7046 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7047
7048 if (may_be_null)
7049 *reg = saved_reg;
7050
7051 return err;
e5069b9c
DB
7052}
7053
00b85860
KKD
7054static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7055 u32 regno)
d583691c
KKD
7056{
7057 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7058 bool may_be_null = type_may_be_null(mem_reg->type);
7059 struct bpf_reg_state saved_reg;
be77354a 7060 struct bpf_call_arg_meta meta;
d583691c
KKD
7061 int err;
7062
7063 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7064
be77354a
KKD
7065 memset(&meta, 0, sizeof(meta));
7066
d583691c
KKD
7067 if (may_be_null) {
7068 saved_reg = *mem_reg;
7069 mark_ptr_not_null_reg(mem_reg);
7070 }
7071
be77354a
KKD
7072 err = check_mem_size_reg(env, reg, regno, true, &meta);
7073 /* Check access for BPF_WRITE */
7074 meta.raw_mode = true;
7075 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
d583691c
KKD
7076
7077 if (may_be_null)
7078 *mem_reg = saved_reg;
7079 return err;
7080}
7081
d83525ca 7082/* Implementation details:
4e814da0
KKD
7083 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7084 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
d83525ca 7085 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4e814da0
KKD
7086 * Two separate bpf_obj_new will also have different reg->id.
7087 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7088 * clears reg->id after value_or_null->value transition, since the verifier only
7089 * cares about the range of access to valid map value pointer and doesn't care
7090 * about actual address of the map element.
d83525ca
AS
7091 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7092 * reg->id > 0 after value_or_null->value transition. By doing so
7093 * two bpf_map_lookups will be considered two different pointers that
4e814da0
KKD
7094 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7095 * returned from bpf_obj_new.
d83525ca
AS
7096 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7097 * dead-locks.
7098 * Since only one bpf_spin_lock is allowed the checks are simpler than
7099 * reg_is_refcounted() logic. The verifier needs to remember only
7100 * one spin_lock instead of array of acquired_refs.
d0d78c1d 7101 * cur_state->active_lock remembers which map value element or allocated
4e814da0 7102 * object got locked and clears it after bpf_spin_unlock.
d83525ca
AS
7103 */
7104static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7105 bool is_lock)
7106{
7107 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7108 struct bpf_verifier_state *cur = env->cur_state;
7109 bool is_const = tnum_is_const(reg->var_off);
d83525ca 7110 u64 val = reg->var_off.value;
4e814da0
KKD
7111 struct bpf_map *map = NULL;
7112 struct btf *btf = NULL;
7113 struct btf_record *rec;
d83525ca 7114
d83525ca
AS
7115 if (!is_const) {
7116 verbose(env,
7117 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7118 regno);
7119 return -EINVAL;
7120 }
4e814da0
KKD
7121 if (reg->type == PTR_TO_MAP_VALUE) {
7122 map = reg->map_ptr;
7123 if (!map->btf) {
7124 verbose(env,
7125 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7126 map->name);
7127 return -EINVAL;
7128 }
7129 } else {
7130 btf = reg->btf;
d83525ca 7131 }
4e814da0
KKD
7132
7133 rec = reg_btf_record(reg);
7134 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7135 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7136 map ? map->name : "kptr");
d83525ca
AS
7137 return -EINVAL;
7138 }
4e814da0 7139 if (rec->spin_lock_off != val + reg->off) {
db559117 7140 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
4e814da0 7141 val + reg->off, rec->spin_lock_off);
d83525ca
AS
7142 return -EINVAL;
7143 }
7144 if (is_lock) {
d0d78c1d 7145 if (cur->active_lock.ptr) {
d83525ca
AS
7146 verbose(env,
7147 "Locking two bpf_spin_locks are not allowed\n");
7148 return -EINVAL;
7149 }
d0d78c1d
KKD
7150 if (map)
7151 cur->active_lock.ptr = map;
7152 else
7153 cur->active_lock.ptr = btf;
7154 cur->active_lock.id = reg->id;
d83525ca 7155 } else {
d0d78c1d
KKD
7156 void *ptr;
7157
7158 if (map)
7159 ptr = map;
7160 else
7161 ptr = btf;
7162
7163 if (!cur->active_lock.ptr) {
d83525ca
AS
7164 verbose(env, "bpf_spin_unlock without taking a lock\n");
7165 return -EINVAL;
7166 }
d0d78c1d
KKD
7167 if (cur->active_lock.ptr != ptr ||
7168 cur->active_lock.id != reg->id) {
d83525ca
AS
7169 verbose(env, "bpf_spin_unlock of different lock\n");
7170 return -EINVAL;
7171 }
534e86bc 7172
6a3cd331 7173 invalidate_non_owning_refs(env);
534e86bc 7174
6a3cd331
DM
7175 cur->active_lock.ptr = NULL;
7176 cur->active_lock.id = 0;
d83525ca
AS
7177 }
7178 return 0;
7179}
7180
b00628b1
AS
7181static int process_timer_func(struct bpf_verifier_env *env, int regno,
7182 struct bpf_call_arg_meta *meta)
7183{
7184 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7185 bool is_const = tnum_is_const(reg->var_off);
7186 struct bpf_map *map = reg->map_ptr;
7187 u64 val = reg->var_off.value;
7188
7189 if (!is_const) {
7190 verbose(env,
7191 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7192 regno);
7193 return -EINVAL;
7194 }
7195 if (!map->btf) {
7196 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7197 map->name);
7198 return -EINVAL;
7199 }
db559117
KKD
7200 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7201 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
68134668
AS
7202 return -EINVAL;
7203 }
db559117 7204 if (map->record->timer_off != val + reg->off) {
68134668 7205 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
db559117 7206 val + reg->off, map->record->timer_off);
b00628b1
AS
7207 return -EINVAL;
7208 }
7209 if (meta->map_ptr) {
7210 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7211 return -EFAULT;
7212 }
3e8ce298 7213 meta->map_uid = reg->map_uid;
b00628b1
AS
7214 meta->map_ptr = map;
7215 return 0;
7216}
7217
c0a5a21c
KKD
7218static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7219 struct bpf_call_arg_meta *meta)
7220{
7221 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
c0a5a21c 7222 struct bpf_map *map_ptr = reg->map_ptr;
aa3496ac 7223 struct btf_field *kptr_field;
c0a5a21c 7224 u32 kptr_off;
c0a5a21c
KKD
7225
7226 if (!tnum_is_const(reg->var_off)) {
7227 verbose(env,
7228 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7229 regno);
7230 return -EINVAL;
7231 }
7232 if (!map_ptr->btf) {
7233 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7234 map_ptr->name);
7235 return -EINVAL;
7236 }
aa3496ac
KKD
7237 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7238 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
c0a5a21c
KKD
7239 return -EINVAL;
7240 }
7241
7242 meta->map_ptr = map_ptr;
7243 kptr_off = reg->off + reg->var_off.value;
aa3496ac
KKD
7244 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7245 if (!kptr_field) {
c0a5a21c
KKD
7246 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7247 return -EACCES;
7248 }
aa3496ac 7249 if (kptr_field->type != BPF_KPTR_REF) {
c0a5a21c
KKD
7250 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7251 return -EACCES;
7252 }
aa3496ac 7253 meta->kptr_field = kptr_field;
c0a5a21c
KKD
7254 return 0;
7255}
7256
27060531
KKD
7257/* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7258 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7259 *
7260 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7261 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7262 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7263 *
7264 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7265 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7266 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7267 * mutate the view of the dynptr and also possibly destroy it. In the latter
7268 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7269 * memory that dynptr points to.
7270 *
7271 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7272 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7273 * readonly dynptr view yet, hence only the first case is tracked and checked.
7274 *
7275 * This is consistent with how C applies the const modifier to a struct object,
7276 * where the pointer itself inside bpf_dynptr becomes const but not what it
7277 * points to.
7278 *
7279 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7280 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7281 */
1d18feb2 7282static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
361f129f 7283 enum bpf_arg_type arg_type, int clone_ref_obj_id)
6b75bd3d
KKD
7284{
7285 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1d18feb2 7286 int err;
6b75bd3d 7287
27060531
KKD
7288 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7289 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7290 */
7291 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7292 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7293 return -EFAULT;
7294 }
79168a66 7295
27060531
KKD
7296 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7297 * constructing a mutable bpf_dynptr object.
7298 *
7299 * Currently, this is only possible with PTR_TO_STACK
7300 * pointing to a region of at least 16 bytes which doesn't
7301 * contain an existing bpf_dynptr.
7302 *
7303 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7304 * mutated or destroyed. However, the memory it points to
7305 * may be mutated.
7306 *
7307 * None - Points to a initialized dynptr that can be mutated and
7308 * destroyed, including mutation of the memory it points
7309 * to.
6b75bd3d 7310 */
6b75bd3d 7311 if (arg_type & MEM_UNINIT) {
1d18feb2
JK
7312 int i;
7313
7e0dac28 7314 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6b75bd3d
KKD
7315 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7316 return -EINVAL;
7317 }
7318
1d18feb2
JK
7319 /* we write BPF_DW bits (8 bytes) at a time */
7320 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7321 err = check_mem_access(env, insn_idx, regno,
1f9a1ea8 7322 i, BPF_DW, BPF_WRITE, -1, false, false);
1d18feb2
JK
7323 if (err)
7324 return err;
6b75bd3d
KKD
7325 }
7326
361f129f 7327 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
27060531
KKD
7328 } else /* MEM_RDONLY and None case from above */ {
7329 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7330 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7331 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7332 return -EINVAL;
7333 }
7334
7e0dac28 7335 if (!is_dynptr_reg_valid_init(env, reg)) {
6b75bd3d
KKD
7336 verbose(env,
7337 "Expected an initialized dynptr as arg #%d\n",
7338 regno);
7339 return -EINVAL;
7340 }
7341
27060531
KKD
7342 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7343 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6b75bd3d
KKD
7344 verbose(env,
7345 "Expected a dynptr of type %s as arg #%d\n",
d54e0f6c 7346 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6b75bd3d
KKD
7347 return -EINVAL;
7348 }
d6fefa11
KKD
7349
7350 err = mark_dynptr_read(env, reg);
6b75bd3d 7351 }
1d18feb2 7352 return err;
6b75bd3d
KKD
7353}
7354
06accc87
AN
7355static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7356{
7357 struct bpf_func_state *state = func(env, reg);
7358
7359 return state->stack[spi].spilled_ptr.ref_obj_id;
7360}
7361
7362static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7363{
7364 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7365}
7366
7367static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7368{
7369 return meta->kfunc_flags & KF_ITER_NEW;
7370}
7371
7372static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7373{
7374 return meta->kfunc_flags & KF_ITER_NEXT;
7375}
7376
7377static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7378{
7379 return meta->kfunc_flags & KF_ITER_DESTROY;
7380}
7381
7382static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7383{
7384 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7385 * kfunc is iter state pointer
7386 */
7387 return arg == 0 && is_iter_kfunc(meta);
7388}
7389
7390static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7391 struct bpf_kfunc_call_arg_meta *meta)
7392{
7393 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7394 const struct btf_type *t;
7395 const struct btf_param *arg;
7396 int spi, err, i, nr_slots;
7397 u32 btf_id;
7398
7399 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7400 arg = &btf_params(meta->func_proto)[0];
7401 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7402 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7403 nr_slots = t->size / BPF_REG_SIZE;
7404
06accc87
AN
7405 if (is_iter_new_kfunc(meta)) {
7406 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7407 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7408 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7409 iter_type_str(meta->btf, btf_id), regno);
7410 return -EINVAL;
7411 }
7412
7413 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7414 err = check_mem_access(env, insn_idx, regno,
1f9a1ea8 7415 i, BPF_DW, BPF_WRITE, -1, false, false);
06accc87
AN
7416 if (err)
7417 return err;
7418 }
7419
7420 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7421 if (err)
7422 return err;
7423 } else {
7424 /* iter_next() or iter_destroy() expect initialized iter state*/
7425 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7426 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7427 iter_type_str(meta->btf, btf_id), regno);
7428 return -EINVAL;
7429 }
7430
b63cbc49
AN
7431 spi = iter_get_spi(env, reg, nr_slots);
7432 if (spi < 0)
7433 return spi;
7434
06accc87
AN
7435 err = mark_iter_read(env, reg, spi, nr_slots);
7436 if (err)
7437 return err;
7438
b63cbc49
AN
7439 /* remember meta->iter info for process_iter_next_call() */
7440 meta->iter.spi = spi;
7441 meta->iter.frameno = reg->frameno;
06accc87
AN
7442 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7443
7444 if (is_iter_destroy_kfunc(meta)) {
7445 err = unmark_stack_slots_iter(env, reg, nr_slots);
7446 if (err)
7447 return err;
7448 }
7449 }
7450
7451 return 0;
7452}
7453
7454/* process_iter_next_call() is called when verifier gets to iterator's next
7455 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7456 * to it as just "iter_next()" in comments below.
7457 *
7458 * BPF verifier relies on a crucial contract for any iter_next()
7459 * implementation: it should *eventually* return NULL, and once that happens
7460 * it should keep returning NULL. That is, once iterator exhausts elements to
7461 * iterate, it should never reset or spuriously return new elements.
7462 *
7463 * With the assumption of such contract, process_iter_next_call() simulates
7464 * a fork in the verifier state to validate loop logic correctness and safety
7465 * without having to simulate infinite amount of iterations.
7466 *
7467 * In current state, we first assume that iter_next() returned NULL and
7468 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7469 * conditions we should not form an infinite loop and should eventually reach
7470 * exit.
7471 *
7472 * Besides that, we also fork current state and enqueue it for later
7473 * verification. In a forked state we keep iterator state as ACTIVE
7474 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7475 * also bump iteration depth to prevent erroneous infinite loop detection
7476 * later on (see iter_active_depths_differ() comment for details). In this
7477 * state we assume that we'll eventually loop back to another iter_next()
7478 * calls (it could be in exactly same location or in some other instruction,
7479 * it doesn't matter, we don't make any unnecessary assumptions about this,
7480 * everything revolves around iterator state in a stack slot, not which
7481 * instruction is calling iter_next()). When that happens, we either will come
7482 * to iter_next() with equivalent state and can conclude that next iteration
7483 * will proceed in exactly the same way as we just verified, so it's safe to
7484 * assume that loop converges. If not, we'll go on another iteration
7485 * simulation with a different input state, until all possible starting states
7486 * are validated or we reach maximum number of instructions limit.
7487 *
7488 * This way, we will either exhaustively discover all possible input states
7489 * that iterator loop can start with and eventually will converge, or we'll
7490 * effectively regress into bounded loop simulation logic and either reach
7491 * maximum number of instructions if loop is not provably convergent, or there
7492 * is some statically known limit on number of iterations (e.g., if there is
7493 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7494 *
7495 * One very subtle but very important aspect is that we *always* simulate NULL
7496 * condition first (as the current state) before we simulate non-NULL case.
7497 * This has to do with intricacies of scalar precision tracking. By simulating
7498 * "exit condition" of iter_next() returning NULL first, we make sure all the
7499 * relevant precision marks *that will be set **after** we exit iterator loop*
7500 * are propagated backwards to common parent state of NULL and non-NULL
7501 * branches. Thanks to that, state equivalence checks done later in forked
7502 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7503 * precision marks are finalized and won't change. Because simulating another
7504 * ACTIVE iterator iteration won't change them (because given same input
7505 * states we'll end up with exactly same output states which we are currently
7506 * comparing; and verification after the loop already propagated back what
7507 * needs to be **additionally** tracked as precise). It's subtle, grok
7508 * precision tracking for more intuitive understanding.
7509 */
7510static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7511 struct bpf_kfunc_call_arg_meta *meta)
7512{
7513 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7514 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7515 struct bpf_reg_state *cur_iter, *queued_iter;
7516 int iter_frameno = meta->iter.frameno;
7517 int iter_spi = meta->iter.spi;
7518
7519 BTF_TYPE_EMIT(struct bpf_iter);
7520
7521 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7522
7523 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7524 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7525 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7526 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7527 return -EFAULT;
7528 }
7529
7530 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7531 /* branch out active iter state */
7532 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7533 if (!queued_st)
7534 return -ENOMEM;
7535
7536 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7537 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7538 queued_iter->iter.depth++;
7539
7540 queued_fr = queued_st->frame[queued_st->curframe];
7541 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7542 }
7543
7544 /* switch to DRAINED state, but keep the depth unchanged */
7545 /* mark current iter state as drained and assume returned NULL */
7546 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7547 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7548
7549 return 0;
7550}
7551
90133415
DB
7552static bool arg_type_is_mem_size(enum bpf_arg_type type)
7553{
7554 return type == ARG_CONST_SIZE ||
7555 type == ARG_CONST_SIZE_OR_ZERO;
7556}
7557
8f14852e
KKD
7558static bool arg_type_is_release(enum bpf_arg_type type)
7559{
7560 return type & OBJ_RELEASE;
7561}
7562
97e03f52
JK
7563static bool arg_type_is_dynptr(enum bpf_arg_type type)
7564{
7565 return base_type(type) == ARG_PTR_TO_DYNPTR;
7566}
7567
57c3bb72
AI
7568static int int_ptr_type_to_size(enum bpf_arg_type type)
7569{
7570 if (type == ARG_PTR_TO_INT)
7571 return sizeof(u32);
7572 else if (type == ARG_PTR_TO_LONG)
7573 return sizeof(u64);
7574
7575 return -EINVAL;
7576}
7577
912f442c
LB
7578static int resolve_map_arg_type(struct bpf_verifier_env *env,
7579 const struct bpf_call_arg_meta *meta,
7580 enum bpf_arg_type *arg_type)
7581{
7582 if (!meta->map_ptr) {
7583 /* kernel subsystem misconfigured verifier */
7584 verbose(env, "invalid map_ptr to access map->type\n");
7585 return -EACCES;
7586 }
7587
7588 switch (meta->map_ptr->map_type) {
7589 case BPF_MAP_TYPE_SOCKMAP:
7590 case BPF_MAP_TYPE_SOCKHASH:
7591 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 7592 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
7593 } else {
7594 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7595 return -EINVAL;
7596 }
7597 break;
9330986c
JK
7598 case BPF_MAP_TYPE_BLOOM_FILTER:
7599 if (meta->func_id == BPF_FUNC_map_peek_elem)
7600 *arg_type = ARG_PTR_TO_MAP_VALUE;
7601 break;
912f442c
LB
7602 default:
7603 break;
7604 }
7605 return 0;
7606}
7607
f79e7ea5
LB
7608struct bpf_reg_types {
7609 const enum bpf_reg_type types[10];
1df8f55a 7610 u32 *btf_id;
f79e7ea5
LB
7611};
7612
f79e7ea5
LB
7613static const struct bpf_reg_types sock_types = {
7614 .types = {
7615 PTR_TO_SOCK_COMMON,
7616 PTR_TO_SOCKET,
7617 PTR_TO_TCP_SOCK,
7618 PTR_TO_XDP_SOCK,
7619 },
7620};
7621
49a2a4d4 7622#ifdef CONFIG_NET
1df8f55a
MKL
7623static const struct bpf_reg_types btf_id_sock_common_types = {
7624 .types = {
7625 PTR_TO_SOCK_COMMON,
7626 PTR_TO_SOCKET,
7627 PTR_TO_TCP_SOCK,
7628 PTR_TO_XDP_SOCK,
7629 PTR_TO_BTF_ID,
3f00c523 7630 PTR_TO_BTF_ID | PTR_TRUSTED,
1df8f55a
MKL
7631 },
7632 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7633};
49a2a4d4 7634#endif
1df8f55a 7635
f79e7ea5
LB
7636static const struct bpf_reg_types mem_types = {
7637 .types = {
7638 PTR_TO_STACK,
7639 PTR_TO_PACKET,
7640 PTR_TO_PACKET_META,
69c087ba 7641 PTR_TO_MAP_KEY,
f79e7ea5
LB
7642 PTR_TO_MAP_VALUE,
7643 PTR_TO_MEM,
894f2a8b 7644 PTR_TO_MEM | MEM_RINGBUF,
20b2aff4 7645 PTR_TO_BUF,
3e30be42 7646 PTR_TO_BTF_ID | PTR_TRUSTED,
f79e7ea5
LB
7647 },
7648};
7649
7650static const struct bpf_reg_types int_ptr_types = {
7651 .types = {
7652 PTR_TO_STACK,
7653 PTR_TO_PACKET,
7654 PTR_TO_PACKET_META,
69c087ba 7655 PTR_TO_MAP_KEY,
f79e7ea5
LB
7656 PTR_TO_MAP_VALUE,
7657 },
7658};
7659
4e814da0
KKD
7660static const struct bpf_reg_types spin_lock_types = {
7661 .types = {
7662 PTR_TO_MAP_VALUE,
7663 PTR_TO_BTF_ID | MEM_ALLOC,
7664 }
7665};
7666
f79e7ea5
LB
7667static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7668static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7669static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
894f2a8b 7670static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
f79e7ea5 7671static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
3f00c523
DV
7672static const struct bpf_reg_types btf_ptr_types = {
7673 .types = {
7674 PTR_TO_BTF_ID,
7675 PTR_TO_BTF_ID | PTR_TRUSTED,
fca1aa75 7676 PTR_TO_BTF_ID | MEM_RCU,
3f00c523
DV
7677 },
7678};
7679static const struct bpf_reg_types percpu_btf_ptr_types = {
7680 .types = {
7681 PTR_TO_BTF_ID | MEM_PERCPU,
7682 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7683 }
7684};
69c087ba
YS
7685static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7686static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 7687static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
b00628b1 7688static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
c0a5a21c 7689static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
20571567
DV
7690static const struct bpf_reg_types dynptr_types = {
7691 .types = {
7692 PTR_TO_STACK,
27060531 7693 CONST_PTR_TO_DYNPTR,
20571567
DV
7694 }
7695};
f79e7ea5 7696
0789e13b 7697static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
d1673304
DM
7698 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7699 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
f79e7ea5
LB
7700 [ARG_CONST_SIZE] = &scalar_types,
7701 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7702 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7703 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7704 [ARG_PTR_TO_CTX] = &context_types,
f79e7ea5 7705 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 7706#ifdef CONFIG_NET
1df8f55a 7707 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 7708#endif
f79e7ea5 7709 [ARG_PTR_TO_SOCKET] = &fullsock_types,
f79e7ea5
LB
7710 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7711 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7712 [ARG_PTR_TO_MEM] = &mem_types,
894f2a8b 7713 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
f79e7ea5
LB
7714 [ARG_PTR_TO_INT] = &int_ptr_types,
7715 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 7716 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba 7717 [ARG_PTR_TO_FUNC] = &func_ptr_types,
48946bd6 7718 [ARG_PTR_TO_STACK] = &stack_ptr_types,
fff13c4b 7719 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
b00628b1 7720 [ARG_PTR_TO_TIMER] = &timer_types,
c0a5a21c 7721 [ARG_PTR_TO_KPTR] = &kptr_types,
20571567 7722 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
f79e7ea5
LB
7723};
7724
7725static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2 7726 enum bpf_arg_type arg_type,
c0a5a21c
KKD
7727 const u32 *arg_btf_id,
7728 struct bpf_call_arg_meta *meta)
f79e7ea5
LB
7729{
7730 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7731 enum bpf_reg_type expected, type = reg->type;
a968d5e2 7732 const struct bpf_reg_types *compatible;
f79e7ea5
LB
7733 int i, j;
7734
48946bd6 7735 compatible = compatible_reg_types[base_type(arg_type)];
a968d5e2
MKL
7736 if (!compatible) {
7737 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7738 return -EFAULT;
7739 }
7740
216e3cd2
HL
7741 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7742 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7743 *
7744 * Same for MAYBE_NULL:
7745 *
7746 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7747 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7748 *
2012c867
DR
7749 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7750 *
216e3cd2
HL
7751 * Therefore we fold these flags depending on the arg_type before comparison.
7752 */
7753 if (arg_type & MEM_RDONLY)
7754 type &= ~MEM_RDONLY;
7755 if (arg_type & PTR_MAYBE_NULL)
7756 type &= ~PTR_MAYBE_NULL;
2012c867
DR
7757 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7758 type &= ~DYNPTR_TYPE_FLAG_MASK;
216e3cd2 7759
503e4def 7760 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
738c96d5
DM
7761 type &= ~MEM_ALLOC;
7762
f79e7ea5
LB
7763 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7764 expected = compatible->types[i];
7765 if (expected == NOT_INIT)
7766 break;
7767
7768 if (type == expected)
a968d5e2 7769 goto found;
f79e7ea5
LB
7770 }
7771
216e3cd2 7772 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
f79e7ea5 7773 for (j = 0; j + 1 < i; j++)
c25b2ae1
HL
7774 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7775 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
f79e7ea5 7776 return -EACCES;
a968d5e2
MKL
7777
7778found:
da03e43a
KKD
7779 if (base_type(reg->type) != PTR_TO_BTF_ID)
7780 return 0;
7781
3e30be42
AS
7782 if (compatible == &mem_types) {
7783 if (!(arg_type & MEM_RDONLY)) {
7784 verbose(env,
7785 "%s() may write into memory pointed by R%d type=%s\n",
7786 func_id_name(meta->func_id),
7787 regno, reg_type_str(env, reg->type));
7788 return -EACCES;
7789 }
7790 return 0;
7791 }
7792
da03e43a
KKD
7793 switch ((int)reg->type) {
7794 case PTR_TO_BTF_ID:
7795 case PTR_TO_BTF_ID | PTR_TRUSTED:
7796 case PTR_TO_BTF_ID | MEM_RCU:
add68b84
AS
7797 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7798 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
da03e43a 7799 {
2ab3b380
KKD
7800 /* For bpf_sk_release, it needs to match against first member
7801 * 'struct sock_common', hence make an exception for it. This
7802 * allows bpf_sk_release to work for multiple socket types.
7803 */
7804 bool strict_type_match = arg_type_is_release(arg_type) &&
7805 meta->func_id != BPF_FUNC_sk_release;
7806
add68b84
AS
7807 if (type_may_be_null(reg->type) &&
7808 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7809 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7810 return -EACCES;
7811 }
7812
1df8f55a
MKL
7813 if (!arg_btf_id) {
7814 if (!compatible->btf_id) {
7815 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7816 return -EFAULT;
7817 }
7818 arg_btf_id = compatible->btf_id;
7819 }
7820
c0a5a21c 7821 if (meta->func_id == BPF_FUNC_kptr_xchg) {
aa3496ac 7822 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
c0a5a21c 7823 return -EACCES;
47e34cb7
DM
7824 } else {
7825 if (arg_btf_id == BPF_PTR_POISON) {
7826 verbose(env, "verifier internal error:");
7827 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7828 regno);
7829 return -EACCES;
7830 }
7831
7832 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7833 btf_vmlinux, *arg_btf_id,
7834 strict_type_match)) {
7835 verbose(env, "R%d is of type %s but %s is expected\n",
b32a5dae
DM
7836 regno, btf_type_name(reg->btf, reg->btf_id),
7837 btf_type_name(btf_vmlinux, *arg_btf_id));
47e34cb7
DM
7838 return -EACCES;
7839 }
a968d5e2 7840 }
da03e43a
KKD
7841 break;
7842 }
7843 case PTR_TO_BTF_ID | MEM_ALLOC:
738c96d5
DM
7844 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7845 meta->func_id != BPF_FUNC_kptr_xchg) {
4e814da0
KKD
7846 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7847 return -EFAULT;
7848 }
da03e43a
KKD
7849 /* Handled by helper specific checks */
7850 break;
7851 case PTR_TO_BTF_ID | MEM_PERCPU:
7852 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7853 /* Handled by helper specific checks */
7854 break;
7855 default:
7856 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7857 return -EFAULT;
a968d5e2 7858 }
a968d5e2 7859 return 0;
f79e7ea5
LB
7860}
7861
6a3cd331
DM
7862static struct btf_field *
7863reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7864{
7865 struct btf_field *field;
7866 struct btf_record *rec;
7867
7868 rec = reg_btf_record(reg);
7869 if (!rec)
7870 return NULL;
7871
7872 field = btf_record_find(rec, off, fields);
7873 if (!field)
7874 return NULL;
7875
7876 return field;
7877}
7878
25b35dd2
KKD
7879int check_func_arg_reg_off(struct bpf_verifier_env *env,
7880 const struct bpf_reg_state *reg, int regno,
8f14852e 7881 enum bpf_arg_type arg_type)
25b35dd2 7882{
184c9bdb 7883 u32 type = reg->type;
25b35dd2 7884
184c9bdb
KKD
7885 /* When referenced register is passed to release function, its fixed
7886 * offset must be 0.
7887 *
7888 * We will check arg_type_is_release reg has ref_obj_id when storing
7889 * meta->release_regno.
7890 */
7891 if (arg_type_is_release(arg_type)) {
7892 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7893 * may not directly point to the object being released, but to
7894 * dynptr pointing to such object, which might be at some offset
7895 * on the stack. In that case, we simply to fallback to the
7896 * default handling.
7897 */
7898 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7899 return 0;
6a3cd331
DM
7900
7901 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7902 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7903 return __check_ptr_off_reg(env, reg, regno, true);
7904
7905 verbose(env, "R%d must have zero offset when passed to release func\n",
7906 regno);
7907 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
b32a5dae 7908 btf_type_name(reg->btf, reg->btf_id), reg->off);
6a3cd331
DM
7909 return -EINVAL;
7910 }
7911
184c9bdb
KKD
7912 /* Doing check_ptr_off_reg check for the offset will catch this
7913 * because fixed_off_ok is false, but checking here allows us
7914 * to give the user a better error message.
7915 */
7916 if (reg->off) {
7917 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7918 regno);
7919 return -EINVAL;
7920 }
7921 return __check_ptr_off_reg(env, reg, regno, false);
7922 }
7923
7924 switch (type) {
7925 /* Pointer types where both fixed and variable offset is explicitly allowed: */
97e03f52 7926 case PTR_TO_STACK:
25b35dd2
KKD
7927 case PTR_TO_PACKET:
7928 case PTR_TO_PACKET_META:
7929 case PTR_TO_MAP_KEY:
7930 case PTR_TO_MAP_VALUE:
7931 case PTR_TO_MEM:
7932 case PTR_TO_MEM | MEM_RDONLY:
894f2a8b 7933 case PTR_TO_MEM | MEM_RINGBUF:
25b35dd2
KKD
7934 case PTR_TO_BUF:
7935 case PTR_TO_BUF | MEM_RDONLY:
97e03f52 7936 case SCALAR_VALUE:
184c9bdb 7937 return 0;
25b35dd2
KKD
7938 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7939 * fixed offset.
7940 */
7941 case PTR_TO_BTF_ID:
282de143 7942 case PTR_TO_BTF_ID | MEM_ALLOC:
3f00c523 7943 case PTR_TO_BTF_ID | PTR_TRUSTED:
fca1aa75 7944 case PTR_TO_BTF_ID | MEM_RCU:
6a3cd331 7945 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
24d5bb80 7946 /* When referenced PTR_TO_BTF_ID is passed to release function,
184c9bdb
KKD
7947 * its fixed offset must be 0. In the other cases, fixed offset
7948 * can be non-zero. This was already checked above. So pass
7949 * fixed_off_ok as true to allow fixed offset for all other
7950 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7951 * still need to do checks instead of returning.
24d5bb80 7952 */
184c9bdb 7953 return __check_ptr_off_reg(env, reg, regno, true);
25b35dd2 7954 default:
184c9bdb 7955 return __check_ptr_off_reg(env, reg, regno, false);
25b35dd2 7956 }
25b35dd2
KKD
7957}
7958
485ec51e
JK
7959static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7960 const struct bpf_func_proto *fn,
7961 struct bpf_reg_state *regs)
7962{
7963 struct bpf_reg_state *state = NULL;
7964 int i;
7965
7966 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7967 if (arg_type_is_dynptr(fn->arg_type[i])) {
7968 if (state) {
7969 verbose(env, "verifier internal error: multiple dynptr args\n");
7970 return NULL;
7971 }
7972 state = &regs[BPF_REG_1 + i];
7973 }
7974
7975 if (!state)
7976 verbose(env, "verifier internal error: no dynptr arg found\n");
7977
7978 return state;
7979}
7980
f8064ab9 7981static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
34d4ef57
JK
7982{
7983 struct bpf_func_state *state = func(env, reg);
27060531 7984 int spi;
34d4ef57 7985
27060531 7986 if (reg->type == CONST_PTR_TO_DYNPTR)
f8064ab9
KKD
7987 return reg->id;
7988 spi = dynptr_get_spi(env, reg);
7989 if (spi < 0)
7990 return spi;
7991 return state->stack[spi].spilled_ptr.id;
7992}
7993
79168a66 7994static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
34d4ef57
JK
7995{
7996 struct bpf_func_state *state = func(env, reg);
27060531 7997 int spi;
27060531 7998
27060531
KKD
7999 if (reg->type == CONST_PTR_TO_DYNPTR)
8000 return reg->ref_obj_id;
79168a66
KKD
8001 spi = dynptr_get_spi(env, reg);
8002 if (spi < 0)
8003 return spi;
27060531 8004 return state->stack[spi].spilled_ptr.ref_obj_id;
34d4ef57
JK
8005}
8006
b5964b96
JK
8007static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8008 struct bpf_reg_state *reg)
8009{
8010 struct bpf_func_state *state = func(env, reg);
8011 int spi;
8012
8013 if (reg->type == CONST_PTR_TO_DYNPTR)
8014 return reg->dynptr.type;
8015
8016 spi = __get_spi(reg->off);
8017 if (spi < 0) {
8018 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8019 return BPF_DYNPTR_TYPE_INVALID;
8020 }
8021
8022 return state->stack[spi].spilled_ptr.dynptr.type;
8023}
8024
af7ec138
YS
8025static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8026 struct bpf_call_arg_meta *meta,
1d18feb2
JK
8027 const struct bpf_func_proto *fn,
8028 int insn_idx)
17a52670 8029{
af7ec138 8030 u32 regno = BPF_REG_1 + arg;
638f5b90 8031 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 8032 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 8033 enum bpf_reg_type type = reg->type;
508362ac 8034 u32 *arg_btf_id = NULL;
17a52670
AS
8035 int err = 0;
8036
80f1d68c 8037 if (arg_type == ARG_DONTCARE)
17a52670
AS
8038 return 0;
8039
dc503a8a
EC
8040 err = check_reg_arg(env, regno, SRC_OP);
8041 if (err)
8042 return err;
17a52670 8043
1be7f75d
AS
8044 if (arg_type == ARG_ANYTHING) {
8045 if (is_pointer_value(env, regno)) {
61bd5218
JK
8046 verbose(env, "R%d leaks addr into helper function\n",
8047 regno);
1be7f75d
AS
8048 return -EACCES;
8049 }
80f1d68c 8050 return 0;
1be7f75d 8051 }
80f1d68c 8052
de8f3a83 8053 if (type_is_pkt_pointer(type) &&
3a0af8fd 8054 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 8055 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
8056 return -EACCES;
8057 }
8058
16d1e00c 8059 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
912f442c
LB
8060 err = resolve_map_arg_type(env, meta, &arg_type);
8061 if (err)
8062 return err;
8063 }
8064
48946bd6 8065 if (register_is_null(reg) && type_may_be_null(arg_type))
fd1b0d60
LB
8066 /* A NULL register has a SCALAR_VALUE type, so skip
8067 * type checking.
8068 */
8069 goto skip_type_check;
8070
508362ac 8071 /* arg_btf_id and arg_size are in a union. */
4e814da0
KKD
8072 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8073 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
508362ac
MM
8074 arg_btf_id = fn->arg_btf_id[arg];
8075
8076 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
f79e7ea5
LB
8077 if (err)
8078 return err;
8079
8f14852e 8080 err = check_func_arg_reg_off(env, reg, regno, arg_type);
25b35dd2
KKD
8081 if (err)
8082 return err;
d7b9454a 8083
fd1b0d60 8084skip_type_check:
8f14852e 8085 if (arg_type_is_release(arg_type)) {
bc34dee6
JK
8086 if (arg_type_is_dynptr(arg_type)) {
8087 struct bpf_func_state *state = func(env, reg);
27060531 8088 int spi;
bc34dee6 8089
27060531
KKD
8090 /* Only dynptr created on stack can be released, thus
8091 * the get_spi and stack state checks for spilled_ptr
8092 * should only be done before process_dynptr_func for
8093 * PTR_TO_STACK.
8094 */
8095 if (reg->type == PTR_TO_STACK) {
79168a66 8096 spi = dynptr_get_spi(env, reg);
f5b625e5 8097 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
27060531
KKD
8098 verbose(env, "arg %d is an unacquired reference\n", regno);
8099 return -EINVAL;
8100 }
8101 } else {
8102 verbose(env, "cannot release unowned const bpf_dynptr\n");
bc34dee6
JK
8103 return -EINVAL;
8104 }
8105 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8f14852e
KKD
8106 verbose(env, "R%d must be referenced when passed to release function\n",
8107 regno);
8108 return -EINVAL;
8109 }
8110 if (meta->release_regno) {
8111 verbose(env, "verifier internal error: more than one release argument\n");
8112 return -EFAULT;
8113 }
8114 meta->release_regno = regno;
8115 }
8116
02f7c958 8117 if (reg->ref_obj_id) {
457f4436
AN
8118 if (meta->ref_obj_id) {
8119 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8120 regno, reg->ref_obj_id,
8121 meta->ref_obj_id);
8122 return -EFAULT;
8123 }
8124 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
8125 }
8126
8ab4cdcf
JK
8127 switch (base_type(arg_type)) {
8128 case ARG_CONST_MAP_PTR:
17a52670 8129 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3e8ce298
AS
8130 if (meta->map_ptr) {
8131 /* Use map_uid (which is unique id of inner map) to reject:
8132 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8133 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8134 * if (inner_map1 && inner_map2) {
8135 * timer = bpf_map_lookup_elem(inner_map1);
8136 * if (timer)
8137 * // mismatch would have been allowed
8138 * bpf_timer_init(timer, inner_map2);
8139 * }
8140 *
8141 * Comparing map_ptr is enough to distinguish normal and outer maps.
8142 */
8143 if (meta->map_ptr != reg->map_ptr ||
8144 meta->map_uid != reg->map_uid) {
8145 verbose(env,
8146 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8147 meta->map_uid, reg->map_uid);
8148 return -EINVAL;
8149 }
b00628b1 8150 }
33ff9823 8151 meta->map_ptr = reg->map_ptr;
3e8ce298 8152 meta->map_uid = reg->map_uid;
8ab4cdcf
JK
8153 break;
8154 case ARG_PTR_TO_MAP_KEY:
17a52670
AS
8155 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8156 * check that [key, key + map->key_size) are within
8157 * stack limits and initialized
8158 */
33ff9823 8159 if (!meta->map_ptr) {
17a52670
AS
8160 /* in function declaration map_ptr must come before
8161 * map_key, so that it's verified and known before
8162 * we have to check map_key here. Otherwise it means
8163 * that kernel subsystem misconfigured verifier
8164 */
61bd5218 8165 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
8166 return -EACCES;
8167 }
d71962f3
PC
8168 err = check_helper_mem_access(env, regno,
8169 meta->map_ptr->key_size, false,
8170 NULL);
8ab4cdcf
JK
8171 break;
8172 case ARG_PTR_TO_MAP_VALUE:
48946bd6
HL
8173 if (type_may_be_null(arg_type) && register_is_null(reg))
8174 return 0;
8175
17a52670
AS
8176 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8177 * check [value, value + map->value_size) validity
8178 */
33ff9823 8179 if (!meta->map_ptr) {
17a52670 8180 /* kernel subsystem misconfigured verifier */
61bd5218 8181 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
8182 return -EACCES;
8183 }
16d1e00c 8184 meta->raw_mode = arg_type & MEM_UNINIT;
d71962f3
PC
8185 err = check_helper_mem_access(env, regno,
8186 meta->map_ptr->value_size, false,
2ea864c5 8187 meta);
8ab4cdcf
JK
8188 break;
8189 case ARG_PTR_TO_PERCPU_BTF_ID:
eaa6bcb7
HL
8190 if (!reg->btf_id) {
8191 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8192 return -EACCES;
8193 }
22dc4a0f 8194 meta->ret_btf = reg->btf;
eaa6bcb7 8195 meta->ret_btf_id = reg->btf_id;
8ab4cdcf
JK
8196 break;
8197 case ARG_PTR_TO_SPIN_LOCK:
5d92ddc3
DM
8198 if (in_rbtree_lock_required_cb(env)) {
8199 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8200 return -EACCES;
8201 }
c18f0b6a 8202 if (meta->func_id == BPF_FUNC_spin_lock) {
ac50fe51
KKD
8203 err = process_spin_lock(env, regno, true);
8204 if (err)
8205 return err;
c18f0b6a 8206 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
ac50fe51
KKD
8207 err = process_spin_lock(env, regno, false);
8208 if (err)
8209 return err;
c18f0b6a
LB
8210 } else {
8211 verbose(env, "verifier internal error\n");
8212 return -EFAULT;
8213 }
8ab4cdcf
JK
8214 break;
8215 case ARG_PTR_TO_TIMER:
ac50fe51
KKD
8216 err = process_timer_func(env, regno, meta);
8217 if (err)
8218 return err;
8ab4cdcf
JK
8219 break;
8220 case ARG_PTR_TO_FUNC:
69c087ba 8221 meta->subprogno = reg->subprogno;
8ab4cdcf
JK
8222 break;
8223 case ARG_PTR_TO_MEM:
a2bbe7cc
LB
8224 /* The access to this pointer is only checked when we hit the
8225 * next is_mem_size argument below.
8226 */
16d1e00c 8227 meta->raw_mode = arg_type & MEM_UNINIT;
508362ac
MM
8228 if (arg_type & MEM_FIXED_SIZE) {
8229 err = check_helper_mem_access(env, regno,
8230 fn->arg_size[arg], false,
8231 meta);
8232 }
8ab4cdcf
JK
8233 break;
8234 case ARG_CONST_SIZE:
8235 err = check_mem_size_reg(env, reg, regno, false, meta);
8236 break;
8237 case ARG_CONST_SIZE_OR_ZERO:
8238 err = check_mem_size_reg(env, reg, regno, true, meta);
8239 break;
8240 case ARG_PTR_TO_DYNPTR:
361f129f 8241 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
ac50fe51
KKD
8242 if (err)
8243 return err;
8ab4cdcf
JK
8244 break;
8245 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
457f4436 8246 if (!tnum_is_const(reg->var_off)) {
28a8add6 8247 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
8248 regno);
8249 return -EACCES;
8250 }
8251 meta->mem_size = reg->var_off.value;
2fc31465
KKD
8252 err = mark_chain_precision(env, regno);
8253 if (err)
8254 return err;
8ab4cdcf
JK
8255 break;
8256 case ARG_PTR_TO_INT:
8257 case ARG_PTR_TO_LONG:
8258 {
57c3bb72
AI
8259 int size = int_ptr_type_to_size(arg_type);
8260
8261 err = check_helper_mem_access(env, regno, size, false, meta);
8262 if (err)
8263 return err;
8264 err = check_ptr_alignment(env, reg, 0, size, true);
8ab4cdcf
JK
8265 break;
8266 }
8267 case ARG_PTR_TO_CONST_STR:
8268 {
fff13c4b
FR
8269 struct bpf_map *map = reg->map_ptr;
8270 int map_off;
8271 u64 map_addr;
8272 char *str_ptr;
8273
a8fad73e 8274 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
8275 verbose(env, "R%d does not point to a readonly map'\n", regno);
8276 return -EACCES;
8277 }
8278
8279 if (!tnum_is_const(reg->var_off)) {
8280 verbose(env, "R%d is not a constant address'\n", regno);
8281 return -EACCES;
8282 }
8283
8284 if (!map->ops->map_direct_value_addr) {
8285 verbose(env, "no direct value access support for this map type\n");
8286 return -EACCES;
8287 }
8288
8289 err = check_map_access(env, regno, reg->off,
61df10c7
KKD
8290 map->value_size - reg->off, false,
8291 ACCESS_HELPER);
fff13c4b
FR
8292 if (err)
8293 return err;
8294
8295 map_off = reg->off + reg->var_off.value;
8296 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8297 if (err) {
8298 verbose(env, "direct value access on string failed\n");
8299 return err;
8300 }
8301
8302 str_ptr = (char *)(long)(map_addr);
8303 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8304 verbose(env, "string is not zero-terminated\n");
8305 return -EINVAL;
8306 }
8ab4cdcf
JK
8307 break;
8308 }
8309 case ARG_PTR_TO_KPTR:
ac50fe51
KKD
8310 err = process_kptr_func(env, regno, meta);
8311 if (err)
8312 return err;
8ab4cdcf 8313 break;
17a52670
AS
8314 }
8315
8316 return err;
8317}
8318
0126240f
LB
8319static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8320{
8321 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 8322 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
8323
8324 if (func_id != BPF_FUNC_map_update_elem)
8325 return false;
8326
8327 /* It's not possible to get access to a locked struct sock in these
8328 * contexts, so updating is safe.
8329 */
8330 switch (type) {
8331 case BPF_PROG_TYPE_TRACING:
8332 if (eatype == BPF_TRACE_ITER)
8333 return true;
8334 break;
8335 case BPF_PROG_TYPE_SOCKET_FILTER:
8336 case BPF_PROG_TYPE_SCHED_CLS:
8337 case BPF_PROG_TYPE_SCHED_ACT:
8338 case BPF_PROG_TYPE_XDP:
8339 case BPF_PROG_TYPE_SK_REUSEPORT:
8340 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8341 case BPF_PROG_TYPE_SK_LOOKUP:
8342 return true;
8343 default:
8344 break;
8345 }
8346
8347 verbose(env, "cannot update sockmap in this context\n");
8348 return false;
8349}
8350
e411901c
MF
8351static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8352{
95acd881
TA
8353 return env->prog->jit_requested &&
8354 bpf_jit_supports_subprog_tailcalls();
e411901c
MF
8355}
8356
61bd5218
JK
8357static int check_map_func_compatibility(struct bpf_verifier_env *env,
8358 struct bpf_map *map, int func_id)
35578d79 8359{
35578d79
KX
8360 if (!map)
8361 return 0;
8362
6aff67c8
AS
8363 /* We need a two way check, first is from map perspective ... */
8364 switch (map->map_type) {
8365 case BPF_MAP_TYPE_PROG_ARRAY:
8366 if (func_id != BPF_FUNC_tail_call)
8367 goto error;
8368 break;
8369 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8370 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 8371 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 8372 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
8373 func_id != BPF_FUNC_perf_event_read_value &&
8374 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
8375 goto error;
8376 break;
457f4436
AN
8377 case BPF_MAP_TYPE_RINGBUF:
8378 if (func_id != BPF_FUNC_ringbuf_output &&
8379 func_id != BPF_FUNC_ringbuf_reserve &&
bc34dee6
JK
8380 func_id != BPF_FUNC_ringbuf_query &&
8381 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8382 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8383 func_id != BPF_FUNC_ringbuf_discard_dynptr)
457f4436
AN
8384 goto error;
8385 break;
583c1f42 8386 case BPF_MAP_TYPE_USER_RINGBUF:
20571567
DV
8387 if (func_id != BPF_FUNC_user_ringbuf_drain)
8388 goto error;
8389 break;
6aff67c8
AS
8390 case BPF_MAP_TYPE_STACK_TRACE:
8391 if (func_id != BPF_FUNC_get_stackid)
8392 goto error;
8393 break;
4ed8ec52 8394 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 8395 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 8396 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
8397 goto error;
8398 break;
cd339431 8399 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 8400 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
8401 if (func_id != BPF_FUNC_get_local_storage)
8402 goto error;
8403 break;
546ac1ff 8404 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 8405 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
8406 if (func_id != BPF_FUNC_redirect_map &&
8407 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
8408 goto error;
8409 break;
fbfc504a
BT
8410 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8411 * appear.
8412 */
6710e112
JDB
8413 case BPF_MAP_TYPE_CPUMAP:
8414 if (func_id != BPF_FUNC_redirect_map)
8415 goto error;
8416 break;
fada7fdc
JL
8417 case BPF_MAP_TYPE_XSKMAP:
8418 if (func_id != BPF_FUNC_redirect_map &&
8419 func_id != BPF_FUNC_map_lookup_elem)
8420 goto error;
8421 break;
56f668df 8422 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 8423 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
8424 if (func_id != BPF_FUNC_map_lookup_elem)
8425 goto error;
16a43625 8426 break;
174a79ff
JF
8427 case BPF_MAP_TYPE_SOCKMAP:
8428 if (func_id != BPF_FUNC_sk_redirect_map &&
8429 func_id != BPF_FUNC_sock_map_update &&
4f738adb 8430 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 8431 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 8432 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
8433 func_id != BPF_FUNC_map_lookup_elem &&
8434 !may_update_sockmap(env, func_id))
174a79ff
JF
8435 goto error;
8436 break;
81110384
JF
8437 case BPF_MAP_TYPE_SOCKHASH:
8438 if (func_id != BPF_FUNC_sk_redirect_hash &&
8439 func_id != BPF_FUNC_sock_hash_update &&
8440 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 8441 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 8442 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
8443 func_id != BPF_FUNC_map_lookup_elem &&
8444 !may_update_sockmap(env, func_id))
81110384
JF
8445 goto error;
8446 break;
2dbb9b9e
MKL
8447 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8448 if (func_id != BPF_FUNC_sk_select_reuseport)
8449 goto error;
8450 break;
f1a2e44a
MV
8451 case BPF_MAP_TYPE_QUEUE:
8452 case BPF_MAP_TYPE_STACK:
8453 if (func_id != BPF_FUNC_map_peek_elem &&
8454 func_id != BPF_FUNC_map_pop_elem &&
8455 func_id != BPF_FUNC_map_push_elem)
8456 goto error;
8457 break;
6ac99e8f
MKL
8458 case BPF_MAP_TYPE_SK_STORAGE:
8459 if (func_id != BPF_FUNC_sk_storage_get &&
9db44fdd
KKD
8460 func_id != BPF_FUNC_sk_storage_delete &&
8461 func_id != BPF_FUNC_kptr_xchg)
6ac99e8f
MKL
8462 goto error;
8463 break;
8ea63684
KS
8464 case BPF_MAP_TYPE_INODE_STORAGE:
8465 if (func_id != BPF_FUNC_inode_storage_get &&
9db44fdd
KKD
8466 func_id != BPF_FUNC_inode_storage_delete &&
8467 func_id != BPF_FUNC_kptr_xchg)
8ea63684
KS
8468 goto error;
8469 break;
4cf1bc1f
KS
8470 case BPF_MAP_TYPE_TASK_STORAGE:
8471 if (func_id != BPF_FUNC_task_storage_get &&
9db44fdd
KKD
8472 func_id != BPF_FUNC_task_storage_delete &&
8473 func_id != BPF_FUNC_kptr_xchg)
4cf1bc1f
KS
8474 goto error;
8475 break;
c4bcfb38
YS
8476 case BPF_MAP_TYPE_CGRP_STORAGE:
8477 if (func_id != BPF_FUNC_cgrp_storage_get &&
9db44fdd
KKD
8478 func_id != BPF_FUNC_cgrp_storage_delete &&
8479 func_id != BPF_FUNC_kptr_xchg)
c4bcfb38
YS
8480 goto error;
8481 break;
9330986c
JK
8482 case BPF_MAP_TYPE_BLOOM_FILTER:
8483 if (func_id != BPF_FUNC_map_peek_elem &&
8484 func_id != BPF_FUNC_map_push_elem)
8485 goto error;
8486 break;
6aff67c8
AS
8487 default:
8488 break;
8489 }
8490
8491 /* ... and second from the function itself. */
8492 switch (func_id) {
8493 case BPF_FUNC_tail_call:
8494 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8495 goto error;
e411901c
MF
8496 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8497 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
8498 return -EINVAL;
8499 }
6aff67c8
AS
8500 break;
8501 case BPF_FUNC_perf_event_read:
8502 case BPF_FUNC_perf_event_output:
908432ca 8503 case BPF_FUNC_perf_event_read_value:
a7658e1a 8504 case BPF_FUNC_skb_output:
d831ee84 8505 case BPF_FUNC_xdp_output:
6aff67c8
AS
8506 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8507 goto error;
8508 break;
5b029a32
DB
8509 case BPF_FUNC_ringbuf_output:
8510 case BPF_FUNC_ringbuf_reserve:
8511 case BPF_FUNC_ringbuf_query:
bc34dee6
JK
8512 case BPF_FUNC_ringbuf_reserve_dynptr:
8513 case BPF_FUNC_ringbuf_submit_dynptr:
8514 case BPF_FUNC_ringbuf_discard_dynptr:
5b029a32
DB
8515 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8516 goto error;
8517 break;
20571567
DV
8518 case BPF_FUNC_user_ringbuf_drain:
8519 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8520 goto error;
8521 break;
6aff67c8
AS
8522 case BPF_FUNC_get_stackid:
8523 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8524 goto error;
8525 break;
60d20f91 8526 case BPF_FUNC_current_task_under_cgroup:
747ea55e 8527 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
8528 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8529 goto error;
8530 break;
97f91a7c 8531 case BPF_FUNC_redirect_map:
9c270af3 8532 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 8533 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
8534 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8535 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
8536 goto error;
8537 break;
174a79ff 8538 case BPF_FUNC_sk_redirect_map:
4f738adb 8539 case BPF_FUNC_msg_redirect_map:
81110384 8540 case BPF_FUNC_sock_map_update:
174a79ff
JF
8541 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8542 goto error;
8543 break;
81110384
JF
8544 case BPF_FUNC_sk_redirect_hash:
8545 case BPF_FUNC_msg_redirect_hash:
8546 case BPF_FUNC_sock_hash_update:
8547 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
8548 goto error;
8549 break;
cd339431 8550 case BPF_FUNC_get_local_storage:
b741f163
RG
8551 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8552 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
8553 goto error;
8554 break;
2dbb9b9e 8555 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
8556 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8557 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8558 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
8559 goto error;
8560 break;
f1a2e44a 8561 case BPF_FUNC_map_pop_elem:
f1a2e44a
MV
8562 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8563 map->map_type != BPF_MAP_TYPE_STACK)
8564 goto error;
8565 break;
9330986c
JK
8566 case BPF_FUNC_map_peek_elem:
8567 case BPF_FUNC_map_push_elem:
8568 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8569 map->map_type != BPF_MAP_TYPE_STACK &&
8570 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8571 goto error;
8572 break;
07343110
FZ
8573 case BPF_FUNC_map_lookup_percpu_elem:
8574 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8575 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8576 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8577 goto error;
8578 break;
6ac99e8f
MKL
8579 case BPF_FUNC_sk_storage_get:
8580 case BPF_FUNC_sk_storage_delete:
8581 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8582 goto error;
8583 break;
8ea63684
KS
8584 case BPF_FUNC_inode_storage_get:
8585 case BPF_FUNC_inode_storage_delete:
8586 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8587 goto error;
8588 break;
4cf1bc1f
KS
8589 case BPF_FUNC_task_storage_get:
8590 case BPF_FUNC_task_storage_delete:
8591 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8592 goto error;
8593 break;
c4bcfb38
YS
8594 case BPF_FUNC_cgrp_storage_get:
8595 case BPF_FUNC_cgrp_storage_delete:
8596 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8597 goto error;
8598 break;
6aff67c8
AS
8599 default:
8600 break;
35578d79
KX
8601 }
8602
8603 return 0;
6aff67c8 8604error:
61bd5218 8605 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 8606 map->map_type, func_id_name(func_id), func_id);
6aff67c8 8607 return -EINVAL;
35578d79
KX
8608}
8609
90133415 8610static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
8611{
8612 int count = 0;
8613
39f19ebb 8614 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 8615 count++;
39f19ebb 8616 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 8617 count++;
39f19ebb 8618 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 8619 count++;
39f19ebb 8620 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 8621 count++;
39f19ebb 8622 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
8623 count++;
8624
90133415
DB
8625 /* We only support one arg being in raw mode at the moment,
8626 * which is sufficient for the helper functions we have
8627 * right now.
8628 */
8629 return count <= 1;
8630}
8631
508362ac 8632static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
90133415 8633{
508362ac
MM
8634 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8635 bool has_size = fn->arg_size[arg] != 0;
8636 bool is_next_size = false;
8637
8638 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8639 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8640
8641 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8642 return is_next_size;
8643
8644 return has_size == is_next_size || is_next_size == is_fixed;
90133415
DB
8645}
8646
8647static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8648{
8649 /* bpf_xxx(..., buf, len) call will access 'len'
8650 * bytes from memory 'buf'. Both arg types need
8651 * to be paired, so make sure there's no buggy
8652 * helper function specification.
8653 */
8654 if (arg_type_is_mem_size(fn->arg1_type) ||
508362ac
MM
8655 check_args_pair_invalid(fn, 0) ||
8656 check_args_pair_invalid(fn, 1) ||
8657 check_args_pair_invalid(fn, 2) ||
8658 check_args_pair_invalid(fn, 3) ||
8659 check_args_pair_invalid(fn, 4))
90133415
DB
8660 return false;
8661
8662 return true;
8663}
8664
9436ef6e
LB
8665static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8666{
8667 int i;
8668
1df8f55a 8669 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4e814da0
KKD
8670 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8671 return !!fn->arg_btf_id[i];
8672 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8673 return fn->arg_btf_id[i] == BPF_PTR_POISON;
508362ac
MM
8674 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8675 /* arg_btf_id and arg_size are in a union. */
8676 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8677 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
1df8f55a
MKL
8678 return false;
8679 }
8680
9436ef6e
LB
8681 return true;
8682}
8683
0c9a7a7e 8684static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
8685{
8686 return check_raw_mode_ok(fn) &&
fd978bf7 8687 check_arg_pair_ok(fn) &&
b2d8ef19 8688 check_btf_id_ok(fn) ? 0 : -EINVAL;
435faee1
DB
8689}
8690
de8f3a83
DB
8691/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8692 * are now invalid, so turn them into unknown SCALAR_VALUE.
66e3a13e
JK
8693 *
8694 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8695 * since these slices point to packet data.
f1174f77 8696 */
b239da34 8697static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 8698{
b239da34
KKD
8699 struct bpf_func_state *state;
8700 struct bpf_reg_state *reg;
969bf05e 8701
b239da34 8702 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
66e3a13e 8703 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
dbd8d228 8704 mark_reg_invalid(env, reg);
b239da34 8705 }));
f4d7e40a
AS
8706}
8707
6d94e741
AS
8708enum {
8709 AT_PKT_END = -1,
8710 BEYOND_PKT_END = -2,
8711};
8712
8713static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8714{
8715 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8716 struct bpf_reg_state *reg = &state->regs[regn];
8717
8718 if (reg->type != PTR_TO_PACKET)
8719 /* PTR_TO_PACKET_META is not supported yet */
8720 return;
8721
8722 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8723 * How far beyond pkt_end it goes is unknown.
8724 * if (!range_open) it's the case of pkt >= pkt_end
8725 * if (range_open) it's the case of pkt > pkt_end
8726 * hence this pointer is at least 1 byte bigger than pkt_end
8727 */
8728 if (range_open)
8729 reg->range = BEYOND_PKT_END;
8730 else
8731 reg->range = AT_PKT_END;
8732}
8733
fd978bf7
JS
8734/* The pointer with the specified id has released its reference to kernel
8735 * resources. Identify all copies of the same pointer and clear the reference.
8736 */
8737static int release_reference(struct bpf_verifier_env *env,
1b986589 8738 int ref_obj_id)
fd978bf7 8739{
b239da34
KKD
8740 struct bpf_func_state *state;
8741 struct bpf_reg_state *reg;
1b986589 8742 int err;
fd978bf7 8743
1b986589
MKL
8744 err = release_reference_state(cur_func(env), ref_obj_id);
8745 if (err)
8746 return err;
8747
b239da34 8748 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
dbd8d228
KKD
8749 if (reg->ref_obj_id == ref_obj_id)
8750 mark_reg_invalid(env, reg);
b239da34 8751 }));
fd978bf7 8752
1b986589 8753 return 0;
fd978bf7
JS
8754}
8755
6a3cd331
DM
8756static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8757{
8758 struct bpf_func_state *unused;
8759 struct bpf_reg_state *reg;
8760
8761 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8762 if (type_is_non_owning_ref(reg->type))
dbd8d228 8763 mark_reg_invalid(env, reg);
6a3cd331
DM
8764 }));
8765}
8766
51c39bb1
AS
8767static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8768 struct bpf_reg_state *regs)
8769{
8770 int i;
8771
8772 /* after the call registers r0 - r5 were scratched */
8773 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8774 mark_reg_not_init(env, regs, caller_saved[i]);
8775 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8776 }
8777}
8778
14351375
YS
8779typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8780 struct bpf_func_state *caller,
8781 struct bpf_func_state *callee,
8782 int insn_idx);
8783
be2ef816
AN
8784static int set_callee_state(struct bpf_verifier_env *env,
8785 struct bpf_func_state *caller,
8786 struct bpf_func_state *callee, int insn_idx);
8787
14351375
YS
8788static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8789 int *insn_idx, int subprog,
8790 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
8791{
8792 struct bpf_verifier_state *state = env->cur_state;
8793 struct bpf_func_state *caller, *callee;
14351375 8794 int err;
f4d7e40a 8795
aada9ce6 8796 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 8797 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 8798 state->curframe + 2);
f4d7e40a
AS
8799 return -E2BIG;
8800 }
8801
f4d7e40a
AS
8802 caller = state->frame[state->curframe];
8803 if (state->frame[state->curframe + 1]) {
8804 verbose(env, "verifier bug. Frame %d already allocated\n",
8805 state->curframe + 1);
8806 return -EFAULT;
8807 }
8808
95f2f26f 8809 err = btf_check_subprog_call(env, subprog, caller->regs);
51c39bb1
AS
8810 if (err == -EFAULT)
8811 return err;
fde2a388 8812 if (subprog_is_global(env, subprog)) {
51c39bb1
AS
8813 if (err) {
8814 verbose(env, "Caller passes invalid args into func#%d\n",
8815 subprog);
8816 return err;
8817 } else {
8818 if (env->log.level & BPF_LOG_LEVEL)
8819 verbose(env,
8820 "Func#%d is global and valid. Skipping.\n",
8821 subprog);
8822 clear_caller_saved_regs(env, caller->regs);
8823
45159b27 8824 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 8825 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 8826 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
8827
8828 /* continue with next insn after call */
8829 return 0;
8830 }
8831 }
8832
be2ef816
AN
8833 /* set_callee_state is used for direct subprog calls, but we are
8834 * interested in validating only BPF helpers that can call subprogs as
8835 * callbacks
8836 */
5d92ddc3
DM
8837 if (set_callee_state_cb != set_callee_state) {
8838 if (bpf_pseudo_kfunc_call(insn) &&
8839 !is_callback_calling_kfunc(insn->imm)) {
8840 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8841 func_id_name(insn->imm), insn->imm);
8842 return -EFAULT;
8843 } else if (!bpf_pseudo_kfunc_call(insn) &&
8844 !is_callback_calling_function(insn->imm)) { /* helper */
8845 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8846 func_id_name(insn->imm), insn->imm);
8847 return -EFAULT;
8848 }
be2ef816
AN
8849 }
8850
bfc6bb74 8851 if (insn->code == (BPF_JMP | BPF_CALL) &&
a5bebc4f 8852 insn->src_reg == 0 &&
bfc6bb74
AS
8853 insn->imm == BPF_FUNC_timer_set_callback) {
8854 struct bpf_verifier_state *async_cb;
8855
8856 /* there is no real recursion here. timer callbacks are async */
7ddc80a4 8857 env->subprog_info[subprog].is_async_cb = true;
bfc6bb74
AS
8858 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8859 *insn_idx, subprog);
8860 if (!async_cb)
8861 return -EFAULT;
8862 callee = async_cb->frame[0];
8863 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8864
8865 /* Convert bpf_timer_set_callback() args into timer callback args */
8866 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8867 if (err)
8868 return err;
8869
8870 clear_caller_saved_regs(env, caller->regs);
8871 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8872 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8873 /* continue with next insn after call */
8874 return 0;
8875 }
8876
f4d7e40a
AS
8877 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8878 if (!callee)
8879 return -ENOMEM;
8880 state->frame[state->curframe + 1] = callee;
8881
8882 /* callee cannot access r0, r6 - r9 for reading and has to write
8883 * into its own stack before reading from it.
8884 * callee can read/write into caller's stack
8885 */
8886 init_func_state(env, callee,
8887 /* remember the callsite, it will be used by bpf_exit */
8888 *insn_idx /* callsite */,
8889 state->curframe + 1 /* frameno within this callchain */,
f910cefa 8890 subprog /* subprog number within this prog */);
f4d7e40a 8891
fd978bf7 8892 /* Transfer references to the callee */
c69431aa 8893 err = copy_reference_state(callee, caller);
fd978bf7 8894 if (err)
eb86559a 8895 goto err_out;
fd978bf7 8896
14351375
YS
8897 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8898 if (err)
eb86559a 8899 goto err_out;
f4d7e40a 8900
51c39bb1 8901 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
8902
8903 /* only increment it after check_reg_arg() finished */
8904 state->curframe++;
8905
8906 /* and go analyze first insn of the callee */
14351375 8907 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 8908
06ee7115 8909 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 8910 verbose(env, "caller:\n");
0f55f9ed 8911 print_verifier_state(env, caller, true);
f4d7e40a 8912 verbose(env, "callee:\n");
0f55f9ed 8913 print_verifier_state(env, callee, true);
f4d7e40a
AS
8914 }
8915 return 0;
eb86559a
WY
8916
8917err_out:
8918 free_func_state(callee);
8919 state->frame[state->curframe + 1] = NULL;
8920 return err;
f4d7e40a
AS
8921}
8922
314ee05e
YS
8923int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8924 struct bpf_func_state *caller,
8925 struct bpf_func_state *callee)
8926{
8927 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8928 * void *callback_ctx, u64 flags);
8929 * callback_fn(struct bpf_map *map, void *key, void *value,
8930 * void *callback_ctx);
8931 */
8932 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8933
8934 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8935 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8936 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8937
8938 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8939 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8940 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8941
8942 /* pointer to stack or null */
8943 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8944
8945 /* unused */
8946 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8947 return 0;
8948}
8949
14351375
YS
8950static int set_callee_state(struct bpf_verifier_env *env,
8951 struct bpf_func_state *caller,
8952 struct bpf_func_state *callee, int insn_idx)
8953{
8954 int i;
8955
8956 /* copy r1 - r5 args that callee can access. The copy includes parent
8957 * pointers, which connects us up to the liveness chain
8958 */
8959 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8960 callee->regs[i] = caller->regs[i];
8961 return 0;
8962}
8963
8964static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8965 int *insn_idx)
8966{
8967 int subprog, target_insn;
8968
8969 target_insn = *insn_idx + insn->imm + 1;
8970 subprog = find_subprog(env, target_insn);
8971 if (subprog < 0) {
8972 verbose(env, "verifier bug. No program starts at insn %d\n",
8973 target_insn);
8974 return -EFAULT;
8975 }
8976
8977 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8978}
8979
69c087ba
YS
8980static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8981 struct bpf_func_state *caller,
8982 struct bpf_func_state *callee,
8983 int insn_idx)
8984{
8985 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8986 struct bpf_map *map;
8987 int err;
8988
8989 if (bpf_map_ptr_poisoned(insn_aux)) {
8990 verbose(env, "tail_call abusing map_ptr\n");
8991 return -EINVAL;
8992 }
8993
8994 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8995 if (!map->ops->map_set_for_each_callback_args ||
8996 !map->ops->map_for_each_callback) {
8997 verbose(env, "callback function not allowed for map\n");
8998 return -ENOTSUPP;
8999 }
9000
9001 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9002 if (err)
9003 return err;
9004
9005 callee->in_callback_fn = true;
1bfe26fb 9006 callee->callback_ret_range = tnum_range(0, 1);
69c087ba
YS
9007 return 0;
9008}
9009
e6f2dd0f
JK
9010static int set_loop_callback_state(struct bpf_verifier_env *env,
9011 struct bpf_func_state *caller,
9012 struct bpf_func_state *callee,
9013 int insn_idx)
9014{
9015 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9016 * u64 flags);
9017 * callback_fn(u32 index, void *callback_ctx);
9018 */
9019 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9020 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9021
9022 /* unused */
9023 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9024 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9025 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9026
9027 callee->in_callback_fn = true;
1bfe26fb 9028 callee->callback_ret_range = tnum_range(0, 1);
e6f2dd0f
JK
9029 return 0;
9030}
9031
b00628b1
AS
9032static int set_timer_callback_state(struct bpf_verifier_env *env,
9033 struct bpf_func_state *caller,
9034 struct bpf_func_state *callee,
9035 int insn_idx)
9036{
9037 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9038
9039 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9040 * callback_fn(struct bpf_map *map, void *key, void *value);
9041 */
9042 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9043 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9044 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9045
9046 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9047 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9048 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9049
9050 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9051 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9052 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9053
9054 /* unused */
9055 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9056 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
bfc6bb74 9057 callee->in_async_callback_fn = true;
1bfe26fb 9058 callee->callback_ret_range = tnum_range(0, 1);
b00628b1
AS
9059 return 0;
9060}
9061
7c7e3d31
SL
9062static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9063 struct bpf_func_state *caller,
9064 struct bpf_func_state *callee,
9065 int insn_idx)
9066{
9067 /* bpf_find_vma(struct task_struct *task, u64 addr,
9068 * void *callback_fn, void *callback_ctx, u64 flags)
9069 * (callback_fn)(struct task_struct *task,
9070 * struct vm_area_struct *vma, void *callback_ctx);
9071 */
9072 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9073
9074 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9075 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9076 callee->regs[BPF_REG_2].btf = btf_vmlinux;
d19ddb47 9077 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7c7e3d31
SL
9078
9079 /* pointer to stack or null */
9080 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9081
9082 /* unused */
9083 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9084 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9085 callee->in_callback_fn = true;
1bfe26fb 9086 callee->callback_ret_range = tnum_range(0, 1);
7c7e3d31
SL
9087 return 0;
9088}
9089
20571567
DV
9090static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9091 struct bpf_func_state *caller,
9092 struct bpf_func_state *callee,
9093 int insn_idx)
9094{
9095 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9096 * callback_ctx, u64 flags);
27060531 9097 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
20571567
DV
9098 */
9099 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
f8064ab9 9100 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
20571567
DV
9101 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9102
9103 /* unused */
9104 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9105 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9106 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9107
9108 callee->in_callback_fn = true;
c92a7a52 9109 callee->callback_ret_range = tnum_range(0, 1);
20571567
DV
9110 return 0;
9111}
9112
5d92ddc3
DM
9113static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9114 struct bpf_func_state *caller,
9115 struct bpf_func_state *callee,
9116 int insn_idx)
9117{
d2dcc67d 9118 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
5d92ddc3
DM
9119 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9120 *
d2dcc67d 9121 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
5d92ddc3
DM
9122 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9123 * by this point, so look at 'root'
9124 */
9125 struct btf_field *field;
9126
9127 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9128 BPF_RB_ROOT);
9129 if (!field || !field->graph_root.value_btf_id)
9130 return -EFAULT;
9131
9132 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9133 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9134 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9135 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9136
9137 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9138 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9139 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9140 callee->in_callback_fn = true;
9141 callee->callback_ret_range = tnum_range(0, 1);
9142 return 0;
9143}
9144
9145static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9146
9147/* Are we currently verifying the callback for a rbtree helper that must
9148 * be called with lock held? If so, no need to complain about unreleased
9149 * lock
9150 */
9151static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9152{
9153 struct bpf_verifier_state *state = env->cur_state;
9154 struct bpf_insn *insn = env->prog->insnsi;
9155 struct bpf_func_state *callee;
9156 int kfunc_btf_id;
9157
9158 if (!state->curframe)
9159 return false;
9160
9161 callee = state->frame[state->curframe];
9162
9163 if (!callee->in_callback_fn)
9164 return false;
9165
9166 kfunc_btf_id = insn[callee->callsite].imm;
9167 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9168}
9169
f4d7e40a
AS
9170static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9171{
9172 struct bpf_verifier_state *state = env->cur_state;
9173 struct bpf_func_state *caller, *callee;
9174 struct bpf_reg_state *r0;
fd978bf7 9175 int err;
f4d7e40a
AS
9176
9177 callee = state->frame[state->curframe];
9178 r0 = &callee->regs[BPF_REG_0];
9179 if (r0->type == PTR_TO_STACK) {
9180 /* technically it's ok to return caller's stack pointer
9181 * (or caller's caller's pointer) back to the caller,
9182 * since these pointers are valid. Only current stack
9183 * pointer will be invalid as soon as function exits,
9184 * but let's be conservative
9185 */
9186 verbose(env, "cannot return stack pointer to the caller\n");
9187 return -EINVAL;
9188 }
9189
eb86559a 9190 caller = state->frame[state->curframe - 1];
69c087ba
YS
9191 if (callee->in_callback_fn) {
9192 /* enforce R0 return value range [0, 1]. */
1bfe26fb 9193 struct tnum range = callee->callback_ret_range;
69c087ba
YS
9194
9195 if (r0->type != SCALAR_VALUE) {
9196 verbose(env, "R0 not a scalar value\n");
9197 return -EACCES;
9198 }
9199 if (!tnum_in(range, r0->var_off)) {
9200 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9201 return -EINVAL;
9202 }
9203 } else {
9204 /* return to the caller whatever r0 had in the callee */
9205 caller->regs[BPF_REG_0] = *r0;
9206 }
f4d7e40a 9207
9d9d00ac
KKD
9208 /* callback_fn frame should have released its own additions to parent's
9209 * reference state at this point, or check_reference_leak would
9210 * complain, hence it must be the same as the caller. There is no need
9211 * to copy it back.
9212 */
9213 if (!callee->in_callback_fn) {
9214 /* Transfer references to the caller */
9215 err = copy_reference_state(caller, callee);
9216 if (err)
9217 return err;
9218 }
fd978bf7 9219
f4d7e40a 9220 *insn_idx = callee->callsite + 1;
06ee7115 9221 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 9222 verbose(env, "returning from callee:\n");
0f55f9ed 9223 print_verifier_state(env, callee, true);
f4d7e40a 9224 verbose(env, "to caller at %d:\n", *insn_idx);
0f55f9ed 9225 print_verifier_state(env, caller, true);
f4d7e40a
AS
9226 }
9227 /* clear everything in the callee */
9228 free_func_state(callee);
eb86559a 9229 state->frame[state->curframe--] = NULL;
f4d7e40a
AS
9230 return 0;
9231}
9232
849fa506
YS
9233static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9234 int func_id,
9235 struct bpf_call_arg_meta *meta)
9236{
9237 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9238
f42bcd16 9239 if (ret_type != RET_INTEGER)
849fa506
YS
9240 return;
9241
f42bcd16
AN
9242 switch (func_id) {
9243 case BPF_FUNC_get_stack:
9244 case BPF_FUNC_get_task_stack:
9245 case BPF_FUNC_probe_read_str:
9246 case BPF_FUNC_probe_read_kernel_str:
9247 case BPF_FUNC_probe_read_user_str:
9248 ret_reg->smax_value = meta->msize_max_value;
9249 ret_reg->s32_max_value = meta->msize_max_value;
9250 ret_reg->smin_value = -MAX_ERRNO;
9251 ret_reg->s32_min_value = -MAX_ERRNO;
9252 reg_bounds_sync(ret_reg);
9253 break;
9254 case BPF_FUNC_get_smp_processor_id:
9255 ret_reg->umax_value = nr_cpu_ids - 1;
9256 ret_reg->u32_max_value = nr_cpu_ids - 1;
9257 ret_reg->smax_value = nr_cpu_ids - 1;
9258 ret_reg->s32_max_value = nr_cpu_ids - 1;
9259 ret_reg->umin_value = 0;
9260 ret_reg->u32_min_value = 0;
9261 ret_reg->smin_value = 0;
9262 ret_reg->s32_min_value = 0;
9263 reg_bounds_sync(ret_reg);
9264 break;
9265 }
849fa506
YS
9266}
9267
c93552c4
DB
9268static int
9269record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9270 int func_id, int insn_idx)
9271{
9272 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 9273 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
9274
9275 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
9276 func_id != BPF_FUNC_map_lookup_elem &&
9277 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
9278 func_id != BPF_FUNC_map_delete_elem &&
9279 func_id != BPF_FUNC_map_push_elem &&
9280 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 9281 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f 9282 func_id != BPF_FUNC_for_each_map_elem &&
07343110
FZ
9283 func_id != BPF_FUNC_redirect_map &&
9284 func_id != BPF_FUNC_map_lookup_percpu_elem)
c93552c4 9285 return 0;
09772d92 9286
591fe988 9287 if (map == NULL) {
c93552c4
DB
9288 verbose(env, "kernel subsystem misconfigured verifier\n");
9289 return -EINVAL;
9290 }
9291
591fe988
DB
9292 /* In case of read-only, some additional restrictions
9293 * need to be applied in order to prevent altering the
9294 * state of the map from program side.
9295 */
9296 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9297 (func_id == BPF_FUNC_map_delete_elem ||
9298 func_id == BPF_FUNC_map_update_elem ||
9299 func_id == BPF_FUNC_map_push_elem ||
9300 func_id == BPF_FUNC_map_pop_elem)) {
9301 verbose(env, "write into map forbidden\n");
9302 return -EACCES;
9303 }
9304
d2e4c1e6 9305 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 9306 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 9307 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 9308 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 9309 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 9310 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
9311 return 0;
9312}
9313
d2e4c1e6
DB
9314static int
9315record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9316 int func_id, int insn_idx)
9317{
9318 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9319 struct bpf_reg_state *regs = cur_regs(env), *reg;
9320 struct bpf_map *map = meta->map_ptr;
a657182a 9321 u64 val, max;
cc52d914 9322 int err;
d2e4c1e6
DB
9323
9324 if (func_id != BPF_FUNC_tail_call)
9325 return 0;
9326 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9327 verbose(env, "kernel subsystem misconfigured verifier\n");
9328 return -EINVAL;
9329 }
9330
d2e4c1e6 9331 reg = &regs[BPF_REG_3];
a657182a
DB
9332 val = reg->var_off.value;
9333 max = map->max_entries;
d2e4c1e6 9334
a657182a 9335 if (!(register_is_const(reg) && val < max)) {
d2e4c1e6
DB
9336 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9337 return 0;
9338 }
9339
cc52d914
DB
9340 err = mark_chain_precision(env, BPF_REG_3);
9341 if (err)
9342 return err;
d2e4c1e6
DB
9343 if (bpf_map_key_unseen(aux))
9344 bpf_map_key_store(aux, val);
9345 else if (!bpf_map_key_poisoned(aux) &&
9346 bpf_map_key_immediate(aux) != val)
9347 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9348 return 0;
9349}
9350
fd978bf7
JS
9351static int check_reference_leak(struct bpf_verifier_env *env)
9352{
9353 struct bpf_func_state *state = cur_func(env);
9d9d00ac 9354 bool refs_lingering = false;
fd978bf7
JS
9355 int i;
9356
9d9d00ac
KKD
9357 if (state->frameno && !state->in_callback_fn)
9358 return 0;
9359
fd978bf7 9360 for (i = 0; i < state->acquired_refs; i++) {
9d9d00ac
KKD
9361 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9362 continue;
fd978bf7
JS
9363 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9364 state->refs[i].id, state->refs[i].insn_idx);
9d9d00ac 9365 refs_lingering = true;
fd978bf7 9366 }
9d9d00ac 9367 return refs_lingering ? -EINVAL : 0;
fd978bf7
JS
9368}
9369
7b15523a
FR
9370static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9371 struct bpf_reg_state *regs)
9372{
9373 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9374 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9375 struct bpf_map *fmt_map = fmt_reg->map_ptr;
78aa1cc9 9376 struct bpf_bprintf_data data = {};
7b15523a
FR
9377 int err, fmt_map_off, num_args;
9378 u64 fmt_addr;
9379 char *fmt;
9380
9381 /* data must be an array of u64 */
9382 if (data_len_reg->var_off.value % 8)
9383 return -EINVAL;
9384 num_args = data_len_reg->var_off.value / 8;
9385
9386 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9387 * and map_direct_value_addr is set.
9388 */
9389 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9390 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9391 fmt_map_off);
8e8ee109
FR
9392 if (err) {
9393 verbose(env, "verifier bug\n");
9394 return -EFAULT;
9395 }
7b15523a
FR
9396 fmt = (char *)(long)fmt_addr + fmt_map_off;
9397
9398 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9399 * can focus on validating the format specifiers.
9400 */
78aa1cc9 9401 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7b15523a
FR
9402 if (err < 0)
9403 verbose(env, "Invalid format string\n");
9404
9405 return err;
9406}
9407
9b99edca
JO
9408static int check_get_func_ip(struct bpf_verifier_env *env)
9409{
9b99edca
JO
9410 enum bpf_prog_type type = resolve_prog_type(env->prog);
9411 int func_id = BPF_FUNC_get_func_ip;
9412
9413 if (type == BPF_PROG_TYPE_TRACING) {
f92c1e18 9414 if (!bpf_prog_has_trampoline(env->prog)) {
9b99edca
JO
9415 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9416 func_id_name(func_id), func_id);
9417 return -ENOTSUPP;
9418 }
9419 return 0;
9ffd9f3f
JO
9420 } else if (type == BPF_PROG_TYPE_KPROBE) {
9421 return 0;
9b99edca
JO
9422 }
9423
9424 verbose(env, "func %s#%d not supported for program type %d\n",
9425 func_id_name(func_id), func_id, type);
9426 return -ENOTSUPP;
9427}
9428
1ade2371
EZ
9429static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9430{
9431 return &env->insn_aux_data[env->insn_idx];
9432}
9433
9434static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9435{
9436 struct bpf_reg_state *regs = cur_regs(env);
9437 struct bpf_reg_state *reg = &regs[BPF_REG_4];
9438 bool reg_is_null = register_is_null(reg);
9439
9440 if (reg_is_null)
9441 mark_chain_precision(env, BPF_REG_4);
9442
9443 return reg_is_null;
9444}
9445
9446static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9447{
9448 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9449
9450 if (!state->initialized) {
9451 state->initialized = 1;
9452 state->fit_for_inline = loop_flag_is_zero(env);
9453 state->callback_subprogno = subprogno;
9454 return;
9455 }
9456
9457 if (!state->fit_for_inline)
9458 return;
9459
9460 state->fit_for_inline = (loop_flag_is_zero(env) &&
9461 state->callback_subprogno == subprogno);
9462}
9463
69c087ba
YS
9464static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9465 int *insn_idx_p)
17a52670 9466{
aef9d4a3 9467 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17a52670 9468 const struct bpf_func_proto *fn = NULL;
3c480732 9469 enum bpf_return_type ret_type;
c25b2ae1 9470 enum bpf_type_flag ret_flag;
638f5b90 9471 struct bpf_reg_state *regs;
33ff9823 9472 struct bpf_call_arg_meta meta;
69c087ba 9473 int insn_idx = *insn_idx_p;
969bf05e 9474 bool changes_data;
69c087ba 9475 int i, err, func_id;
17a52670
AS
9476
9477 /* find function prototype */
69c087ba 9478 func_id = insn->imm;
17a52670 9479 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
9480 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9481 func_id);
17a52670
AS
9482 return -EINVAL;
9483 }
9484
00176a34 9485 if (env->ops->get_func_proto)
5e43f899 9486 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 9487 if (!fn) {
61bd5218
JK
9488 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9489 func_id);
17a52670
AS
9490 return -EINVAL;
9491 }
9492
9493 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 9494 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 9495 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
9496 return -EINVAL;
9497 }
9498
eae2e83e
JO
9499 if (fn->allowed && !fn->allowed(env->prog)) {
9500 verbose(env, "helper call is not allowed in probe\n");
9501 return -EINVAL;
9502 }
9503
01685c5b
YS
9504 if (!env->prog->aux->sleepable && fn->might_sleep) {
9505 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9506 return -EINVAL;
9507 }
9508
04514d13 9509 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 9510 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
9511 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9512 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9513 func_id_name(func_id), func_id);
9514 return -EINVAL;
9515 }
969bf05e 9516
33ff9823 9517 memset(&meta, 0, sizeof(meta));
36bbef52 9518 meta.pkt_access = fn->pkt_access;
33ff9823 9519
0c9a7a7e 9520 err = check_func_proto(fn, func_id);
435faee1 9521 if (err) {
61bd5218 9522 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 9523 func_id_name(func_id), func_id);
435faee1
DB
9524 return err;
9525 }
9526
9bb00b28
YS
9527 if (env->cur_state->active_rcu_lock) {
9528 if (fn->might_sleep) {
9529 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9530 func_id_name(func_id), func_id);
9531 return -EINVAL;
9532 }
9533
9534 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9535 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9536 }
9537
d83525ca 9538 meta.func_id = func_id;
17a52670 9539 /* check args */
523a4cf4 9540 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
1d18feb2 9541 err = check_func_arg(env, i, &meta, fn, insn_idx);
a7658e1a
AS
9542 if (err)
9543 return err;
9544 }
17a52670 9545
c93552c4
DB
9546 err = record_func_map(env, &meta, func_id, insn_idx);
9547 if (err)
9548 return err;
9549
d2e4c1e6
DB
9550 err = record_func_key(env, &meta, func_id, insn_idx);
9551 if (err)
9552 return err;
9553
435faee1
DB
9554 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9555 * is inferred from register state.
9556 */
9557 for (i = 0; i < meta.access_size; i++) {
ca369602 9558 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
1f9a1ea8 9559 BPF_WRITE, -1, false, false);
435faee1
DB
9560 if (err)
9561 return err;
9562 }
9563
8f14852e
KKD
9564 regs = cur_regs(env);
9565
9566 if (meta.release_regno) {
9567 err = -EINVAL;
27060531
KKD
9568 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9569 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9570 * is safe to do directly.
9571 */
9572 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9573 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9574 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9575 return -EFAULT;
9576 }
97e03f52 9577 err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
27060531 9578 } else if (meta.ref_obj_id) {
8f14852e 9579 err = release_reference(env, meta.ref_obj_id);
27060531
KKD
9580 } else if (register_is_null(&regs[meta.release_regno])) {
9581 /* meta.ref_obj_id can only be 0 if register that is meant to be
9582 * released is NULL, which must be > R0.
9583 */
8f14852e 9584 err = 0;
27060531 9585 }
46f8bc92
MKL
9586 if (err) {
9587 verbose(env, "func %s#%d reference has not been acquired before\n",
9588 func_id_name(func_id), func_id);
fd978bf7 9589 return err;
46f8bc92 9590 }
fd978bf7
JS
9591 }
9592
e6f2dd0f
JK
9593 switch (func_id) {
9594 case BPF_FUNC_tail_call:
9595 err = check_reference_leak(env);
9596 if (err) {
9597 verbose(env, "tail_call would lead to reference leak\n");
9598 return err;
9599 }
9600 break;
9601 case BPF_FUNC_get_local_storage:
9602 /* check that flags argument in get_local_storage(map, flags) is 0,
9603 * this is required because get_local_storage() can't return an error.
9604 */
9605 if (!register_is_null(&regs[BPF_REG_2])) {
9606 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9607 return -EINVAL;
9608 }
9609 break;
9610 case BPF_FUNC_for_each_map_elem:
69c087ba
YS
9611 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9612 set_map_elem_callback_state);
e6f2dd0f
JK
9613 break;
9614 case BPF_FUNC_timer_set_callback:
b00628b1
AS
9615 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9616 set_timer_callback_state);
e6f2dd0f
JK
9617 break;
9618 case BPF_FUNC_find_vma:
7c7e3d31
SL
9619 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9620 set_find_vma_callback_state);
e6f2dd0f
JK
9621 break;
9622 case BPF_FUNC_snprintf:
7b15523a 9623 err = check_bpf_snprintf_call(env, regs);
e6f2dd0f
JK
9624 break;
9625 case BPF_FUNC_loop:
1ade2371 9626 update_loop_inline_state(env, meta.subprogno);
e6f2dd0f
JK
9627 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9628 set_loop_callback_state);
9629 break;
263ae152
JK
9630 case BPF_FUNC_dynptr_from_mem:
9631 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9632 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9633 reg_type_str(env, regs[BPF_REG_1].type));
9634 return -EACCES;
9635 }
69fd337a
SF
9636 break;
9637 case BPF_FUNC_set_retval:
aef9d4a3
SF
9638 if (prog_type == BPF_PROG_TYPE_LSM &&
9639 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
69fd337a
SF
9640 if (!env->prog->aux->attach_func_proto->type) {
9641 /* Make sure programs that attach to void
9642 * hooks don't try to modify return value.
9643 */
9644 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9645 return -EINVAL;
9646 }
9647 }
9648 break;
88374342 9649 case BPF_FUNC_dynptr_data:
485ec51e
JK
9650 {
9651 struct bpf_reg_state *reg;
9652 int id, ref_obj_id;
20571567 9653
485ec51e
JK
9654 reg = get_dynptr_arg_reg(env, fn, regs);
9655 if (!reg)
9656 return -EFAULT;
f8064ab9 9657
f8064ab9 9658
485ec51e
JK
9659 if (meta.dynptr_id) {
9660 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9661 return -EFAULT;
88374342 9662 }
485ec51e
JK
9663 if (meta.ref_obj_id) {
9664 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
88374342
JK
9665 return -EFAULT;
9666 }
485ec51e
JK
9667
9668 id = dynptr_id(env, reg);
9669 if (id < 0) {
9670 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9671 return id;
9672 }
9673
9674 ref_obj_id = dynptr_ref_obj_id(env, reg);
9675 if (ref_obj_id < 0) {
9676 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9677 return ref_obj_id;
9678 }
9679
9680 meta.dynptr_id = id;
9681 meta.ref_obj_id = ref_obj_id;
9682
88374342 9683 break;
485ec51e 9684 }
b5964b96
JK
9685 case BPF_FUNC_dynptr_write:
9686 {
9687 enum bpf_dynptr_type dynptr_type;
9688 struct bpf_reg_state *reg;
9689
9690 reg = get_dynptr_arg_reg(env, fn, regs);
9691 if (!reg)
9692 return -EFAULT;
9693
9694 dynptr_type = dynptr_get_type(env, reg);
9695 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9696 return -EFAULT;
9697
9698 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9699 /* this will trigger clear_all_pkt_pointers(), which will
9700 * invalidate all dynptr slices associated with the skb
9701 */
9702 changes_data = true;
9703
9704 break;
9705 }
20571567
DV
9706 case BPF_FUNC_user_ringbuf_drain:
9707 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9708 set_user_ringbuf_callback_state);
9709 break;
7b15523a
FR
9710 }
9711
e6f2dd0f
JK
9712 if (err)
9713 return err;
9714
17a52670 9715 /* reset caller saved regs */
dc503a8a 9716 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 9717 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
9718 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9719 }
17a52670 9720
5327ed3d
JW
9721 /* helper call returns 64-bit value. */
9722 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9723
dc503a8a 9724 /* update return register (already marked as written above) */
3c480732 9725 ret_type = fn->ret_type;
0c9a7a7e
JK
9726 ret_flag = type_flag(ret_type);
9727
9728 switch (base_type(ret_type)) {
9729 case RET_INTEGER:
f1174f77 9730 /* sets type to SCALAR_VALUE */
61bd5218 9731 mark_reg_unknown(env, regs, BPF_REG_0);
0c9a7a7e
JK
9732 break;
9733 case RET_VOID:
17a52670 9734 regs[BPF_REG_0].type = NOT_INIT;
0c9a7a7e
JK
9735 break;
9736 case RET_PTR_TO_MAP_VALUE:
f1174f77 9737 /* There is no offset yet applied, variable or fixed */
61bd5218 9738 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
9739 /* remember map_ptr, so that check_map_access()
9740 * can check 'value_size' boundary of memory access
9741 * to map element returned from bpf_map_lookup_elem()
9742 */
33ff9823 9743 if (meta.map_ptr == NULL) {
61bd5218
JK
9744 verbose(env,
9745 "kernel subsystem misconfigured verifier\n");
17a52670
AS
9746 return -EINVAL;
9747 }
33ff9823 9748 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3e8ce298 9749 regs[BPF_REG_0].map_uid = meta.map_uid;
c25b2ae1
HL
9750 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9751 if (!type_may_be_null(ret_type) &&
db559117 9752 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
c25b2ae1 9753 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301 9754 }
0c9a7a7e
JK
9755 break;
9756 case RET_PTR_TO_SOCKET:
c64b7983 9757 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9758 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
0c9a7a7e
JK
9759 break;
9760 case RET_PTR_TO_SOCK_COMMON:
85a51f8c 9761 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9762 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
0c9a7a7e
JK
9763 break;
9764 case RET_PTR_TO_TCP_SOCK:
655a51e5 9765 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9766 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
0c9a7a7e 9767 break;
2de2669b 9768 case RET_PTR_TO_MEM:
457f4436 9769 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9770 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
457f4436 9771 regs[BPF_REG_0].mem_size = meta.mem_size;
0c9a7a7e
JK
9772 break;
9773 case RET_PTR_TO_MEM_OR_BTF_ID:
9774 {
eaa6bcb7
HL
9775 const struct btf_type *t;
9776
9777 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 9778 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
9779 if (!btf_type_is_struct(t)) {
9780 u32 tsize;
9781 const struct btf_type *ret;
9782 const char *tname;
9783
9784 /* resolve the type size of ksym. */
22dc4a0f 9785 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 9786 if (IS_ERR(ret)) {
22dc4a0f 9787 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
9788 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9789 tname, PTR_ERR(ret));
9790 return -EINVAL;
9791 }
c25b2ae1 9792 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
eaa6bcb7
HL
9793 regs[BPF_REG_0].mem_size = tsize;
9794 } else {
34d3a78c
HL
9795 /* MEM_RDONLY may be carried from ret_flag, but it
9796 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9797 * it will confuse the check of PTR_TO_BTF_ID in
9798 * check_mem_access().
9799 */
9800 ret_flag &= ~MEM_RDONLY;
9801
c25b2ae1 9802 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
22dc4a0f 9803 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
9804 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9805 }
0c9a7a7e
JK
9806 break;
9807 }
9808 case RET_PTR_TO_BTF_ID:
9809 {
c0a5a21c 9810 struct btf *ret_btf;
af7ec138
YS
9811 int ret_btf_id;
9812
9813 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 9814 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
c0a5a21c 9815 if (func_id == BPF_FUNC_kptr_xchg) {
aa3496ac
KKD
9816 ret_btf = meta.kptr_field->kptr.btf;
9817 ret_btf_id = meta.kptr_field->kptr.btf_id;
738c96d5
DM
9818 if (!btf_is_kernel(ret_btf))
9819 regs[BPF_REG_0].type |= MEM_ALLOC;
c0a5a21c 9820 } else {
47e34cb7
DM
9821 if (fn->ret_btf_id == BPF_PTR_POISON) {
9822 verbose(env, "verifier internal error:");
9823 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9824 func_id_name(func_id));
9825 return -EINVAL;
9826 }
c0a5a21c
KKD
9827 ret_btf = btf_vmlinux;
9828 ret_btf_id = *fn->ret_btf_id;
9829 }
af7ec138 9830 if (ret_btf_id == 0) {
3c480732
HL
9831 verbose(env, "invalid return type %u of func %s#%d\n",
9832 base_type(ret_type), func_id_name(func_id),
9833 func_id);
af7ec138
YS
9834 return -EINVAL;
9835 }
c0a5a21c 9836 regs[BPF_REG_0].btf = ret_btf;
af7ec138 9837 regs[BPF_REG_0].btf_id = ret_btf_id;
0c9a7a7e
JK
9838 break;
9839 }
9840 default:
3c480732
HL
9841 verbose(env, "unknown return type %u of func %s#%d\n",
9842 base_type(ret_type), func_id_name(func_id), func_id);
17a52670
AS
9843 return -EINVAL;
9844 }
04fd61ab 9845
c25b2ae1 9846 if (type_may_be_null(regs[BPF_REG_0].type))
93c230e3
MKL
9847 regs[BPF_REG_0].id = ++env->id_gen;
9848
b2d8ef19
DM
9849 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9850 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9851 func_id_name(func_id), func_id);
9852 return -EFAULT;
9853 }
9854
f8064ab9
KKD
9855 if (is_dynptr_ref_function(func_id))
9856 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9857
88374342 9858 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
1b986589
MKL
9859 /* For release_reference() */
9860 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 9861 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
9862 int id = acquire_reference_state(env, insn_idx);
9863
9864 if (id < 0)
9865 return id;
9866 /* For mark_ptr_or_null_reg() */
9867 regs[BPF_REG_0].id = id;
9868 /* For release_reference() */
9869 regs[BPF_REG_0].ref_obj_id = id;
9870 }
1b986589 9871
849fa506
YS
9872 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9873
61bd5218 9874 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
9875 if (err)
9876 return err;
04fd61ab 9877
fa28dcb8
SL
9878 if ((func_id == BPF_FUNC_get_stack ||
9879 func_id == BPF_FUNC_get_task_stack) &&
9880 !env->prog->has_callchain_buf) {
c195651e
YS
9881 const char *err_str;
9882
9883#ifdef CONFIG_PERF_EVENTS
9884 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9885 err_str = "cannot get callchain buffer for func %s#%d\n";
9886#else
9887 err = -ENOTSUPP;
9888 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9889#endif
9890 if (err) {
9891 verbose(env, err_str, func_id_name(func_id), func_id);
9892 return err;
9893 }
9894
9895 env->prog->has_callchain_buf = true;
9896 }
9897
5d99cb2c
SL
9898 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9899 env->prog->call_get_stack = true;
9900
9b99edca
JO
9901 if (func_id == BPF_FUNC_get_func_ip) {
9902 if (check_get_func_ip(env))
9903 return -ENOTSUPP;
9904 env->prog->call_get_func_ip = true;
9905 }
9906
969bf05e
AS
9907 if (changes_data)
9908 clear_all_pkt_pointers(env);
9909 return 0;
9910}
9911
e6ac2450
MKL
9912/* mark_btf_func_reg_size() is used when the reg size is determined by
9913 * the BTF func_proto's return value size and argument.
9914 */
9915static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9916 size_t reg_size)
9917{
9918 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9919
9920 if (regno == BPF_REG_0) {
9921 /* Function return value */
9922 reg->live |= REG_LIVE_WRITTEN;
9923 reg->subreg_def = reg_size == sizeof(u64) ?
9924 DEF_NOT_SUBREG : env->insn_idx + 1;
9925 } else {
9926 /* Function argument */
9927 if (reg_size == sizeof(u64)) {
9928 mark_insn_zext(env, reg);
9929 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9930 } else {
9931 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9932 }
9933 }
9934}
9935
00b85860
KKD
9936static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9937{
9938 return meta->kfunc_flags & KF_ACQUIRE;
9939}
a5d82727 9940
00b85860
KKD
9941static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9942{
9943 return meta->kfunc_flags & KF_RELEASE;
9944}
e6ac2450 9945
00b85860
KKD
9946static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9947{
6c831c46 9948 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
00b85860 9949}
4dd48c6f 9950
00b85860
KKD
9951static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9952{
9953 return meta->kfunc_flags & KF_SLEEPABLE;
9954}
5c073f26 9955
00b85860
KKD
9956static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9957{
9958 return meta->kfunc_flags & KF_DESTRUCTIVE;
9959}
eb1f7f71 9960
fca1aa75
YS
9961static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9962{
9963 return meta->kfunc_flags & KF_RCU;
9964}
9965
a50388db
KKD
9966static bool __kfunc_param_match_suffix(const struct btf *btf,
9967 const struct btf_param *arg,
9968 const char *suffix)
00b85860 9969{
a50388db 9970 int suffix_len = strlen(suffix), len;
00b85860 9971 const char *param_name;
e6ac2450 9972
00b85860
KKD
9973 /* In the future, this can be ported to use BTF tagging */
9974 param_name = btf_name_by_offset(btf, arg->name_off);
9975 if (str_is_empty(param_name))
9976 return false;
9977 len = strlen(param_name);
a50388db 9978 if (len < suffix_len)
00b85860 9979 return false;
a50388db
KKD
9980 param_name += len - suffix_len;
9981 return !strncmp(param_name, suffix, suffix_len);
9982}
5c073f26 9983
a50388db
KKD
9984static bool is_kfunc_arg_mem_size(const struct btf *btf,
9985 const struct btf_param *arg,
9986 const struct bpf_reg_state *reg)
9987{
9988 const struct btf_type *t;
5c073f26 9989
a50388db
KKD
9990 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9991 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
00b85860 9992 return false;
eb1f7f71 9993
a50388db
KKD
9994 return __kfunc_param_match_suffix(btf, arg, "__sz");
9995}
eb1f7f71 9996
66e3a13e
JK
9997static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9998 const struct btf_param *arg,
9999 const struct bpf_reg_state *reg)
10000{
10001 const struct btf_type *t;
10002
10003 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10004 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10005 return false;
10006
10007 return __kfunc_param_match_suffix(btf, arg, "__szk");
10008}
10009
3bda08b6
DR
10010static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10011{
10012 return __kfunc_param_match_suffix(btf, arg, "__opt");
10013}
10014
a50388db
KKD
10015static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10016{
10017 return __kfunc_param_match_suffix(btf, arg, "__k");
00b85860 10018}
eb1f7f71 10019
958cf2e2
KKD
10020static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10021{
10022 return __kfunc_param_match_suffix(btf, arg, "__ign");
10023}
5c073f26 10024
ac9f0605
KKD
10025static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10026{
10027 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10028}
e6ac2450 10029
d96d937d
JK
10030static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10031{
10032 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10033}
10034
7c50b1cb
DM
10035static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10036{
10037 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10038}
10039
00b85860
KKD
10040static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10041 const struct btf_param *arg,
10042 const char *name)
10043{
10044 int len, target_len = strlen(name);
10045 const char *param_name;
e6ac2450 10046
00b85860
KKD
10047 param_name = btf_name_by_offset(btf, arg->name_off);
10048 if (str_is_empty(param_name))
10049 return false;
10050 len = strlen(param_name);
10051 if (len != target_len)
10052 return false;
10053 if (strcmp(param_name, name))
10054 return false;
e6ac2450 10055
00b85860 10056 return true;
e6ac2450
MKL
10057}
10058
00b85860
KKD
10059enum {
10060 KF_ARG_DYNPTR_ID,
8cab76ec
KKD
10061 KF_ARG_LIST_HEAD_ID,
10062 KF_ARG_LIST_NODE_ID,
cd6791b4
DM
10063 KF_ARG_RB_ROOT_ID,
10064 KF_ARG_RB_NODE_ID,
00b85860 10065};
b03c9f9f 10066
00b85860
KKD
10067BTF_ID_LIST(kf_arg_btf_ids)
10068BTF_ID(struct, bpf_dynptr_kern)
8cab76ec
KKD
10069BTF_ID(struct, bpf_list_head)
10070BTF_ID(struct, bpf_list_node)
bd1279ae
DM
10071BTF_ID(struct, bpf_rb_root)
10072BTF_ID(struct, bpf_rb_node)
b03c9f9f 10073
8cab76ec
KKD
10074static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10075 const struct btf_param *arg, int type)
3f50f132 10076{
00b85860
KKD
10077 const struct btf_type *t;
10078 u32 res_id;
3f50f132 10079
00b85860
KKD
10080 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10081 if (!t)
10082 return false;
10083 if (!btf_type_is_ptr(t))
10084 return false;
10085 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10086 if (!t)
10087 return false;
8cab76ec 10088 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
3f50f132
JF
10089}
10090
8cab76ec 10091static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
b03c9f9f 10092{
8cab76ec 10093 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
969bf05e
AS
10094}
10095
8cab76ec 10096static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
3f50f132 10097{
8cab76ec 10098 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
3f50f132
JF
10099}
10100
8cab76ec 10101static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
bb7f0f98 10102{
8cab76ec 10103 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
00b85860
KKD
10104}
10105
cd6791b4
DM
10106static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10107{
10108 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10109}
10110
10111static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10112{
10113 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10114}
10115
5d92ddc3
DM
10116static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10117 const struct btf_param *arg)
10118{
10119 const struct btf_type *t;
10120
10121 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10122 if (!t)
10123 return false;
10124
10125 return true;
10126}
10127
00b85860
KKD
10128/* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10129static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10130 const struct btf *btf,
10131 const struct btf_type *t, int rec)
10132{
10133 const struct btf_type *member_type;
10134 const struct btf_member *member;
10135 u32 i;
10136
10137 if (!btf_type_is_struct(t))
10138 return false;
10139
10140 for_each_member(i, t, member) {
10141 const struct btf_array *array;
10142
10143 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10144 if (btf_type_is_struct(member_type)) {
10145 if (rec >= 3) {
10146 verbose(env, "max struct nesting depth exceeded\n");
10147 return false;
10148 }
10149 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10150 return false;
10151 continue;
10152 }
10153 if (btf_type_is_array(member_type)) {
10154 array = btf_array(member_type);
10155 if (!array->nelems)
10156 return false;
10157 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10158 if (!btf_type_is_scalar(member_type))
10159 return false;
10160 continue;
10161 }
10162 if (!btf_type_is_scalar(member_type))
10163 return false;
10164 }
10165 return true;
10166}
10167
00b85860
KKD
10168enum kfunc_ptr_arg_type {
10169 KF_ARG_PTR_TO_CTX,
7c50b1cb
DM
10170 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10171 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
00b85860 10172 KF_ARG_PTR_TO_DYNPTR,
06accc87 10173 KF_ARG_PTR_TO_ITER,
8cab76ec
KKD
10174 KF_ARG_PTR_TO_LIST_HEAD,
10175 KF_ARG_PTR_TO_LIST_NODE,
7c50b1cb 10176 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
00b85860 10177 KF_ARG_PTR_TO_MEM,
7c50b1cb 10178 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
5d92ddc3 10179 KF_ARG_PTR_TO_CALLBACK,
cd6791b4
DM
10180 KF_ARG_PTR_TO_RB_ROOT,
10181 KF_ARG_PTR_TO_RB_NODE,
00b85860
KKD
10182};
10183
ac9f0605
KKD
10184enum special_kfunc_type {
10185 KF_bpf_obj_new_impl,
10186 KF_bpf_obj_drop_impl,
7c50b1cb 10187 KF_bpf_refcount_acquire_impl,
d2dcc67d
DM
10188 KF_bpf_list_push_front_impl,
10189 KF_bpf_list_push_back_impl,
8cab76ec
KKD
10190 KF_bpf_list_pop_front,
10191 KF_bpf_list_pop_back,
fd264ca0 10192 KF_bpf_cast_to_kern_ctx,
a35b9af4 10193 KF_bpf_rdonly_cast,
9bb00b28
YS
10194 KF_bpf_rcu_read_lock,
10195 KF_bpf_rcu_read_unlock,
bd1279ae 10196 KF_bpf_rbtree_remove,
d2dcc67d 10197 KF_bpf_rbtree_add_impl,
bd1279ae 10198 KF_bpf_rbtree_first,
b5964b96 10199 KF_bpf_dynptr_from_skb,
05421aec 10200 KF_bpf_dynptr_from_xdp,
66e3a13e
JK
10201 KF_bpf_dynptr_slice,
10202 KF_bpf_dynptr_slice_rdwr,
361f129f 10203 KF_bpf_dynptr_clone,
ac9f0605
KKD
10204};
10205
10206BTF_SET_START(special_kfunc_set)
10207BTF_ID(func, bpf_obj_new_impl)
10208BTF_ID(func, bpf_obj_drop_impl)
7c50b1cb 10209BTF_ID(func, bpf_refcount_acquire_impl)
d2dcc67d
DM
10210BTF_ID(func, bpf_list_push_front_impl)
10211BTF_ID(func, bpf_list_push_back_impl)
8cab76ec
KKD
10212BTF_ID(func, bpf_list_pop_front)
10213BTF_ID(func, bpf_list_pop_back)
fd264ca0 10214BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 10215BTF_ID(func, bpf_rdonly_cast)
bd1279ae 10216BTF_ID(func, bpf_rbtree_remove)
d2dcc67d 10217BTF_ID(func, bpf_rbtree_add_impl)
bd1279ae 10218BTF_ID(func, bpf_rbtree_first)
b5964b96 10219BTF_ID(func, bpf_dynptr_from_skb)
05421aec 10220BTF_ID(func, bpf_dynptr_from_xdp)
66e3a13e
JK
10221BTF_ID(func, bpf_dynptr_slice)
10222BTF_ID(func, bpf_dynptr_slice_rdwr)
361f129f 10223BTF_ID(func, bpf_dynptr_clone)
ac9f0605
KKD
10224BTF_SET_END(special_kfunc_set)
10225
10226BTF_ID_LIST(special_kfunc_list)
10227BTF_ID(func, bpf_obj_new_impl)
10228BTF_ID(func, bpf_obj_drop_impl)
7c50b1cb 10229BTF_ID(func, bpf_refcount_acquire_impl)
d2dcc67d
DM
10230BTF_ID(func, bpf_list_push_front_impl)
10231BTF_ID(func, bpf_list_push_back_impl)
8cab76ec
KKD
10232BTF_ID(func, bpf_list_pop_front)
10233BTF_ID(func, bpf_list_pop_back)
fd264ca0 10234BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 10235BTF_ID(func, bpf_rdonly_cast)
9bb00b28
YS
10236BTF_ID(func, bpf_rcu_read_lock)
10237BTF_ID(func, bpf_rcu_read_unlock)
bd1279ae 10238BTF_ID(func, bpf_rbtree_remove)
d2dcc67d 10239BTF_ID(func, bpf_rbtree_add_impl)
bd1279ae 10240BTF_ID(func, bpf_rbtree_first)
b5964b96 10241BTF_ID(func, bpf_dynptr_from_skb)
05421aec 10242BTF_ID(func, bpf_dynptr_from_xdp)
66e3a13e
JK
10243BTF_ID(func, bpf_dynptr_slice)
10244BTF_ID(func, bpf_dynptr_slice_rdwr)
361f129f 10245BTF_ID(func, bpf_dynptr_clone)
9bb00b28 10246
7793fc3b
DM
10247static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10248{
10249 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10250 meta->arg_owning_ref) {
10251 return false;
10252 }
10253
10254 return meta->kfunc_flags & KF_RET_NULL;
10255}
10256
9bb00b28
YS
10257static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10258{
10259 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10260}
10261
10262static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10263{
10264 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10265}
ac9f0605 10266
00b85860
KKD
10267static enum kfunc_ptr_arg_type
10268get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10269 struct bpf_kfunc_call_arg_meta *meta,
10270 const struct btf_type *t, const struct btf_type *ref_t,
10271 const char *ref_tname, const struct btf_param *args,
10272 int argno, int nargs)
10273{
10274 u32 regno = argno + 1;
10275 struct bpf_reg_state *regs = cur_regs(env);
10276 struct bpf_reg_state *reg = &regs[regno];
10277 bool arg_mem_size = false;
10278
fd264ca0
YS
10279 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10280 return KF_ARG_PTR_TO_CTX;
10281
00b85860
KKD
10282 /* In this function, we verify the kfunc's BTF as per the argument type,
10283 * leaving the rest of the verification with respect to the register
10284 * type to our caller. When a set of conditions hold in the BTF type of
10285 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10286 */
10287 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10288 return KF_ARG_PTR_TO_CTX;
10289
ac9f0605
KKD
10290 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10291 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10292
7c50b1cb
DM
10293 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10294 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
00b85860
KKD
10295
10296 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10297 return KF_ARG_PTR_TO_DYNPTR;
10298
06accc87
AN
10299 if (is_kfunc_arg_iter(meta, argno))
10300 return KF_ARG_PTR_TO_ITER;
10301
8cab76ec
KKD
10302 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10303 return KF_ARG_PTR_TO_LIST_HEAD;
10304
10305 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10306 return KF_ARG_PTR_TO_LIST_NODE;
10307
cd6791b4
DM
10308 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10309 return KF_ARG_PTR_TO_RB_ROOT;
10310
10311 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10312 return KF_ARG_PTR_TO_RB_NODE;
10313
00b85860
KKD
10314 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10315 if (!btf_type_is_struct(ref_t)) {
10316 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10317 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10318 return -EINVAL;
10319 }
10320 return KF_ARG_PTR_TO_BTF_ID;
10321 }
10322
5d92ddc3
DM
10323 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10324 return KF_ARG_PTR_TO_CALLBACK;
10325
66e3a13e
JK
10326
10327 if (argno + 1 < nargs &&
10328 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10329 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
00b85860
KKD
10330 arg_mem_size = true;
10331
10332 /* This is the catch all argument type of register types supported by
10333 * check_helper_mem_access. However, we only allow when argument type is
10334 * pointer to scalar, or struct composed (recursively) of scalars. When
10335 * arg_mem_size is true, the pointer can be void *.
10336 */
10337 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10338 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10339 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10340 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10341 return -EINVAL;
10342 }
10343 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10344}
10345
10346static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10347 struct bpf_reg_state *reg,
10348 const struct btf_type *ref_t,
10349 const char *ref_tname, u32 ref_id,
10350 struct bpf_kfunc_call_arg_meta *meta,
10351 int argno)
10352{
10353 const struct btf_type *reg_ref_t;
10354 bool strict_type_match = false;
10355 const struct btf *reg_btf;
10356 const char *reg_ref_tname;
10357 u32 reg_ref_id;
10358
3f00c523 10359 if (base_type(reg->type) == PTR_TO_BTF_ID) {
00b85860
KKD
10360 reg_btf = reg->btf;
10361 reg_ref_id = reg->btf_id;
10362 } else {
10363 reg_btf = btf_vmlinux;
10364 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10365 }
10366
b613d335
DV
10367 /* Enforce strict type matching for calls to kfuncs that are acquiring
10368 * or releasing a reference, or are no-cast aliases. We do _not_
10369 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10370 * as we want to enable BPF programs to pass types that are bitwise
10371 * equivalent without forcing them to explicitly cast with something
10372 * like bpf_cast_to_kern_ctx().
10373 *
10374 * For example, say we had a type like the following:
10375 *
10376 * struct bpf_cpumask {
10377 * cpumask_t cpumask;
10378 * refcount_t usage;
10379 * };
10380 *
10381 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10382 * to a struct cpumask, so it would be safe to pass a struct
10383 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10384 *
10385 * The philosophy here is similar to how we allow scalars of different
10386 * types to be passed to kfuncs as long as the size is the same. The
10387 * only difference here is that we're simply allowing
10388 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10389 * resolve types.
10390 */
10391 if (is_kfunc_acquire(meta) ||
10392 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10393 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
00b85860
KKD
10394 strict_type_match = true;
10395
b613d335
DV
10396 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10397
00b85860
KKD
10398 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10399 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10400 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10401 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10402 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10403 btf_type_str(reg_ref_t), reg_ref_tname);
10404 return -EINVAL;
10405 }
10406 return 0;
10407}
10408
6a3cd331 10409static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
534e86bc 10410{
6a3cd331
DM
10411 struct bpf_verifier_state *state = env->cur_state;
10412
10413 if (!state->active_lock.ptr) {
10414 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10415 return -EFAULT;
10416 }
10417
10418 if (type_flag(reg->type) & NON_OWN_REF) {
10419 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10420 return -EFAULT;
10421 }
10422
10423 reg->type |= NON_OWN_REF;
10424 return 0;
10425}
10426
10427static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10428{
10429 struct bpf_func_state *state, *unused;
534e86bc
KKD
10430 struct bpf_reg_state *reg;
10431 int i;
10432
6a3cd331
DM
10433 state = cur_func(env);
10434
534e86bc 10435 if (!ref_obj_id) {
6a3cd331
DM
10436 verbose(env, "verifier internal error: ref_obj_id is zero for "
10437 "owning -> non-owning conversion\n");
534e86bc
KKD
10438 return -EFAULT;
10439 }
6a3cd331 10440
534e86bc 10441 for (i = 0; i < state->acquired_refs; i++) {
6a3cd331
DM
10442 if (state->refs[i].id != ref_obj_id)
10443 continue;
10444
10445 /* Clear ref_obj_id here so release_reference doesn't clobber
10446 * the whole reg
10447 */
10448 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10449 if (reg->ref_obj_id == ref_obj_id) {
10450 reg->ref_obj_id = 0;
10451 ref_set_non_owning(env, reg);
534e86bc 10452 }
6a3cd331
DM
10453 }));
10454 return 0;
534e86bc 10455 }
6a3cd331 10456
534e86bc
KKD
10457 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10458 return -EFAULT;
10459}
10460
8cab76ec
KKD
10461/* Implementation details:
10462 *
10463 * Each register points to some region of memory, which we define as an
10464 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10465 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10466 * allocation. The lock and the data it protects are colocated in the same
10467 * memory region.
10468 *
10469 * Hence, everytime a register holds a pointer value pointing to such
10470 * allocation, the verifier preserves a unique reg->id for it.
10471 *
10472 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10473 * bpf_spin_lock is called.
10474 *
10475 * To enable this, lock state in the verifier captures two values:
10476 * active_lock.ptr = Register's type specific pointer
10477 * active_lock.id = A unique ID for each register pointer value
10478 *
10479 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10480 * supported register types.
10481 *
10482 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10483 * allocated objects is the reg->btf pointer.
10484 *
10485 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10486 * can establish the provenance of the map value statically for each distinct
10487 * lookup into such maps. They always contain a single map value hence unique
10488 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10489 *
10490 * So, in case of global variables, they use array maps with max_entries = 1,
10491 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10492 * into the same map value as max_entries is 1, as described above).
10493 *
10494 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10495 * outer map pointer (in verifier context), but each lookup into an inner map
10496 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10497 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10498 * will get different reg->id assigned to each lookup, hence different
10499 * active_lock.id.
10500 *
10501 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10502 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10503 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10504 */
10505static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10506{
10507 void *ptr;
10508 u32 id;
10509
10510 switch ((int)reg->type) {
10511 case PTR_TO_MAP_VALUE:
10512 ptr = reg->map_ptr;
10513 break;
10514 case PTR_TO_BTF_ID | MEM_ALLOC:
10515 ptr = reg->btf;
10516 break;
10517 default:
10518 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10519 return -EFAULT;
10520 }
10521 id = reg->id;
10522
10523 if (!env->cur_state->active_lock.ptr)
10524 return -EINVAL;
10525 if (env->cur_state->active_lock.ptr != ptr ||
10526 env->cur_state->active_lock.id != id) {
10527 verbose(env, "held lock and object are not in the same allocation\n");
10528 return -EINVAL;
10529 }
10530 return 0;
10531}
10532
10533static bool is_bpf_list_api_kfunc(u32 btf_id)
10534{
d2dcc67d
DM
10535 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10536 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
8cab76ec
KKD
10537 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10538 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10539}
10540
cd6791b4
DM
10541static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10542{
d2dcc67d 10543 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
cd6791b4
DM
10544 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10545 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10546}
10547
10548static bool is_bpf_graph_api_kfunc(u32 btf_id)
10549{
7c50b1cb
DM
10550 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10551 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
cd6791b4
DM
10552}
10553
5d92ddc3
DM
10554static bool is_callback_calling_kfunc(u32 btf_id)
10555{
d2dcc67d 10556 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
5d92ddc3
DM
10557}
10558
10559static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10560{
10561 return is_bpf_rbtree_api_kfunc(btf_id);
10562}
10563
cd6791b4
DM
10564static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10565 enum btf_field_type head_field_type,
10566 u32 kfunc_btf_id)
10567{
10568 bool ret;
10569
10570 switch (head_field_type) {
10571 case BPF_LIST_HEAD:
10572 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10573 break;
10574 case BPF_RB_ROOT:
10575 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10576 break;
10577 default:
10578 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10579 btf_field_type_name(head_field_type));
10580 return false;
10581 }
10582
10583 if (!ret)
10584 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10585 btf_field_type_name(head_field_type));
10586 return ret;
10587}
10588
10589static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10590 enum btf_field_type node_field_type,
10591 u32 kfunc_btf_id)
8cab76ec 10592{
cd6791b4
DM
10593 bool ret;
10594
10595 switch (node_field_type) {
10596 case BPF_LIST_NODE:
d2dcc67d
DM
10597 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10598 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
cd6791b4
DM
10599 break;
10600 case BPF_RB_NODE:
10601 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
d2dcc67d 10602 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
cd6791b4
DM
10603 break;
10604 default:
10605 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10606 btf_field_type_name(node_field_type));
10607 return false;
10608 }
10609
10610 if (!ret)
10611 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10612 btf_field_type_name(node_field_type));
10613 return ret;
10614}
10615
10616static int
10617__process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10618 struct bpf_reg_state *reg, u32 regno,
10619 struct bpf_kfunc_call_arg_meta *meta,
10620 enum btf_field_type head_field_type,
10621 struct btf_field **head_field)
10622{
10623 const char *head_type_name;
8cab76ec
KKD
10624 struct btf_field *field;
10625 struct btf_record *rec;
cd6791b4 10626 u32 head_off;
8cab76ec 10627
cd6791b4
DM
10628 if (meta->btf != btf_vmlinux) {
10629 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
8cab76ec
KKD
10630 return -EFAULT;
10631 }
10632
cd6791b4
DM
10633 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10634 return -EFAULT;
10635
10636 head_type_name = btf_field_type_name(head_field_type);
8cab76ec
KKD
10637 if (!tnum_is_const(reg->var_off)) {
10638 verbose(env,
cd6791b4
DM
10639 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10640 regno, head_type_name);
8cab76ec
KKD
10641 return -EINVAL;
10642 }
10643
10644 rec = reg_btf_record(reg);
cd6791b4
DM
10645 head_off = reg->off + reg->var_off.value;
10646 field = btf_record_find(rec, head_off, head_field_type);
8cab76ec 10647 if (!field) {
cd6791b4 10648 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
8cab76ec
KKD
10649 return -EINVAL;
10650 }
10651
10652 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10653 if (check_reg_allocation_locked(env, reg)) {
cd6791b4
DM
10654 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10655 rec->spin_lock_off, head_type_name);
8cab76ec
KKD
10656 return -EINVAL;
10657 }
10658
cd6791b4
DM
10659 if (*head_field) {
10660 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
8cab76ec
KKD
10661 return -EFAULT;
10662 }
cd6791b4 10663 *head_field = field;
8cab76ec
KKD
10664 return 0;
10665}
10666
cd6791b4 10667static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8cab76ec
KKD
10668 struct bpf_reg_state *reg, u32 regno,
10669 struct bpf_kfunc_call_arg_meta *meta)
10670{
cd6791b4
DM
10671 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10672 &meta->arg_list_head.field);
10673}
10674
10675static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10676 struct bpf_reg_state *reg, u32 regno,
10677 struct bpf_kfunc_call_arg_meta *meta)
10678{
10679 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10680 &meta->arg_rbtree_root.field);
10681}
10682
10683static int
10684__process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10685 struct bpf_reg_state *reg, u32 regno,
10686 struct bpf_kfunc_call_arg_meta *meta,
10687 enum btf_field_type head_field_type,
10688 enum btf_field_type node_field_type,
10689 struct btf_field **node_field)
10690{
10691 const char *node_type_name;
8cab76ec
KKD
10692 const struct btf_type *et, *t;
10693 struct btf_field *field;
cd6791b4 10694 u32 node_off;
8cab76ec 10695
cd6791b4
DM
10696 if (meta->btf != btf_vmlinux) {
10697 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
8cab76ec
KKD
10698 return -EFAULT;
10699 }
10700
cd6791b4
DM
10701 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10702 return -EFAULT;
10703
10704 node_type_name = btf_field_type_name(node_field_type);
8cab76ec
KKD
10705 if (!tnum_is_const(reg->var_off)) {
10706 verbose(env,
cd6791b4
DM
10707 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10708 regno, node_type_name);
8cab76ec
KKD
10709 return -EINVAL;
10710 }
10711
cd6791b4
DM
10712 node_off = reg->off + reg->var_off.value;
10713 field = reg_find_field_offset(reg, node_off, node_field_type);
10714 if (!field || field->offset != node_off) {
10715 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
8cab76ec
KKD
10716 return -EINVAL;
10717 }
10718
cd6791b4 10719 field = *node_field;
8cab76ec 10720
30465003 10721 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
8cab76ec 10722 t = btf_type_by_id(reg->btf, reg->btf_id);
30465003
DM
10723 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10724 field->graph_root.value_btf_id, true)) {
cd6791b4 10725 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
8cab76ec 10726 "in struct %s, but arg is at offset=%d in struct %s\n",
cd6791b4
DM
10727 btf_field_type_name(head_field_type),
10728 btf_field_type_name(node_field_type),
30465003
DM
10729 field->graph_root.node_offset,
10730 btf_name_by_offset(field->graph_root.btf, et->name_off),
cd6791b4 10731 node_off, btf_name_by_offset(reg->btf, t->name_off));
8cab76ec
KKD
10732 return -EINVAL;
10733 }
2140a6e3
DM
10734 meta->arg_btf = reg->btf;
10735 meta->arg_btf_id = reg->btf_id;
8cab76ec 10736
cd6791b4
DM
10737 if (node_off != field->graph_root.node_offset) {
10738 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10739 node_off, btf_field_type_name(node_field_type),
10740 field->graph_root.node_offset,
30465003 10741 btf_name_by_offset(field->graph_root.btf, et->name_off));
8cab76ec
KKD
10742 return -EINVAL;
10743 }
6a3cd331
DM
10744
10745 return 0;
8cab76ec
KKD
10746}
10747
cd6791b4
DM
10748static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10749 struct bpf_reg_state *reg, u32 regno,
10750 struct bpf_kfunc_call_arg_meta *meta)
10751{
10752 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10753 BPF_LIST_HEAD, BPF_LIST_NODE,
10754 &meta->arg_list_head.field);
10755}
10756
10757static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10758 struct bpf_reg_state *reg, u32 regno,
10759 struct bpf_kfunc_call_arg_meta *meta)
10760{
10761 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10762 BPF_RB_ROOT, BPF_RB_NODE,
10763 &meta->arg_rbtree_root.field);
10764}
10765
1d18feb2
JK
10766static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10767 int insn_idx)
00b85860
KKD
10768{
10769 const char *func_name = meta->func_name, *ref_tname;
10770 const struct btf *btf = meta->btf;
10771 const struct btf_param *args;
7c50b1cb 10772 struct btf_record *rec;
00b85860
KKD
10773 u32 i, nargs;
10774 int ret;
10775
10776 args = (const struct btf_param *)(meta->func_proto + 1);
10777 nargs = btf_type_vlen(meta->func_proto);
10778 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10779 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10780 MAX_BPF_FUNC_REG_ARGS);
10781 return -EINVAL;
10782 }
10783
10784 /* Check that BTF function arguments match actual types that the
10785 * verifier sees.
10786 */
10787 for (i = 0; i < nargs; i++) {
10788 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10789 const struct btf_type *t, *ref_t, *resolve_ret;
10790 enum bpf_arg_type arg_type = ARG_DONTCARE;
10791 u32 regno = i + 1, ref_id, type_size;
10792 bool is_ret_buf_sz = false;
10793 int kf_arg_type;
10794
10795 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
958cf2e2
KKD
10796
10797 if (is_kfunc_arg_ignore(btf, &args[i]))
10798 continue;
10799
00b85860
KKD
10800 if (btf_type_is_scalar(t)) {
10801 if (reg->type != SCALAR_VALUE) {
10802 verbose(env, "R%d is not a scalar\n", regno);
10803 return -EINVAL;
10804 }
a50388db
KKD
10805
10806 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10807 if (meta->arg_constant.found) {
10808 verbose(env, "verifier internal error: only one constant argument permitted\n");
10809 return -EFAULT;
10810 }
10811 if (!tnum_is_const(reg->var_off)) {
10812 verbose(env, "R%d must be a known constant\n", regno);
10813 return -EINVAL;
10814 }
10815 ret = mark_chain_precision(env, regno);
10816 if (ret < 0)
10817 return ret;
10818 meta->arg_constant.found = true;
10819 meta->arg_constant.value = reg->var_off.value;
10820 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
00b85860
KKD
10821 meta->r0_rdonly = true;
10822 is_ret_buf_sz = true;
10823 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10824 is_ret_buf_sz = true;
10825 }
10826
10827 if (is_ret_buf_sz) {
10828 if (meta->r0_size) {
10829 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10830 return -EINVAL;
10831 }
10832
10833 if (!tnum_is_const(reg->var_off)) {
10834 verbose(env, "R%d is not a const\n", regno);
10835 return -EINVAL;
10836 }
10837
10838 meta->r0_size = reg->var_off.value;
10839 ret = mark_chain_precision(env, regno);
10840 if (ret)
10841 return ret;
10842 }
10843 continue;
10844 }
10845
10846 if (!btf_type_is_ptr(t)) {
10847 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10848 return -EINVAL;
10849 }
10850
20c09d92 10851 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
caf713c3
DV
10852 (register_is_null(reg) || type_may_be_null(reg->type))) {
10853 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10854 return -EACCES;
10855 }
10856
00b85860
KKD
10857 if (reg->ref_obj_id) {
10858 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10859 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10860 regno, reg->ref_obj_id,
10861 meta->ref_obj_id);
10862 return -EFAULT;
10863 }
10864 meta->ref_obj_id = reg->ref_obj_id;
10865 if (is_kfunc_release(meta))
10866 meta->release_regno = regno;
10867 }
10868
10869 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10870 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10871
10872 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10873 if (kf_arg_type < 0)
10874 return kf_arg_type;
10875
10876 switch (kf_arg_type) {
ac9f0605 10877 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
00b85860 10878 case KF_ARG_PTR_TO_BTF_ID:
fca1aa75 10879 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
00b85860 10880 break;
3f00c523
DV
10881
10882 if (!is_trusted_reg(reg)) {
fca1aa75
YS
10883 if (!is_kfunc_rcu(meta)) {
10884 verbose(env, "R%d must be referenced or trusted\n", regno);
10885 return -EINVAL;
10886 }
10887 if (!is_rcu_reg(reg)) {
10888 verbose(env, "R%d must be a rcu pointer\n", regno);
10889 return -EINVAL;
10890 }
00b85860 10891 }
fca1aa75 10892
00b85860
KKD
10893 fallthrough;
10894 case KF_ARG_PTR_TO_CTX:
10895 /* Trusted arguments have the same offset checks as release arguments */
10896 arg_type |= OBJ_RELEASE;
10897 break;
00b85860 10898 case KF_ARG_PTR_TO_DYNPTR:
06accc87 10899 case KF_ARG_PTR_TO_ITER:
8cab76ec
KKD
10900 case KF_ARG_PTR_TO_LIST_HEAD:
10901 case KF_ARG_PTR_TO_LIST_NODE:
cd6791b4
DM
10902 case KF_ARG_PTR_TO_RB_ROOT:
10903 case KF_ARG_PTR_TO_RB_NODE:
00b85860
KKD
10904 case KF_ARG_PTR_TO_MEM:
10905 case KF_ARG_PTR_TO_MEM_SIZE:
5d92ddc3 10906 case KF_ARG_PTR_TO_CALLBACK:
7c50b1cb 10907 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
00b85860
KKD
10908 /* Trusted by default */
10909 break;
10910 default:
10911 WARN_ON_ONCE(1);
10912 return -EFAULT;
10913 }
10914
10915 if (is_kfunc_release(meta) && reg->ref_obj_id)
10916 arg_type |= OBJ_RELEASE;
10917 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10918 if (ret < 0)
10919 return ret;
10920
10921 switch (kf_arg_type) {
10922 case KF_ARG_PTR_TO_CTX:
10923 if (reg->type != PTR_TO_CTX) {
10924 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10925 return -EINVAL;
10926 }
fd264ca0
YS
10927
10928 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10929 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10930 if (ret < 0)
10931 return -EINVAL;
10932 meta->ret_btf_id = ret;
10933 }
00b85860 10934 break;
ac9f0605
KKD
10935 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10936 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10937 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10938 return -EINVAL;
10939 }
10940 if (!reg->ref_obj_id) {
10941 verbose(env, "allocated object must be referenced\n");
10942 return -EINVAL;
10943 }
10944 if (meta->btf == btf_vmlinux &&
10945 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
4d585f48
DM
10946 meta->arg_btf = reg->btf;
10947 meta->arg_btf_id = reg->btf_id;
ac9f0605
KKD
10948 }
10949 break;
00b85860 10950 case KF_ARG_PTR_TO_DYNPTR:
d96d937d
JK
10951 {
10952 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
361f129f 10953 int clone_ref_obj_id = 0;
d96d937d 10954
6b75bd3d 10955 if (reg->type != PTR_TO_STACK &&
27060531 10956 reg->type != CONST_PTR_TO_DYNPTR) {
6b75bd3d 10957 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
00b85860
KKD
10958 return -EINVAL;
10959 }
10960
d96d937d
JK
10961 if (reg->type == CONST_PTR_TO_DYNPTR)
10962 dynptr_arg_type |= MEM_RDONLY;
10963
10964 if (is_kfunc_arg_uninit(btf, &args[i]))
10965 dynptr_arg_type |= MEM_UNINIT;
10966
361f129f 10967 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
b5964b96 10968 dynptr_arg_type |= DYNPTR_TYPE_SKB;
361f129f 10969 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
05421aec 10970 dynptr_arg_type |= DYNPTR_TYPE_XDP;
361f129f
JK
10971 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10972 (dynptr_arg_type & MEM_UNINIT)) {
10973 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10974
10975 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10976 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10977 return -EFAULT;
10978 }
10979
10980 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10981 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10982 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10983 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10984 return -EFAULT;
10985 }
10986 }
b5964b96 10987
361f129f 10988 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
6b75bd3d
KKD
10989 if (ret < 0)
10990 return ret;
66e3a13e
JK
10991
10992 if (!(dynptr_arg_type & MEM_UNINIT)) {
10993 int id = dynptr_id(env, reg);
10994
10995 if (id < 0) {
10996 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10997 return id;
10998 }
10999 meta->initialized_dynptr.id = id;
11000 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
361f129f 11001 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
66e3a13e
JK
11002 }
11003
00b85860 11004 break;
d96d937d 11005 }
06accc87
AN
11006 case KF_ARG_PTR_TO_ITER:
11007 ret = process_iter_arg(env, regno, insn_idx, meta);
11008 if (ret < 0)
11009 return ret;
11010 break;
8cab76ec
KKD
11011 case KF_ARG_PTR_TO_LIST_HEAD:
11012 if (reg->type != PTR_TO_MAP_VALUE &&
11013 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11014 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11015 return -EINVAL;
11016 }
11017 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11018 verbose(env, "allocated object must be referenced\n");
11019 return -EINVAL;
11020 }
11021 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11022 if (ret < 0)
11023 return ret;
11024 break;
cd6791b4
DM
11025 case KF_ARG_PTR_TO_RB_ROOT:
11026 if (reg->type != PTR_TO_MAP_VALUE &&
11027 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11028 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11029 return -EINVAL;
11030 }
11031 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11032 verbose(env, "allocated object must be referenced\n");
11033 return -EINVAL;
11034 }
11035 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11036 if (ret < 0)
11037 return ret;
11038 break;
8cab76ec
KKD
11039 case KF_ARG_PTR_TO_LIST_NODE:
11040 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11041 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11042 return -EINVAL;
11043 }
11044 if (!reg->ref_obj_id) {
11045 verbose(env, "allocated object must be referenced\n");
11046 return -EINVAL;
11047 }
11048 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11049 if (ret < 0)
11050 return ret;
11051 break;
cd6791b4 11052 case KF_ARG_PTR_TO_RB_NODE:
a40d3632
DM
11053 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11054 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11055 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11056 return -EINVAL;
11057 }
11058 if (in_rbtree_lock_required_cb(env)) {
11059 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11060 return -EINVAL;
11061 }
11062 } else {
11063 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11064 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11065 return -EINVAL;
11066 }
11067 if (!reg->ref_obj_id) {
11068 verbose(env, "allocated object must be referenced\n");
11069 return -EINVAL;
11070 }
cd6791b4 11071 }
a40d3632 11072
cd6791b4
DM
11073 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11074 if (ret < 0)
11075 return ret;
11076 break;
00b85860
KKD
11077 case KF_ARG_PTR_TO_BTF_ID:
11078 /* Only base_type is checked, further checks are done here */
3f00c523 11079 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
fca1aa75 11080 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
3f00c523
DV
11081 !reg2btf_ids[base_type(reg->type)]) {
11082 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11083 verbose(env, "expected %s or socket\n",
11084 reg_type_str(env, base_type(reg->type) |
11085 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
00b85860
KKD
11086 return -EINVAL;
11087 }
11088 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11089 if (ret < 0)
11090 return ret;
11091 break;
11092 case KF_ARG_PTR_TO_MEM:
11093 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11094 if (IS_ERR(resolve_ret)) {
11095 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11096 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11097 return -EINVAL;
11098 }
11099 ret = check_mem_reg(env, reg, regno, type_size);
11100 if (ret < 0)
11101 return ret;
11102 break;
11103 case KF_ARG_PTR_TO_MEM_SIZE:
66e3a13e 11104 {
3bda08b6
DR
11105 struct bpf_reg_state *buff_reg = &regs[regno];
11106 const struct btf_param *buff_arg = &args[i];
66e3a13e
JK
11107 struct bpf_reg_state *size_reg = &regs[regno + 1];
11108 const struct btf_param *size_arg = &args[i + 1];
11109
3bda08b6
DR
11110 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11111 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11112 if (ret < 0) {
11113 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11114 return ret;
11115 }
00b85860 11116 }
66e3a13e
JK
11117
11118 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11119 if (meta->arg_constant.found) {
11120 verbose(env, "verifier internal error: only one constant argument permitted\n");
11121 return -EFAULT;
11122 }
11123 if (!tnum_is_const(size_reg->var_off)) {
11124 verbose(env, "R%d must be a known constant\n", regno + 1);
11125 return -EINVAL;
11126 }
11127 meta->arg_constant.found = true;
11128 meta->arg_constant.value = size_reg->var_off.value;
11129 }
11130
11131 /* Skip next '__sz' or '__szk' argument */
00b85860
KKD
11132 i++;
11133 break;
66e3a13e 11134 }
5d92ddc3
DM
11135 case KF_ARG_PTR_TO_CALLBACK:
11136 meta->subprogno = reg->subprogno;
11137 break;
7c50b1cb 11138 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
7793fc3b 11139 if (!type_is_ptr_alloc_obj(reg->type)) {
7c50b1cb
DM
11140 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11141 return -EINVAL;
11142 }
7793fc3b
DM
11143 if (!type_is_non_owning_ref(reg->type))
11144 meta->arg_owning_ref = true;
7c50b1cb
DM
11145
11146 rec = reg_btf_record(reg);
11147 if (!rec) {
11148 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11149 return -EFAULT;
11150 }
11151
11152 if (rec->refcount_off < 0) {
11153 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11154 return -EINVAL;
11155 }
7deca5ea
DM
11156 if (rec->refcount_off >= 0) {
11157 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11158 return -EINVAL;
11159 }
4d585f48
DM
11160 meta->arg_btf = reg->btf;
11161 meta->arg_btf_id = reg->btf_id;
7c50b1cb 11162 break;
00b85860
KKD
11163 }
11164 }
11165
11166 if (is_kfunc_release(meta) && !meta->release_regno) {
11167 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11168 func_name);
11169 return -EINVAL;
11170 }
11171
11172 return 0;
11173}
11174
07236eab
AN
11175static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11176 struct bpf_insn *insn,
11177 struct bpf_kfunc_call_arg_meta *meta,
11178 const char **kfunc_name)
e6ac2450 11179{
07236eab
AN
11180 const struct btf_type *func, *func_proto;
11181 u32 func_id, *kfunc_flags;
11182 const char *func_name;
2357672c 11183 struct btf *desc_btf;
e6ac2450 11184
07236eab
AN
11185 if (kfunc_name)
11186 *kfunc_name = NULL;
11187
a5d82727 11188 if (!insn->imm)
07236eab 11189 return -EINVAL;
a5d82727 11190
43bf0878 11191 desc_btf = find_kfunc_desc_btf(env, insn->off);
2357672c
KKD
11192 if (IS_ERR(desc_btf))
11193 return PTR_ERR(desc_btf);
11194
e6ac2450 11195 func_id = insn->imm;
2357672c
KKD
11196 func = btf_type_by_id(desc_btf, func_id);
11197 func_name = btf_name_by_offset(desc_btf, func->name_off);
07236eab
AN
11198 if (kfunc_name)
11199 *kfunc_name = func_name;
2357672c 11200 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450 11201
e924e80e 11202 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
a4703e31 11203 if (!kfunc_flags) {
e6ac2450
MKL
11204 return -EACCES;
11205 }
00b85860 11206
07236eab
AN
11207 memset(meta, 0, sizeof(*meta));
11208 meta->btf = desc_btf;
11209 meta->func_id = func_id;
11210 meta->kfunc_flags = *kfunc_flags;
11211 meta->func_proto = func_proto;
11212 meta->func_name = func_name;
11213
11214 return 0;
11215}
11216
11217static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11218 int *insn_idx_p)
11219{
11220 const struct btf_type *t, *ptr_type;
11221 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11222 struct bpf_reg_state *regs = cur_regs(env);
11223 const char *func_name, *ptr_type_name;
11224 bool sleepable, rcu_lock, rcu_unlock;
11225 struct bpf_kfunc_call_arg_meta meta;
11226 struct bpf_insn_aux_data *insn_aux;
11227 int err, insn_idx = *insn_idx_p;
11228 const struct btf_param *args;
11229 const struct btf_type *ret_t;
11230 struct btf *desc_btf;
11231
11232 /* skip for now, but return error when we find this in fixup_kfunc_call */
11233 if (!insn->imm)
11234 return 0;
11235
11236 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11237 if (err == -EACCES && func_name)
11238 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11239 if (err)
11240 return err;
11241 desc_btf = meta.btf;
11242 insn_aux = &env->insn_aux_data[insn_idx];
00b85860 11243
06accc87
AN
11244 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11245
00b85860
KKD
11246 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11247 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
4dd48c6f
AS
11248 return -EACCES;
11249 }
11250
9bb00b28
YS
11251 sleepable = is_kfunc_sleepable(&meta);
11252 if (sleepable && !env->prog->aux->sleepable) {
00b85860
KKD
11253 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11254 return -EACCES;
11255 }
eb1f7f71 11256
9bb00b28
YS
11257 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11258 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
9bb00b28
YS
11259
11260 if (env->cur_state->active_rcu_lock) {
11261 struct bpf_func_state *state;
11262 struct bpf_reg_state *reg;
11263
11264 if (rcu_lock) {
11265 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11266 return -EINVAL;
11267 } else if (rcu_unlock) {
11268 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11269 if (reg->type & MEM_RCU) {
fca1aa75 11270 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9bb00b28
YS
11271 reg->type |= PTR_UNTRUSTED;
11272 }
11273 }));
11274 env->cur_state->active_rcu_lock = false;
11275 } else if (sleepable) {
11276 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11277 return -EACCES;
11278 }
11279 } else if (rcu_lock) {
11280 env->cur_state->active_rcu_lock = true;
11281 } else if (rcu_unlock) {
11282 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11283 return -EINVAL;
11284 }
11285
e6ac2450 11286 /* Check the arguments */
1d18feb2 11287 err = check_kfunc_args(env, &meta, insn_idx);
5c073f26 11288 if (err < 0)
e6ac2450 11289 return err;
5c073f26 11290 /* In case of release function, we get register number of refcounted
00b85860 11291 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
5c073f26 11292 */
00b85860
KKD
11293 if (meta.release_regno) {
11294 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
5c073f26
KKD
11295 if (err) {
11296 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
07236eab 11297 func_name, meta.func_id);
5c073f26
KKD
11298 return err;
11299 }
11300 }
e6ac2450 11301
d2dcc67d
DM
11302 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11303 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11304 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
6a3cd331 11305 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
d2dcc67d 11306 insn_aux->insert_off = regs[BPF_REG_2].off;
2140a6e3 11307 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
6a3cd331
DM
11308 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11309 if (err) {
11310 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
07236eab 11311 func_name, meta.func_id);
6a3cd331
DM
11312 return err;
11313 }
11314
11315 err = release_reference(env, release_ref_obj_id);
11316 if (err) {
11317 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
07236eab 11318 func_name, meta.func_id);
6a3cd331
DM
11319 return err;
11320 }
11321 }
11322
d2dcc67d 11323 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
5d92ddc3
DM
11324 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11325 set_rbtree_add_callback_state);
11326 if (err) {
11327 verbose(env, "kfunc %s#%d failed callback verification\n",
07236eab 11328 func_name, meta.func_id);
5d92ddc3
DM
11329 return err;
11330 }
11331 }
11332
e6ac2450
MKL
11333 for (i = 0; i < CALLER_SAVED_REGS; i++)
11334 mark_reg_not_init(env, regs, caller_saved[i]);
11335
11336 /* Check return type */
07236eab 11337 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
5c073f26 11338
00b85860 11339 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
958cf2e2 11340 /* Only exception is bpf_obj_new_impl */
7c50b1cb
DM
11341 if (meta.btf != btf_vmlinux ||
11342 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11343 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
958cf2e2
KKD
11344 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11345 return -EINVAL;
11346 }
5c073f26
KKD
11347 }
11348
e6ac2450
MKL
11349 if (btf_type_is_scalar(t)) {
11350 mark_reg_unknown(env, regs, BPF_REG_0);
11351 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11352 } else if (btf_type_is_ptr(t)) {
958cf2e2
KKD
11353 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11354
11355 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11356 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
958cf2e2
KKD
11357 struct btf *ret_btf;
11358 u32 ret_btf_id;
11359
e181d3f1
KKD
11360 if (unlikely(!bpf_global_ma_set))
11361 return -ENOMEM;
11362
958cf2e2
KKD
11363 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11364 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11365 return -EINVAL;
11366 }
11367
11368 ret_btf = env->prog->aux->btf;
11369 ret_btf_id = meta.arg_constant.value;
11370
11371 /* This may be NULL due to user not supplying a BTF */
11372 if (!ret_btf) {
11373 verbose(env, "bpf_obj_new requires prog BTF\n");
11374 return -EINVAL;
11375 }
11376
11377 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11378 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11379 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11380 return -EINVAL;
11381 }
11382
11383 mark_reg_known_zero(env, regs, BPF_REG_0);
11384 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11385 regs[BPF_REG_0].btf = ret_btf;
11386 regs[BPF_REG_0].btf_id = ret_btf_id;
11387
07236eab
AN
11388 insn_aux->obj_new_size = ret_t->size;
11389 insn_aux->kptr_struct_meta =
958cf2e2 11390 btf_find_struct_meta(ret_btf, ret_btf_id);
7c50b1cb
DM
11391 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11392 mark_reg_known_zero(env, regs, BPF_REG_0);
11393 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
4d585f48
DM
11394 regs[BPF_REG_0].btf = meta.arg_btf;
11395 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
7c50b1cb
DM
11396
11397 insn_aux->kptr_struct_meta =
4d585f48
DM
11398 btf_find_struct_meta(meta.arg_btf,
11399 meta.arg_btf_id);
8cab76ec
KKD
11400 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11401 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11402 struct btf_field *field = meta.arg_list_head.field;
11403
a40d3632
DM
11404 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11405 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11406 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11407 struct btf_field *field = meta.arg_rbtree_root.field;
11408
11409 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
fd264ca0
YS
11410 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11411 mark_reg_known_zero(env, regs, BPF_REG_0);
11412 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11413 regs[BPF_REG_0].btf = desc_btf;
11414 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
a35b9af4
YS
11415 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11416 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11417 if (!ret_t || !btf_type_is_struct(ret_t)) {
11418 verbose(env,
11419 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11420 return -EINVAL;
11421 }
11422
11423 mark_reg_known_zero(env, regs, BPF_REG_0);
11424 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11425 regs[BPF_REG_0].btf = desc_btf;
11426 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
66e3a13e
JK
11427 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11428 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11429 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11430
11431 mark_reg_known_zero(env, regs, BPF_REG_0);
11432
11433 if (!meta.arg_constant.found) {
11434 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11435 return -EFAULT;
11436 }
11437
11438 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11439
11440 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11441 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11442
11443 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11444 regs[BPF_REG_0].type |= MEM_RDONLY;
11445 } else {
11446 /* this will set env->seen_direct_write to true */
11447 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11448 verbose(env, "the prog does not allow writes to packet data\n");
11449 return -EINVAL;
11450 }
11451 }
11452
11453 if (!meta.initialized_dynptr.id) {
11454 verbose(env, "verifier internal error: no dynptr id\n");
11455 return -EFAULT;
11456 }
11457 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11458
11459 /* we don't need to set BPF_REG_0's ref obj id
11460 * because packet slices are not refcounted (see
11461 * dynptr_type_refcounted)
11462 */
958cf2e2
KKD
11463 } else {
11464 verbose(env, "kernel function %s unhandled dynamic return type\n",
11465 meta.func_name);
11466 return -EFAULT;
11467 }
11468 } else if (!__btf_type_is_struct(ptr_type)) {
f4b4eee6
AN
11469 if (!meta.r0_size) {
11470 __u32 sz;
11471
11472 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11473 meta.r0_size = sz;
11474 meta.r0_rdonly = true;
11475 }
11476 }
eb1f7f71
BT
11477 if (!meta.r0_size) {
11478 ptr_type_name = btf_name_by_offset(desc_btf,
11479 ptr_type->name_off);
11480 verbose(env,
11481 "kernel function %s returns pointer type %s %s is not supported\n",
11482 func_name,
11483 btf_type_str(ptr_type),
11484 ptr_type_name);
11485 return -EINVAL;
11486 }
11487
11488 mark_reg_known_zero(env, regs, BPF_REG_0);
11489 regs[BPF_REG_0].type = PTR_TO_MEM;
11490 regs[BPF_REG_0].mem_size = meta.r0_size;
11491
11492 if (meta.r0_rdonly)
11493 regs[BPF_REG_0].type |= MEM_RDONLY;
11494
11495 /* Ensures we don't access the memory after a release_reference() */
11496 if (meta.ref_obj_id)
11497 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11498 } else {
11499 mark_reg_known_zero(env, regs, BPF_REG_0);
11500 regs[BPF_REG_0].btf = desc_btf;
11501 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11502 regs[BPF_REG_0].btf_id = ptr_type_id;
e6ac2450 11503 }
958cf2e2 11504
00b85860 11505 if (is_kfunc_ret_null(&meta)) {
5c073f26
KKD
11506 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11507 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11508 regs[BPF_REG_0].id = ++env->id_gen;
11509 }
e6ac2450 11510 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
00b85860 11511 if (is_kfunc_acquire(&meta)) {
5c073f26
KKD
11512 int id = acquire_reference_state(env, insn_idx);
11513
11514 if (id < 0)
11515 return id;
00b85860
KKD
11516 if (is_kfunc_ret_null(&meta))
11517 regs[BPF_REG_0].id = id;
5c073f26 11518 regs[BPF_REG_0].ref_obj_id = id;
a40d3632
DM
11519 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11520 ref_set_non_owning(env, &regs[BPF_REG_0]);
5c073f26 11521 }
a40d3632 11522
00b85860
KKD
11523 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11524 regs[BPF_REG_0].id = ++env->id_gen;
f6a6a5a9
DM
11525 } else if (btf_type_is_void(t)) {
11526 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11527 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11528 insn_aux->kptr_struct_meta =
4d585f48
DM
11529 btf_find_struct_meta(meta.arg_btf,
11530 meta.arg_btf_id);
f6a6a5a9
DM
11531 }
11532 }
11533 }
e6ac2450 11534
07236eab
AN
11535 nargs = btf_type_vlen(meta.func_proto);
11536 args = (const struct btf_param *)(meta.func_proto + 1);
e6ac2450
MKL
11537 for (i = 0; i < nargs; i++) {
11538 u32 regno = i + 1;
11539
2357672c 11540 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
e6ac2450
MKL
11541 if (btf_type_is_ptr(t))
11542 mark_btf_func_reg_size(env, regno, sizeof(void *));
11543 else
11544 /* scalar. ensured by btf_check_kfunc_arg_match() */
11545 mark_btf_func_reg_size(env, regno, t->size);
11546 }
11547
06accc87
AN
11548 if (is_iter_next_kfunc(&meta)) {
11549 err = process_iter_next_call(env, insn_idx, &meta);
11550 if (err)
11551 return err;
11552 }
11553
e6ac2450
MKL
11554 return 0;
11555}
11556
b03c9f9f
EC
11557static bool signed_add_overflows(s64 a, s64 b)
11558{
11559 /* Do the add in u64, where overflow is well-defined */
11560 s64 res = (s64)((u64)a + (u64)b);
11561
11562 if (b < 0)
11563 return res > a;
11564 return res < a;
11565}
11566
bc895e8b 11567static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
11568{
11569 /* Do the add in u32, where overflow is well-defined */
11570 s32 res = (s32)((u32)a + (u32)b);
11571
11572 if (b < 0)
11573 return res > a;
11574 return res < a;
11575}
11576
bc895e8b 11577static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
11578{
11579 /* Do the sub in u64, where overflow is well-defined */
11580 s64 res = (s64)((u64)a - (u64)b);
11581
11582 if (b < 0)
11583 return res < a;
11584 return res > a;
969bf05e
AS
11585}
11586
3f50f132
JF
11587static bool signed_sub32_overflows(s32 a, s32 b)
11588{
bc895e8b 11589 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
11590 s32 res = (s32)((u32)a - (u32)b);
11591
11592 if (b < 0)
11593 return res < a;
11594 return res > a;
11595}
11596
bb7f0f98
AS
11597static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11598 const struct bpf_reg_state *reg,
11599 enum bpf_reg_type type)
11600{
11601 bool known = tnum_is_const(reg->var_off);
11602 s64 val = reg->var_off.value;
11603 s64 smin = reg->smin_value;
11604
11605 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11606 verbose(env, "math between %s pointer and %lld is not allowed\n",
c25b2ae1 11607 reg_type_str(env, type), val);
bb7f0f98
AS
11608 return false;
11609 }
11610
11611 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11612 verbose(env, "%s pointer offset %d is not allowed\n",
c25b2ae1 11613 reg_type_str(env, type), reg->off);
bb7f0f98
AS
11614 return false;
11615 }
11616
11617 if (smin == S64_MIN) {
11618 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
c25b2ae1 11619 reg_type_str(env, type));
bb7f0f98
AS
11620 return false;
11621 }
11622
11623 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11624 verbose(env, "value %lld makes %s pointer be out of bounds\n",
c25b2ae1 11625 smin, reg_type_str(env, type));
bb7f0f98
AS
11626 return false;
11627 }
11628
11629 return true;
11630}
11631
a6aaece0
DB
11632enum {
11633 REASON_BOUNDS = -1,
11634 REASON_TYPE = -2,
11635 REASON_PATHS = -3,
11636 REASON_LIMIT = -4,
11637 REASON_STACK = -5,
11638};
11639
979d63d5 11640static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 11641 u32 *alu_limit, bool mask_to_left)
979d63d5 11642{
7fedb63a 11643 u32 max = 0, ptr_limit = 0;
979d63d5
DB
11644
11645 switch (ptr_reg->type) {
11646 case PTR_TO_STACK:
1b1597e6 11647 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
11648 * left direction, see BPF_REG_FP. Also, unknown scalar
11649 * offset where we would need to deal with min/max bounds is
11650 * currently prohibited for unprivileged.
1b1597e6
PK
11651 */
11652 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 11653 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 11654 break;
979d63d5 11655 case PTR_TO_MAP_VALUE:
1b1597e6 11656 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
11657 ptr_limit = (mask_to_left ?
11658 ptr_reg->smin_value :
11659 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 11660 break;
979d63d5 11661 default:
a6aaece0 11662 return REASON_TYPE;
979d63d5 11663 }
b658bbb8
DB
11664
11665 if (ptr_limit >= max)
a6aaece0 11666 return REASON_LIMIT;
b658bbb8
DB
11667 *alu_limit = ptr_limit;
11668 return 0;
979d63d5
DB
11669}
11670
d3bd7413
DB
11671static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11672 const struct bpf_insn *insn)
11673{
2c78ee89 11674 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
11675}
11676
11677static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11678 u32 alu_state, u32 alu_limit)
11679{
11680 /* If we arrived here from different branches with different
11681 * state or limits to sanitize, then this won't work.
11682 */
11683 if (aux->alu_state &&
11684 (aux->alu_state != alu_state ||
11685 aux->alu_limit != alu_limit))
a6aaece0 11686 return REASON_PATHS;
d3bd7413 11687
e6ac5933 11688 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
11689 aux->alu_state = alu_state;
11690 aux->alu_limit = alu_limit;
11691 return 0;
11692}
11693
11694static int sanitize_val_alu(struct bpf_verifier_env *env,
11695 struct bpf_insn *insn)
11696{
11697 struct bpf_insn_aux_data *aux = cur_aux(env);
11698
11699 if (can_skip_alu_sanitation(env, insn))
11700 return 0;
11701
11702 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11703}
11704
f5288193
DB
11705static bool sanitize_needed(u8 opcode)
11706{
11707 return opcode == BPF_ADD || opcode == BPF_SUB;
11708}
11709
3d0220f6
DB
11710struct bpf_sanitize_info {
11711 struct bpf_insn_aux_data aux;
bb01a1bb 11712 bool mask_to_left;
3d0220f6
DB
11713};
11714
9183671a
DB
11715static struct bpf_verifier_state *
11716sanitize_speculative_path(struct bpf_verifier_env *env,
11717 const struct bpf_insn *insn,
11718 u32 next_idx, u32 curr_idx)
11719{
11720 struct bpf_verifier_state *branch;
11721 struct bpf_reg_state *regs;
11722
11723 branch = push_stack(env, next_idx, curr_idx, true);
11724 if (branch && insn) {
11725 regs = branch->frame[branch->curframe]->regs;
11726 if (BPF_SRC(insn->code) == BPF_K) {
11727 mark_reg_unknown(env, regs, insn->dst_reg);
11728 } else if (BPF_SRC(insn->code) == BPF_X) {
11729 mark_reg_unknown(env, regs, insn->dst_reg);
11730 mark_reg_unknown(env, regs, insn->src_reg);
11731 }
11732 }
11733 return branch;
11734}
11735
979d63d5
DB
11736static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11737 struct bpf_insn *insn,
11738 const struct bpf_reg_state *ptr_reg,
6f55b2f2 11739 const struct bpf_reg_state *off_reg,
979d63d5 11740 struct bpf_reg_state *dst_reg,
3d0220f6 11741 struct bpf_sanitize_info *info,
7fedb63a 11742 const bool commit_window)
979d63d5 11743{
3d0220f6 11744 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 11745 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 11746 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 11747 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
11748 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11749 u8 opcode = BPF_OP(insn->code);
11750 u32 alu_state, alu_limit;
11751 struct bpf_reg_state tmp;
11752 bool ret;
f232326f 11753 int err;
979d63d5 11754
d3bd7413 11755 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
11756 return 0;
11757
11758 /* We already marked aux for masking from non-speculative
11759 * paths, thus we got here in the first place. We only care
11760 * to explore bad access from here.
11761 */
11762 if (vstate->speculative)
11763 goto do_sim;
11764
bb01a1bb
DB
11765 if (!commit_window) {
11766 if (!tnum_is_const(off_reg->var_off) &&
11767 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11768 return REASON_BOUNDS;
11769
11770 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11771 (opcode == BPF_SUB && !off_is_neg);
11772 }
11773
11774 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
11775 if (err < 0)
11776 return err;
11777
7fedb63a
DB
11778 if (commit_window) {
11779 /* In commit phase we narrow the masking window based on
11780 * the observed pointer move after the simulated operation.
11781 */
3d0220f6
DB
11782 alu_state = info->aux.alu_state;
11783 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
11784 } else {
11785 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 11786 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
11787 alu_state |= ptr_is_dst_reg ?
11788 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
e042aa53
DB
11789
11790 /* Limit pruning on unknown scalars to enable deep search for
11791 * potential masking differences from other program paths.
11792 */
11793 if (!off_is_imm)
11794 env->explore_alu_limits = true;
7fedb63a
DB
11795 }
11796
f232326f
PK
11797 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11798 if (err < 0)
11799 return err;
979d63d5 11800do_sim:
7fedb63a
DB
11801 /* If we're in commit phase, we're done here given we already
11802 * pushed the truncated dst_reg into the speculative verification
11803 * stack.
a7036191
DB
11804 *
11805 * Also, when register is a known constant, we rewrite register-based
11806 * operation to immediate-based, and thus do not need masking (and as
11807 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 11808 */
a7036191 11809 if (commit_window || off_is_imm)
7fedb63a
DB
11810 return 0;
11811
979d63d5
DB
11812 /* Simulate and find potential out-of-bounds access under
11813 * speculative execution from truncation as a result of
11814 * masking when off was not within expected range. If off
11815 * sits in dst, then we temporarily need to move ptr there
11816 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11817 * for cases where we use K-based arithmetic in one direction
11818 * and truncated reg-based in the other in order to explore
11819 * bad access.
11820 */
11821 if (!ptr_is_dst_reg) {
11822 tmp = *dst_reg;
71f656a5 11823 copy_register_state(dst_reg, ptr_reg);
979d63d5 11824 }
9183671a
DB
11825 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11826 env->insn_idx);
0803278b 11827 if (!ptr_is_dst_reg && ret)
979d63d5 11828 *dst_reg = tmp;
a6aaece0
DB
11829 return !ret ? REASON_STACK : 0;
11830}
11831
fe9a5ca7
DB
11832static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11833{
11834 struct bpf_verifier_state *vstate = env->cur_state;
11835
11836 /* If we simulate paths under speculation, we don't update the
11837 * insn as 'seen' such that when we verify unreachable paths in
11838 * the non-speculative domain, sanitize_dead_code() can still
11839 * rewrite/sanitize them.
11840 */
11841 if (!vstate->speculative)
11842 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11843}
11844
a6aaece0
DB
11845static int sanitize_err(struct bpf_verifier_env *env,
11846 const struct bpf_insn *insn, int reason,
11847 const struct bpf_reg_state *off_reg,
11848 const struct bpf_reg_state *dst_reg)
11849{
11850 static const char *err = "pointer arithmetic with it prohibited for !root";
11851 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11852 u32 dst = insn->dst_reg, src = insn->src_reg;
11853
11854 switch (reason) {
11855 case REASON_BOUNDS:
11856 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11857 off_reg == dst_reg ? dst : src, err);
11858 break;
11859 case REASON_TYPE:
11860 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11861 off_reg == dst_reg ? src : dst, err);
11862 break;
11863 case REASON_PATHS:
11864 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11865 dst, op, err);
11866 break;
11867 case REASON_LIMIT:
11868 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11869 dst, op, err);
11870 break;
11871 case REASON_STACK:
11872 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11873 dst, err);
11874 break;
11875 default:
11876 verbose(env, "verifier internal error: unknown reason (%d)\n",
11877 reason);
11878 break;
11879 }
11880
11881 return -EACCES;
979d63d5
DB
11882}
11883
01f810ac
AM
11884/* check that stack access falls within stack limits and that 'reg' doesn't
11885 * have a variable offset.
11886 *
11887 * Variable offset is prohibited for unprivileged mode for simplicity since it
11888 * requires corresponding support in Spectre masking for stack ALU. See also
11889 * retrieve_ptr_limit().
11890 *
11891 *
11892 * 'off' includes 'reg->off'.
11893 */
11894static int check_stack_access_for_ptr_arithmetic(
11895 struct bpf_verifier_env *env,
11896 int regno,
11897 const struct bpf_reg_state *reg,
11898 int off)
11899{
11900 if (!tnum_is_const(reg->var_off)) {
11901 char tn_buf[48];
11902
11903 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11904 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11905 regno, tn_buf, off);
11906 return -EACCES;
11907 }
11908
11909 if (off >= 0 || off < -MAX_BPF_STACK) {
11910 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11911 "prohibited for !root; off=%d\n", regno, off);
11912 return -EACCES;
11913 }
11914
11915 return 0;
11916}
11917
073815b7
DB
11918static int sanitize_check_bounds(struct bpf_verifier_env *env,
11919 const struct bpf_insn *insn,
11920 const struct bpf_reg_state *dst_reg)
11921{
11922 u32 dst = insn->dst_reg;
11923
11924 /* For unprivileged we require that resulting offset must be in bounds
11925 * in order to be able to sanitize access later on.
11926 */
11927 if (env->bypass_spec_v1)
11928 return 0;
11929
11930 switch (dst_reg->type) {
11931 case PTR_TO_STACK:
11932 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11933 dst_reg->off + dst_reg->var_off.value))
11934 return -EACCES;
11935 break;
11936 case PTR_TO_MAP_VALUE:
61df10c7 11937 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
073815b7
DB
11938 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11939 "prohibited for !root\n", dst);
11940 return -EACCES;
11941 }
11942 break;
11943 default:
11944 break;
11945 }
11946
11947 return 0;
11948}
01f810ac 11949
f1174f77 11950/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
11951 * Caller should also handle BPF_MOV case separately.
11952 * If we return -EACCES, caller may want to try again treating pointer as a
11953 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
11954 */
11955static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11956 struct bpf_insn *insn,
11957 const struct bpf_reg_state *ptr_reg,
11958 const struct bpf_reg_state *off_reg)
969bf05e 11959{
f4d7e40a
AS
11960 struct bpf_verifier_state *vstate = env->cur_state;
11961 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11962 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 11963 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
11964 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11965 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11966 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11967 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 11968 struct bpf_sanitize_info info = {};
969bf05e 11969 u8 opcode = BPF_OP(insn->code);
24c109bb 11970 u32 dst = insn->dst_reg;
979d63d5 11971 int ret;
969bf05e 11972
f1174f77 11973 dst_reg = &regs[dst];
969bf05e 11974
6f16101e
DB
11975 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11976 smin_val > smax_val || umin_val > umax_val) {
11977 /* Taint dst register if offset had invalid bounds derived from
11978 * e.g. dead branches.
11979 */
f54c7898 11980 __mark_reg_unknown(env, dst_reg);
6f16101e 11981 return 0;
f1174f77
EC
11982 }
11983
11984 if (BPF_CLASS(insn->code) != BPF_ALU64) {
11985 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
11986 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11987 __mark_reg_unknown(env, dst_reg);
11988 return 0;
11989 }
11990
82abbf8d
AS
11991 verbose(env,
11992 "R%d 32-bit pointer arithmetic prohibited\n",
11993 dst);
f1174f77 11994 return -EACCES;
969bf05e
AS
11995 }
11996
c25b2ae1 11997 if (ptr_reg->type & PTR_MAYBE_NULL) {
aad2eeaf 11998 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
c25b2ae1 11999 dst, reg_type_str(env, ptr_reg->type));
f1174f77 12000 return -EACCES;
c25b2ae1
HL
12001 }
12002
12003 switch (base_type(ptr_reg->type)) {
aad2eeaf 12004 case CONST_PTR_TO_MAP:
7c696732
YS
12005 /* smin_val represents the known value */
12006 if (known && smin_val == 0 && opcode == BPF_ADD)
12007 break;
8731745e 12008 fallthrough;
aad2eeaf 12009 case PTR_TO_PACKET_END:
c64b7983 12010 case PTR_TO_SOCKET:
46f8bc92 12011 case PTR_TO_SOCK_COMMON:
655a51e5 12012 case PTR_TO_TCP_SOCK:
fada7fdc 12013 case PTR_TO_XDP_SOCK:
aad2eeaf 12014 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
c25b2ae1 12015 dst, reg_type_str(env, ptr_reg->type));
f1174f77 12016 return -EACCES;
aad2eeaf
JS
12017 default:
12018 break;
f1174f77
EC
12019 }
12020
12021 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12022 * The id may be overwritten later if we create a new variable offset.
969bf05e 12023 */
f1174f77
EC
12024 dst_reg->type = ptr_reg->type;
12025 dst_reg->id = ptr_reg->id;
969bf05e 12026
bb7f0f98
AS
12027 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12028 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12029 return -EINVAL;
12030
3f50f132
JF
12031 /* pointer types do not carry 32-bit bounds at the moment. */
12032 __mark_reg32_unbounded(dst_reg);
12033
7fedb63a
DB
12034 if (sanitize_needed(opcode)) {
12035 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 12036 &info, false);
a6aaece0
DB
12037 if (ret < 0)
12038 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 12039 }
a6aaece0 12040
f1174f77
EC
12041 switch (opcode) {
12042 case BPF_ADD:
12043 /* We can take a fixed offset as long as it doesn't overflow
12044 * the s32 'off' field
969bf05e 12045 */
b03c9f9f
EC
12046 if (known && (ptr_reg->off + smin_val ==
12047 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 12048 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
12049 dst_reg->smin_value = smin_ptr;
12050 dst_reg->smax_value = smax_ptr;
12051 dst_reg->umin_value = umin_ptr;
12052 dst_reg->umax_value = umax_ptr;
f1174f77 12053 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 12054 dst_reg->off = ptr_reg->off + smin_val;
0962590e 12055 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
12056 break;
12057 }
f1174f77
EC
12058 /* A new variable offset is created. Note that off_reg->off
12059 * == 0, since it's a scalar.
12060 * dst_reg gets the pointer type and since some positive
12061 * integer value was added to the pointer, give it a new 'id'
12062 * if it's a PTR_TO_PACKET.
12063 * this creates a new 'base' pointer, off_reg (variable) gets
12064 * added into the variable offset, and we copy the fixed offset
12065 * from ptr_reg.
969bf05e 12066 */
b03c9f9f
EC
12067 if (signed_add_overflows(smin_ptr, smin_val) ||
12068 signed_add_overflows(smax_ptr, smax_val)) {
12069 dst_reg->smin_value = S64_MIN;
12070 dst_reg->smax_value = S64_MAX;
12071 } else {
12072 dst_reg->smin_value = smin_ptr + smin_val;
12073 dst_reg->smax_value = smax_ptr + smax_val;
12074 }
12075 if (umin_ptr + umin_val < umin_ptr ||
12076 umax_ptr + umax_val < umax_ptr) {
12077 dst_reg->umin_value = 0;
12078 dst_reg->umax_value = U64_MAX;
12079 } else {
12080 dst_reg->umin_value = umin_ptr + umin_val;
12081 dst_reg->umax_value = umax_ptr + umax_val;
12082 }
f1174f77
EC
12083 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12084 dst_reg->off = ptr_reg->off;
0962590e 12085 dst_reg->raw = ptr_reg->raw;
de8f3a83 12086 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
12087 dst_reg->id = ++env->id_gen;
12088 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 12089 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
12090 }
12091 break;
12092 case BPF_SUB:
12093 if (dst_reg == off_reg) {
12094 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
12095 verbose(env, "R%d tried to subtract pointer from scalar\n",
12096 dst);
f1174f77
EC
12097 return -EACCES;
12098 }
12099 /* We don't allow subtraction from FP, because (according to
12100 * test_verifier.c test "invalid fp arithmetic", JITs might not
12101 * be able to deal with it.
969bf05e 12102 */
f1174f77 12103 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
12104 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12105 dst);
f1174f77
EC
12106 return -EACCES;
12107 }
b03c9f9f
EC
12108 if (known && (ptr_reg->off - smin_val ==
12109 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 12110 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
12111 dst_reg->smin_value = smin_ptr;
12112 dst_reg->smax_value = smax_ptr;
12113 dst_reg->umin_value = umin_ptr;
12114 dst_reg->umax_value = umax_ptr;
f1174f77
EC
12115 dst_reg->var_off = ptr_reg->var_off;
12116 dst_reg->id = ptr_reg->id;
b03c9f9f 12117 dst_reg->off = ptr_reg->off - smin_val;
0962590e 12118 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
12119 break;
12120 }
f1174f77
EC
12121 /* A new variable offset is created. If the subtrahend is known
12122 * nonnegative, then any reg->range we had before is still good.
969bf05e 12123 */
b03c9f9f
EC
12124 if (signed_sub_overflows(smin_ptr, smax_val) ||
12125 signed_sub_overflows(smax_ptr, smin_val)) {
12126 /* Overflow possible, we know nothing */
12127 dst_reg->smin_value = S64_MIN;
12128 dst_reg->smax_value = S64_MAX;
12129 } else {
12130 dst_reg->smin_value = smin_ptr - smax_val;
12131 dst_reg->smax_value = smax_ptr - smin_val;
12132 }
12133 if (umin_ptr < umax_val) {
12134 /* Overflow possible, we know nothing */
12135 dst_reg->umin_value = 0;
12136 dst_reg->umax_value = U64_MAX;
12137 } else {
12138 /* Cannot overflow (as long as bounds are consistent) */
12139 dst_reg->umin_value = umin_ptr - umax_val;
12140 dst_reg->umax_value = umax_ptr - umin_val;
12141 }
f1174f77
EC
12142 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12143 dst_reg->off = ptr_reg->off;
0962590e 12144 dst_reg->raw = ptr_reg->raw;
de8f3a83 12145 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
12146 dst_reg->id = ++env->id_gen;
12147 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 12148 if (smin_val < 0)
22dc4a0f 12149 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 12150 }
f1174f77
EC
12151 break;
12152 case BPF_AND:
12153 case BPF_OR:
12154 case BPF_XOR:
82abbf8d
AS
12155 /* bitwise ops on pointers are troublesome, prohibit. */
12156 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12157 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
12158 return -EACCES;
12159 default:
12160 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
12161 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12162 dst, bpf_alu_string[opcode >> 4]);
f1174f77 12163 return -EACCES;
43188702
JF
12164 }
12165
bb7f0f98
AS
12166 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12167 return -EINVAL;
3844d153 12168 reg_bounds_sync(dst_reg);
073815b7
DB
12169 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12170 return -EACCES;
7fedb63a
DB
12171 if (sanitize_needed(opcode)) {
12172 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 12173 &info, true);
7fedb63a
DB
12174 if (ret < 0)
12175 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
12176 }
12177
43188702
JF
12178 return 0;
12179}
12180
3f50f132
JF
12181static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12182 struct bpf_reg_state *src_reg)
12183{
12184 s32 smin_val = src_reg->s32_min_value;
12185 s32 smax_val = src_reg->s32_max_value;
12186 u32 umin_val = src_reg->u32_min_value;
12187 u32 umax_val = src_reg->u32_max_value;
12188
12189 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12190 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12191 dst_reg->s32_min_value = S32_MIN;
12192 dst_reg->s32_max_value = S32_MAX;
12193 } else {
12194 dst_reg->s32_min_value += smin_val;
12195 dst_reg->s32_max_value += smax_val;
12196 }
12197 if (dst_reg->u32_min_value + umin_val < umin_val ||
12198 dst_reg->u32_max_value + umax_val < umax_val) {
12199 dst_reg->u32_min_value = 0;
12200 dst_reg->u32_max_value = U32_MAX;
12201 } else {
12202 dst_reg->u32_min_value += umin_val;
12203 dst_reg->u32_max_value += umax_val;
12204 }
12205}
12206
07cd2631
JF
12207static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12208 struct bpf_reg_state *src_reg)
12209{
12210 s64 smin_val = src_reg->smin_value;
12211 s64 smax_val = src_reg->smax_value;
12212 u64 umin_val = src_reg->umin_value;
12213 u64 umax_val = src_reg->umax_value;
12214
12215 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12216 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12217 dst_reg->smin_value = S64_MIN;
12218 dst_reg->smax_value = S64_MAX;
12219 } else {
12220 dst_reg->smin_value += smin_val;
12221 dst_reg->smax_value += smax_val;
12222 }
12223 if (dst_reg->umin_value + umin_val < umin_val ||
12224 dst_reg->umax_value + umax_val < umax_val) {
12225 dst_reg->umin_value = 0;
12226 dst_reg->umax_value = U64_MAX;
12227 } else {
12228 dst_reg->umin_value += umin_val;
12229 dst_reg->umax_value += umax_val;
12230 }
3f50f132
JF
12231}
12232
12233static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12234 struct bpf_reg_state *src_reg)
12235{
12236 s32 smin_val = src_reg->s32_min_value;
12237 s32 smax_val = src_reg->s32_max_value;
12238 u32 umin_val = src_reg->u32_min_value;
12239 u32 umax_val = src_reg->u32_max_value;
12240
12241 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12242 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12243 /* Overflow possible, we know nothing */
12244 dst_reg->s32_min_value = S32_MIN;
12245 dst_reg->s32_max_value = S32_MAX;
12246 } else {
12247 dst_reg->s32_min_value -= smax_val;
12248 dst_reg->s32_max_value -= smin_val;
12249 }
12250 if (dst_reg->u32_min_value < umax_val) {
12251 /* Overflow possible, we know nothing */
12252 dst_reg->u32_min_value = 0;
12253 dst_reg->u32_max_value = U32_MAX;
12254 } else {
12255 /* Cannot overflow (as long as bounds are consistent) */
12256 dst_reg->u32_min_value -= umax_val;
12257 dst_reg->u32_max_value -= umin_val;
12258 }
07cd2631
JF
12259}
12260
12261static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12262 struct bpf_reg_state *src_reg)
12263{
12264 s64 smin_val = src_reg->smin_value;
12265 s64 smax_val = src_reg->smax_value;
12266 u64 umin_val = src_reg->umin_value;
12267 u64 umax_val = src_reg->umax_value;
12268
12269 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12270 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12271 /* Overflow possible, we know nothing */
12272 dst_reg->smin_value = S64_MIN;
12273 dst_reg->smax_value = S64_MAX;
12274 } else {
12275 dst_reg->smin_value -= smax_val;
12276 dst_reg->smax_value -= smin_val;
12277 }
12278 if (dst_reg->umin_value < umax_val) {
12279 /* Overflow possible, we know nothing */
12280 dst_reg->umin_value = 0;
12281 dst_reg->umax_value = U64_MAX;
12282 } else {
12283 /* Cannot overflow (as long as bounds are consistent) */
12284 dst_reg->umin_value -= umax_val;
12285 dst_reg->umax_value -= umin_val;
12286 }
3f50f132
JF
12287}
12288
12289static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12290 struct bpf_reg_state *src_reg)
12291{
12292 s32 smin_val = src_reg->s32_min_value;
12293 u32 umin_val = src_reg->u32_min_value;
12294 u32 umax_val = src_reg->u32_max_value;
12295
12296 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12297 /* Ain't nobody got time to multiply that sign */
12298 __mark_reg32_unbounded(dst_reg);
12299 return;
12300 }
12301 /* Both values are positive, so we can work with unsigned and
12302 * copy the result to signed (unless it exceeds S32_MAX).
12303 */
12304 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12305 /* Potential overflow, we know nothing */
12306 __mark_reg32_unbounded(dst_reg);
12307 return;
12308 }
12309 dst_reg->u32_min_value *= umin_val;
12310 dst_reg->u32_max_value *= umax_val;
12311 if (dst_reg->u32_max_value > S32_MAX) {
12312 /* Overflow possible, we know nothing */
12313 dst_reg->s32_min_value = S32_MIN;
12314 dst_reg->s32_max_value = S32_MAX;
12315 } else {
12316 dst_reg->s32_min_value = dst_reg->u32_min_value;
12317 dst_reg->s32_max_value = dst_reg->u32_max_value;
12318 }
07cd2631
JF
12319}
12320
12321static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12322 struct bpf_reg_state *src_reg)
12323{
12324 s64 smin_val = src_reg->smin_value;
12325 u64 umin_val = src_reg->umin_value;
12326 u64 umax_val = src_reg->umax_value;
12327
07cd2631
JF
12328 if (smin_val < 0 || dst_reg->smin_value < 0) {
12329 /* Ain't nobody got time to multiply that sign */
3f50f132 12330 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
12331 return;
12332 }
12333 /* Both values are positive, so we can work with unsigned and
12334 * copy the result to signed (unless it exceeds S64_MAX).
12335 */
12336 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12337 /* Potential overflow, we know nothing */
3f50f132 12338 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
12339 return;
12340 }
12341 dst_reg->umin_value *= umin_val;
12342 dst_reg->umax_value *= umax_val;
12343 if (dst_reg->umax_value > S64_MAX) {
12344 /* Overflow possible, we know nothing */
12345 dst_reg->smin_value = S64_MIN;
12346 dst_reg->smax_value = S64_MAX;
12347 } else {
12348 dst_reg->smin_value = dst_reg->umin_value;
12349 dst_reg->smax_value = dst_reg->umax_value;
12350 }
12351}
12352
3f50f132
JF
12353static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12354 struct bpf_reg_state *src_reg)
12355{
12356 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12357 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12358 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12359 s32 smin_val = src_reg->s32_min_value;
12360 u32 umax_val = src_reg->u32_max_value;
12361
049c4e13
DB
12362 if (src_known && dst_known) {
12363 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 12364 return;
049c4e13 12365 }
3f50f132
JF
12366
12367 /* We get our minimum from the var_off, since that's inherently
12368 * bitwise. Our maximum is the minimum of the operands' maxima.
12369 */
12370 dst_reg->u32_min_value = var32_off.value;
12371 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12372 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12373 /* Lose signed bounds when ANDing negative numbers,
12374 * ain't nobody got time for that.
12375 */
12376 dst_reg->s32_min_value = S32_MIN;
12377 dst_reg->s32_max_value = S32_MAX;
12378 } else {
12379 /* ANDing two positives gives a positive, so safe to
12380 * cast result into s64.
12381 */
12382 dst_reg->s32_min_value = dst_reg->u32_min_value;
12383 dst_reg->s32_max_value = dst_reg->u32_max_value;
12384 }
3f50f132
JF
12385}
12386
07cd2631
JF
12387static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12388 struct bpf_reg_state *src_reg)
12389{
3f50f132
JF
12390 bool src_known = tnum_is_const(src_reg->var_off);
12391 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
12392 s64 smin_val = src_reg->smin_value;
12393 u64 umax_val = src_reg->umax_value;
12394
3f50f132 12395 if (src_known && dst_known) {
4fbb38a3 12396 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
12397 return;
12398 }
12399
07cd2631
JF
12400 /* We get our minimum from the var_off, since that's inherently
12401 * bitwise. Our maximum is the minimum of the operands' maxima.
12402 */
07cd2631
JF
12403 dst_reg->umin_value = dst_reg->var_off.value;
12404 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12405 if (dst_reg->smin_value < 0 || smin_val < 0) {
12406 /* Lose signed bounds when ANDing negative numbers,
12407 * ain't nobody got time for that.
12408 */
12409 dst_reg->smin_value = S64_MIN;
12410 dst_reg->smax_value = S64_MAX;
12411 } else {
12412 /* ANDing two positives gives a positive, so safe to
12413 * cast result into s64.
12414 */
12415 dst_reg->smin_value = dst_reg->umin_value;
12416 dst_reg->smax_value = dst_reg->umax_value;
12417 }
12418 /* We may learn something more from the var_off */
12419 __update_reg_bounds(dst_reg);
12420}
12421
3f50f132
JF
12422static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12423 struct bpf_reg_state *src_reg)
12424{
12425 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12426 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12427 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
12428 s32 smin_val = src_reg->s32_min_value;
12429 u32 umin_val = src_reg->u32_min_value;
3f50f132 12430
049c4e13
DB
12431 if (src_known && dst_known) {
12432 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 12433 return;
049c4e13 12434 }
3f50f132
JF
12435
12436 /* We get our maximum from the var_off, and our minimum is the
12437 * maximum of the operands' minima
12438 */
12439 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12440 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12441 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12442 /* Lose signed bounds when ORing negative numbers,
12443 * ain't nobody got time for that.
12444 */
12445 dst_reg->s32_min_value = S32_MIN;
12446 dst_reg->s32_max_value = S32_MAX;
12447 } else {
12448 /* ORing two positives gives a positive, so safe to
12449 * cast result into s64.
12450 */
5b9fbeb7
DB
12451 dst_reg->s32_min_value = dst_reg->u32_min_value;
12452 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
12453 }
12454}
12455
07cd2631
JF
12456static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12457 struct bpf_reg_state *src_reg)
12458{
3f50f132
JF
12459 bool src_known = tnum_is_const(src_reg->var_off);
12460 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
12461 s64 smin_val = src_reg->smin_value;
12462 u64 umin_val = src_reg->umin_value;
12463
3f50f132 12464 if (src_known && dst_known) {
4fbb38a3 12465 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
12466 return;
12467 }
12468
07cd2631
JF
12469 /* We get our maximum from the var_off, and our minimum is the
12470 * maximum of the operands' minima
12471 */
07cd2631
JF
12472 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12473 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12474 if (dst_reg->smin_value < 0 || smin_val < 0) {
12475 /* Lose signed bounds when ORing negative numbers,
12476 * ain't nobody got time for that.
12477 */
12478 dst_reg->smin_value = S64_MIN;
12479 dst_reg->smax_value = S64_MAX;
12480 } else {
12481 /* ORing two positives gives a positive, so safe to
12482 * cast result into s64.
12483 */
12484 dst_reg->smin_value = dst_reg->umin_value;
12485 dst_reg->smax_value = dst_reg->umax_value;
12486 }
12487 /* We may learn something more from the var_off */
12488 __update_reg_bounds(dst_reg);
12489}
12490
2921c90d
YS
12491static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12492 struct bpf_reg_state *src_reg)
12493{
12494 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12495 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12496 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12497 s32 smin_val = src_reg->s32_min_value;
12498
049c4e13
DB
12499 if (src_known && dst_known) {
12500 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 12501 return;
049c4e13 12502 }
2921c90d
YS
12503
12504 /* We get both minimum and maximum from the var32_off. */
12505 dst_reg->u32_min_value = var32_off.value;
12506 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12507
12508 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12509 /* XORing two positive sign numbers gives a positive,
12510 * so safe to cast u32 result into s32.
12511 */
12512 dst_reg->s32_min_value = dst_reg->u32_min_value;
12513 dst_reg->s32_max_value = dst_reg->u32_max_value;
12514 } else {
12515 dst_reg->s32_min_value = S32_MIN;
12516 dst_reg->s32_max_value = S32_MAX;
12517 }
12518}
12519
12520static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12521 struct bpf_reg_state *src_reg)
12522{
12523 bool src_known = tnum_is_const(src_reg->var_off);
12524 bool dst_known = tnum_is_const(dst_reg->var_off);
12525 s64 smin_val = src_reg->smin_value;
12526
12527 if (src_known && dst_known) {
12528 /* dst_reg->var_off.value has been updated earlier */
12529 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12530 return;
12531 }
12532
12533 /* We get both minimum and maximum from the var_off. */
12534 dst_reg->umin_value = dst_reg->var_off.value;
12535 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12536
12537 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12538 /* XORing two positive sign numbers gives a positive,
12539 * so safe to cast u64 result into s64.
12540 */
12541 dst_reg->smin_value = dst_reg->umin_value;
12542 dst_reg->smax_value = dst_reg->umax_value;
12543 } else {
12544 dst_reg->smin_value = S64_MIN;
12545 dst_reg->smax_value = S64_MAX;
12546 }
12547
12548 __update_reg_bounds(dst_reg);
12549}
12550
3f50f132
JF
12551static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12552 u64 umin_val, u64 umax_val)
07cd2631 12553{
07cd2631
JF
12554 /* We lose all sign bit information (except what we can pick
12555 * up from var_off)
12556 */
3f50f132
JF
12557 dst_reg->s32_min_value = S32_MIN;
12558 dst_reg->s32_max_value = S32_MAX;
12559 /* If we might shift our top bit out, then we know nothing */
12560 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12561 dst_reg->u32_min_value = 0;
12562 dst_reg->u32_max_value = U32_MAX;
12563 } else {
12564 dst_reg->u32_min_value <<= umin_val;
12565 dst_reg->u32_max_value <<= umax_val;
12566 }
12567}
12568
12569static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12570 struct bpf_reg_state *src_reg)
12571{
12572 u32 umax_val = src_reg->u32_max_value;
12573 u32 umin_val = src_reg->u32_min_value;
12574 /* u32 alu operation will zext upper bits */
12575 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12576
12577 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12578 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12579 /* Not required but being careful mark reg64 bounds as unknown so
12580 * that we are forced to pick them up from tnum and zext later and
12581 * if some path skips this step we are still safe.
12582 */
12583 __mark_reg64_unbounded(dst_reg);
12584 __update_reg32_bounds(dst_reg);
12585}
12586
12587static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12588 u64 umin_val, u64 umax_val)
12589{
12590 /* Special case <<32 because it is a common compiler pattern to sign
12591 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12592 * positive we know this shift will also be positive so we can track
12593 * bounds correctly. Otherwise we lose all sign bit information except
12594 * what we can pick up from var_off. Perhaps we can generalize this
12595 * later to shifts of any length.
12596 */
12597 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12598 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12599 else
12600 dst_reg->smax_value = S64_MAX;
12601
12602 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12603 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12604 else
12605 dst_reg->smin_value = S64_MIN;
12606
07cd2631
JF
12607 /* If we might shift our top bit out, then we know nothing */
12608 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12609 dst_reg->umin_value = 0;
12610 dst_reg->umax_value = U64_MAX;
12611 } else {
12612 dst_reg->umin_value <<= umin_val;
12613 dst_reg->umax_value <<= umax_val;
12614 }
3f50f132
JF
12615}
12616
12617static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12618 struct bpf_reg_state *src_reg)
12619{
12620 u64 umax_val = src_reg->umax_value;
12621 u64 umin_val = src_reg->umin_value;
12622
12623 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12624 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12625 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12626
07cd2631
JF
12627 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12628 /* We may learn something more from the var_off */
12629 __update_reg_bounds(dst_reg);
12630}
12631
3f50f132
JF
12632static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12633 struct bpf_reg_state *src_reg)
12634{
12635 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12636 u32 umax_val = src_reg->u32_max_value;
12637 u32 umin_val = src_reg->u32_min_value;
12638
12639 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12640 * be negative, then either:
12641 * 1) src_reg might be zero, so the sign bit of the result is
12642 * unknown, so we lose our signed bounds
12643 * 2) it's known negative, thus the unsigned bounds capture the
12644 * signed bounds
12645 * 3) the signed bounds cross zero, so they tell us nothing
12646 * about the result
12647 * If the value in dst_reg is known nonnegative, then again the
18b24d78 12648 * unsigned bounds capture the signed bounds.
3f50f132
JF
12649 * Thus, in all cases it suffices to blow away our signed bounds
12650 * and rely on inferring new ones from the unsigned bounds and
12651 * var_off of the result.
12652 */
12653 dst_reg->s32_min_value = S32_MIN;
12654 dst_reg->s32_max_value = S32_MAX;
12655
12656 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12657 dst_reg->u32_min_value >>= umax_val;
12658 dst_reg->u32_max_value >>= umin_val;
12659
12660 __mark_reg64_unbounded(dst_reg);
12661 __update_reg32_bounds(dst_reg);
12662}
12663
07cd2631
JF
12664static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12665 struct bpf_reg_state *src_reg)
12666{
12667 u64 umax_val = src_reg->umax_value;
12668 u64 umin_val = src_reg->umin_value;
12669
12670 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12671 * be negative, then either:
12672 * 1) src_reg might be zero, so the sign bit of the result is
12673 * unknown, so we lose our signed bounds
12674 * 2) it's known negative, thus the unsigned bounds capture the
12675 * signed bounds
12676 * 3) the signed bounds cross zero, so they tell us nothing
12677 * about the result
12678 * If the value in dst_reg is known nonnegative, then again the
18b24d78 12679 * unsigned bounds capture the signed bounds.
07cd2631
JF
12680 * Thus, in all cases it suffices to blow away our signed bounds
12681 * and rely on inferring new ones from the unsigned bounds and
12682 * var_off of the result.
12683 */
12684 dst_reg->smin_value = S64_MIN;
12685 dst_reg->smax_value = S64_MAX;
12686 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12687 dst_reg->umin_value >>= umax_val;
12688 dst_reg->umax_value >>= umin_val;
3f50f132
JF
12689
12690 /* Its not easy to operate on alu32 bounds here because it depends
12691 * on bits being shifted in. Take easy way out and mark unbounded
12692 * so we can recalculate later from tnum.
12693 */
12694 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
12695 __update_reg_bounds(dst_reg);
12696}
12697
3f50f132
JF
12698static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12699 struct bpf_reg_state *src_reg)
07cd2631 12700{
3f50f132 12701 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
12702
12703 /* Upon reaching here, src_known is true and
12704 * umax_val is equal to umin_val.
12705 */
3f50f132
JF
12706 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12707 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 12708
3f50f132
JF
12709 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12710
12711 /* blow away the dst_reg umin_value/umax_value and rely on
12712 * dst_reg var_off to refine the result.
12713 */
12714 dst_reg->u32_min_value = 0;
12715 dst_reg->u32_max_value = U32_MAX;
12716
12717 __mark_reg64_unbounded(dst_reg);
12718 __update_reg32_bounds(dst_reg);
12719}
12720
12721static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12722 struct bpf_reg_state *src_reg)
12723{
12724 u64 umin_val = src_reg->umin_value;
12725
12726 /* Upon reaching here, src_known is true and umax_val is equal
12727 * to umin_val.
12728 */
12729 dst_reg->smin_value >>= umin_val;
12730 dst_reg->smax_value >>= umin_val;
12731
12732 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
12733
12734 /* blow away the dst_reg umin_value/umax_value and rely on
12735 * dst_reg var_off to refine the result.
12736 */
12737 dst_reg->umin_value = 0;
12738 dst_reg->umax_value = U64_MAX;
3f50f132
JF
12739
12740 /* Its not easy to operate on alu32 bounds here because it depends
12741 * on bits being shifted in from upper 32-bits. Take easy way out
12742 * and mark unbounded so we can recalculate later from tnum.
12743 */
12744 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
12745 __update_reg_bounds(dst_reg);
12746}
12747
468f6eaf
JH
12748/* WARNING: This function does calculations on 64-bit values, but the actual
12749 * execution may occur on 32-bit values. Therefore, things like bitshifts
12750 * need extra checks in the 32-bit case.
12751 */
f1174f77
EC
12752static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12753 struct bpf_insn *insn,
12754 struct bpf_reg_state *dst_reg,
12755 struct bpf_reg_state src_reg)
969bf05e 12756{
638f5b90 12757 struct bpf_reg_state *regs = cur_regs(env);
48461135 12758 u8 opcode = BPF_OP(insn->code);
b0b3fb67 12759 bool src_known;
b03c9f9f
EC
12760 s64 smin_val, smax_val;
12761 u64 umin_val, umax_val;
3f50f132
JF
12762 s32 s32_min_val, s32_max_val;
12763 u32 u32_min_val, u32_max_val;
468f6eaf 12764 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 12765 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 12766 int ret;
b799207e 12767
b03c9f9f
EC
12768 smin_val = src_reg.smin_value;
12769 smax_val = src_reg.smax_value;
12770 umin_val = src_reg.umin_value;
12771 umax_val = src_reg.umax_value;
f23cc643 12772
3f50f132
JF
12773 s32_min_val = src_reg.s32_min_value;
12774 s32_max_val = src_reg.s32_max_value;
12775 u32_min_val = src_reg.u32_min_value;
12776 u32_max_val = src_reg.u32_max_value;
12777
12778 if (alu32) {
12779 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
12780 if ((src_known &&
12781 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12782 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12783 /* Taint dst register if offset had invalid bounds
12784 * derived from e.g. dead branches.
12785 */
12786 __mark_reg_unknown(env, dst_reg);
12787 return 0;
12788 }
12789 } else {
12790 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
12791 if ((src_known &&
12792 (smin_val != smax_val || umin_val != umax_val)) ||
12793 smin_val > smax_val || umin_val > umax_val) {
12794 /* Taint dst register if offset had invalid bounds
12795 * derived from e.g. dead branches.
12796 */
12797 __mark_reg_unknown(env, dst_reg);
12798 return 0;
12799 }
6f16101e
DB
12800 }
12801
bb7f0f98
AS
12802 if (!src_known &&
12803 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 12804 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
12805 return 0;
12806 }
12807
f5288193
DB
12808 if (sanitize_needed(opcode)) {
12809 ret = sanitize_val_alu(env, insn);
12810 if (ret < 0)
12811 return sanitize_err(env, insn, ret, NULL, NULL);
12812 }
12813
3f50f132
JF
12814 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12815 * There are two classes of instructions: The first class we track both
12816 * alu32 and alu64 sign/unsigned bounds independently this provides the
12817 * greatest amount of precision when alu operations are mixed with jmp32
12818 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12819 * and BPF_OR. This is possible because these ops have fairly easy to
12820 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12821 * See alu32 verifier tests for examples. The second class of
12822 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12823 * with regards to tracking sign/unsigned bounds because the bits may
12824 * cross subreg boundaries in the alu64 case. When this happens we mark
12825 * the reg unbounded in the subreg bound space and use the resulting
12826 * tnum to calculate an approximation of the sign/unsigned bounds.
12827 */
48461135
JB
12828 switch (opcode) {
12829 case BPF_ADD:
3f50f132 12830 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 12831 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 12832 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
12833 break;
12834 case BPF_SUB:
3f50f132 12835 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 12836 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 12837 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
12838 break;
12839 case BPF_MUL:
3f50f132
JF
12840 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12841 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 12842 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
12843 break;
12844 case BPF_AND:
3f50f132
JF
12845 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12846 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 12847 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
12848 break;
12849 case BPF_OR:
3f50f132
JF
12850 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12851 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 12852 scalar_min_max_or(dst_reg, &src_reg);
48461135 12853 break;
2921c90d
YS
12854 case BPF_XOR:
12855 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12856 scalar32_min_max_xor(dst_reg, &src_reg);
12857 scalar_min_max_xor(dst_reg, &src_reg);
12858 break;
48461135 12859 case BPF_LSH:
468f6eaf
JH
12860 if (umax_val >= insn_bitness) {
12861 /* Shifts greater than 31 or 63 are undefined.
12862 * This includes shifts by a negative number.
b03c9f9f 12863 */
61bd5218 12864 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
12865 break;
12866 }
3f50f132
JF
12867 if (alu32)
12868 scalar32_min_max_lsh(dst_reg, &src_reg);
12869 else
12870 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
12871 break;
12872 case BPF_RSH:
468f6eaf
JH
12873 if (umax_val >= insn_bitness) {
12874 /* Shifts greater than 31 or 63 are undefined.
12875 * This includes shifts by a negative number.
b03c9f9f 12876 */
61bd5218 12877 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
12878 break;
12879 }
3f50f132
JF
12880 if (alu32)
12881 scalar32_min_max_rsh(dst_reg, &src_reg);
12882 else
12883 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 12884 break;
9cbe1f5a
YS
12885 case BPF_ARSH:
12886 if (umax_val >= insn_bitness) {
12887 /* Shifts greater than 31 or 63 are undefined.
12888 * This includes shifts by a negative number.
12889 */
12890 mark_reg_unknown(env, regs, insn->dst_reg);
12891 break;
12892 }
3f50f132
JF
12893 if (alu32)
12894 scalar32_min_max_arsh(dst_reg, &src_reg);
12895 else
12896 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 12897 break;
48461135 12898 default:
61bd5218 12899 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
12900 break;
12901 }
12902
3f50f132
JF
12903 /* ALU32 ops are zero extended into 64bit register */
12904 if (alu32)
12905 zext_32_to_64(dst_reg);
3844d153 12906 reg_bounds_sync(dst_reg);
f1174f77
EC
12907 return 0;
12908}
12909
12910/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12911 * and var_off.
12912 */
12913static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12914 struct bpf_insn *insn)
12915{
f4d7e40a
AS
12916 struct bpf_verifier_state *vstate = env->cur_state;
12917 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12918 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
12919 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12920 u8 opcode = BPF_OP(insn->code);
b5dc0163 12921 int err;
f1174f77
EC
12922
12923 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
12924 src_reg = NULL;
12925 if (dst_reg->type != SCALAR_VALUE)
12926 ptr_reg = dst_reg;
75748837
AS
12927 else
12928 /* Make sure ID is cleared otherwise dst_reg min/max could be
12929 * incorrectly propagated into other registers by find_equal_scalars()
12930 */
12931 dst_reg->id = 0;
f1174f77
EC
12932 if (BPF_SRC(insn->code) == BPF_X) {
12933 src_reg = &regs[insn->src_reg];
f1174f77
EC
12934 if (src_reg->type != SCALAR_VALUE) {
12935 if (dst_reg->type != SCALAR_VALUE) {
12936 /* Combining two pointers by any ALU op yields
82abbf8d
AS
12937 * an arbitrary scalar. Disallow all math except
12938 * pointer subtraction
f1174f77 12939 */
dd066823 12940 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
12941 mark_reg_unknown(env, regs, insn->dst_reg);
12942 return 0;
f1174f77 12943 }
82abbf8d
AS
12944 verbose(env, "R%d pointer %s pointer prohibited\n",
12945 insn->dst_reg,
12946 bpf_alu_string[opcode >> 4]);
12947 return -EACCES;
f1174f77
EC
12948 } else {
12949 /* scalar += pointer
12950 * This is legal, but we have to reverse our
12951 * src/dest handling in computing the range
12952 */
b5dc0163
AS
12953 err = mark_chain_precision(env, insn->dst_reg);
12954 if (err)
12955 return err;
82abbf8d
AS
12956 return adjust_ptr_min_max_vals(env, insn,
12957 src_reg, dst_reg);
f1174f77
EC
12958 }
12959 } else if (ptr_reg) {
12960 /* pointer += scalar */
b5dc0163
AS
12961 err = mark_chain_precision(env, insn->src_reg);
12962 if (err)
12963 return err;
82abbf8d
AS
12964 return adjust_ptr_min_max_vals(env, insn,
12965 dst_reg, src_reg);
a3b666bf
AN
12966 } else if (dst_reg->precise) {
12967 /* if dst_reg is precise, src_reg should be precise as well */
12968 err = mark_chain_precision(env, insn->src_reg);
12969 if (err)
12970 return err;
f1174f77
EC
12971 }
12972 } else {
12973 /* Pretend the src is a reg with a known value, since we only
12974 * need to be able to read from this state.
12975 */
12976 off_reg.type = SCALAR_VALUE;
b03c9f9f 12977 __mark_reg_known(&off_reg, insn->imm);
f1174f77 12978 src_reg = &off_reg;
82abbf8d
AS
12979 if (ptr_reg) /* pointer += K */
12980 return adjust_ptr_min_max_vals(env, insn,
12981 ptr_reg, src_reg);
f1174f77
EC
12982 }
12983
12984 /* Got here implies adding two SCALAR_VALUEs */
12985 if (WARN_ON_ONCE(ptr_reg)) {
0f55f9ed 12986 print_verifier_state(env, state, true);
61bd5218 12987 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
12988 return -EINVAL;
12989 }
12990 if (WARN_ON(!src_reg)) {
0f55f9ed 12991 print_verifier_state(env, state, true);
61bd5218 12992 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
12993 return -EINVAL;
12994 }
12995 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
12996}
12997
17a52670 12998/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 12999static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 13000{
638f5b90 13001 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
13002 u8 opcode = BPF_OP(insn->code);
13003 int err;
13004
13005 if (opcode == BPF_END || opcode == BPF_NEG) {
13006 if (opcode == BPF_NEG) {
395e942d 13007 if (BPF_SRC(insn->code) != BPF_K ||
17a52670
AS
13008 insn->src_reg != BPF_REG_0 ||
13009 insn->off != 0 || insn->imm != 0) {
61bd5218 13010 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
13011 return -EINVAL;
13012 }
13013 } else {
13014 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
13015 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13016 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 13017 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
13018 return -EINVAL;
13019 }
13020 }
13021
13022 /* check src operand */
dc503a8a 13023 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13024 if (err)
13025 return err;
13026
1be7f75d 13027 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 13028 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
13029 insn->dst_reg);
13030 return -EACCES;
13031 }
13032
17a52670 13033 /* check dest operand */
dc503a8a 13034 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
13035 if (err)
13036 return err;
13037
13038 } else if (opcode == BPF_MOV) {
13039
13040 if (BPF_SRC(insn->code) == BPF_X) {
13041 if (insn->imm != 0 || insn->off != 0) {
61bd5218 13042 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
13043 return -EINVAL;
13044 }
13045
13046 /* check src operand */
dc503a8a 13047 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13048 if (err)
13049 return err;
13050 } else {
13051 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 13052 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
13053 return -EINVAL;
13054 }
13055 }
13056
fbeb1603
AF
13057 /* check dest operand, mark as required later */
13058 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
13059 if (err)
13060 return err;
13061
13062 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
13063 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13064 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
1ffc85d9
EZ
13065 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13066 !tnum_is_const(src_reg->var_off);
e434b8cd 13067
17a52670
AS
13068 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13069 /* case: R1 = R2
13070 * copy register state to dest reg
13071 */
1ffc85d9 13072 if (need_id)
75748837
AS
13073 /* Assign src and dst registers the same ID
13074 * that will be used by find_equal_scalars()
13075 * to propagate min/max range.
13076 */
13077 src_reg->id = ++env->id_gen;
71f656a5 13078 copy_register_state(dst_reg, src_reg);
e434b8cd 13079 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 13080 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 13081 } else {
f1174f77 13082 /* R1 = (u32) R2 */
1be7f75d 13083 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
13084 verbose(env,
13085 "R%d partial copy of pointer\n",
1be7f75d
AS
13086 insn->src_reg);
13087 return -EACCES;
e434b8cd 13088 } else if (src_reg->type == SCALAR_VALUE) {
3be49f79
YS
13089 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13090
1ffc85d9 13091 if (is_src_reg_u32 && need_id)
3be49f79 13092 src_reg->id = ++env->id_gen;
71f656a5 13093 copy_register_state(dst_reg, src_reg);
3be49f79 13094 /* Make sure ID is cleared if src_reg is not in u32 range otherwise
75748837
AS
13095 * dst_reg min/max could be incorrectly
13096 * propagated into src_reg by find_equal_scalars()
13097 */
3be49f79
YS
13098 if (!is_src_reg_u32)
13099 dst_reg->id = 0;
e434b8cd 13100 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 13101 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
13102 } else {
13103 mark_reg_unknown(env, regs,
13104 insn->dst_reg);
1be7f75d 13105 }
3f50f132 13106 zext_32_to_64(dst_reg);
3844d153 13107 reg_bounds_sync(dst_reg);
17a52670
AS
13108 }
13109 } else {
13110 /* case: R = imm
13111 * remember the value we stored into this reg
13112 */
fbeb1603
AF
13113 /* clear any state __mark_reg_known doesn't set */
13114 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 13115 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
13116 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13117 __mark_reg_known(regs + insn->dst_reg,
13118 insn->imm);
13119 } else {
13120 __mark_reg_known(regs + insn->dst_reg,
13121 (u32)insn->imm);
13122 }
17a52670
AS
13123 }
13124
13125 } else if (opcode > BPF_END) {
61bd5218 13126 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
13127 return -EINVAL;
13128
13129 } else { /* all other ALU ops: and, sub, xor, add, ... */
13130
17a52670
AS
13131 if (BPF_SRC(insn->code) == BPF_X) {
13132 if (insn->imm != 0 || insn->off != 0) {
61bd5218 13133 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
13134 return -EINVAL;
13135 }
13136 /* check src1 operand */
dc503a8a 13137 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13138 if (err)
13139 return err;
13140 } else {
13141 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 13142 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
13143 return -EINVAL;
13144 }
13145 }
13146
13147 /* check src2 operand */
dc503a8a 13148 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13149 if (err)
13150 return err;
13151
13152 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13153 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 13154 verbose(env, "div by zero\n");
17a52670
AS
13155 return -EINVAL;
13156 }
13157
229394e8
RV
13158 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13159 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13160 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13161
13162 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 13163 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
13164 return -EINVAL;
13165 }
13166 }
13167
1a0dc1ac 13168 /* check dest operand */
dc503a8a 13169 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
13170 if (err)
13171 return err;
13172
f1174f77 13173 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
13174 }
13175
13176 return 0;
13177}
13178
f4d7e40a 13179static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 13180 struct bpf_reg_state *dst_reg,
f8ddadc4 13181 enum bpf_reg_type type,
fb2a311a 13182 bool range_right_open)
969bf05e 13183{
b239da34
KKD
13184 struct bpf_func_state *state;
13185 struct bpf_reg_state *reg;
13186 int new_range;
2d2be8ca 13187
fb2a311a
DB
13188 if (dst_reg->off < 0 ||
13189 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
13190 /* This doesn't give us any range */
13191 return;
13192
b03c9f9f
EC
13193 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13194 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
13195 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13196 * than pkt_end, but that's because it's also less than pkt.
13197 */
13198 return;
13199
fb2a311a
DB
13200 new_range = dst_reg->off;
13201 if (range_right_open)
2fa7d94a 13202 new_range++;
fb2a311a
DB
13203
13204 /* Examples for register markings:
2d2be8ca 13205 *
fb2a311a 13206 * pkt_data in dst register:
2d2be8ca
DB
13207 *
13208 * r2 = r3;
13209 * r2 += 8;
13210 * if (r2 > pkt_end) goto <handle exception>
13211 * <access okay>
13212 *
b4e432f1
DB
13213 * r2 = r3;
13214 * r2 += 8;
13215 * if (r2 < pkt_end) goto <access okay>
13216 * <handle exception>
13217 *
2d2be8ca
DB
13218 * Where:
13219 * r2 == dst_reg, pkt_end == src_reg
13220 * r2=pkt(id=n,off=8,r=0)
13221 * r3=pkt(id=n,off=0,r=0)
13222 *
fb2a311a 13223 * pkt_data in src register:
2d2be8ca
DB
13224 *
13225 * r2 = r3;
13226 * r2 += 8;
13227 * if (pkt_end >= r2) goto <access okay>
13228 * <handle exception>
13229 *
b4e432f1
DB
13230 * r2 = r3;
13231 * r2 += 8;
13232 * if (pkt_end <= r2) goto <handle exception>
13233 * <access okay>
13234 *
2d2be8ca
DB
13235 * Where:
13236 * pkt_end == dst_reg, r2 == src_reg
13237 * r2=pkt(id=n,off=8,r=0)
13238 * r3=pkt(id=n,off=0,r=0)
13239 *
13240 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
13241 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13242 * and [r3, r3 + 8-1) respectively is safe to access depending on
13243 * the check.
969bf05e 13244 */
2d2be8ca 13245
f1174f77
EC
13246 /* If our ids match, then we must have the same max_value. And we
13247 * don't care about the other reg's fixed offset, since if it's too big
13248 * the range won't allow anything.
13249 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13250 */
b239da34
KKD
13251 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13252 if (reg->type == type && reg->id == dst_reg->id)
13253 /* keep the maximum range already checked */
13254 reg->range = max(reg->range, new_range);
13255 }));
969bf05e
AS
13256}
13257
3f50f132 13258static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 13259{
3f50f132
JF
13260 struct tnum subreg = tnum_subreg(reg->var_off);
13261 s32 sval = (s32)val;
a72dafaf 13262
3f50f132
JF
13263 switch (opcode) {
13264 case BPF_JEQ:
13265 if (tnum_is_const(subreg))
13266 return !!tnum_equals_const(subreg, val);
13fbcee5
YS
13267 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13268 return 0;
3f50f132
JF
13269 break;
13270 case BPF_JNE:
13271 if (tnum_is_const(subreg))
13272 return !tnum_equals_const(subreg, val);
13fbcee5
YS
13273 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13274 return 1;
3f50f132
JF
13275 break;
13276 case BPF_JSET:
13277 if ((~subreg.mask & subreg.value) & val)
13278 return 1;
13279 if (!((subreg.mask | subreg.value) & val))
13280 return 0;
13281 break;
13282 case BPF_JGT:
13283 if (reg->u32_min_value > val)
13284 return 1;
13285 else if (reg->u32_max_value <= val)
13286 return 0;
13287 break;
13288 case BPF_JSGT:
13289 if (reg->s32_min_value > sval)
13290 return 1;
ee114dd6 13291 else if (reg->s32_max_value <= sval)
3f50f132
JF
13292 return 0;
13293 break;
13294 case BPF_JLT:
13295 if (reg->u32_max_value < val)
13296 return 1;
13297 else if (reg->u32_min_value >= val)
13298 return 0;
13299 break;
13300 case BPF_JSLT:
13301 if (reg->s32_max_value < sval)
13302 return 1;
13303 else if (reg->s32_min_value >= sval)
13304 return 0;
13305 break;
13306 case BPF_JGE:
13307 if (reg->u32_min_value >= val)
13308 return 1;
13309 else if (reg->u32_max_value < val)
13310 return 0;
13311 break;
13312 case BPF_JSGE:
13313 if (reg->s32_min_value >= sval)
13314 return 1;
13315 else if (reg->s32_max_value < sval)
13316 return 0;
13317 break;
13318 case BPF_JLE:
13319 if (reg->u32_max_value <= val)
13320 return 1;
13321 else if (reg->u32_min_value > val)
13322 return 0;
13323 break;
13324 case BPF_JSLE:
13325 if (reg->s32_max_value <= sval)
13326 return 1;
13327 else if (reg->s32_min_value > sval)
13328 return 0;
13329 break;
13330 }
4f7b3e82 13331
3f50f132
JF
13332 return -1;
13333}
092ed096 13334
3f50f132
JF
13335
13336static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13337{
13338 s64 sval = (s64)val;
a72dafaf 13339
4f7b3e82
AS
13340 switch (opcode) {
13341 case BPF_JEQ:
13342 if (tnum_is_const(reg->var_off))
13343 return !!tnum_equals_const(reg->var_off, val);
13fbcee5
YS
13344 else if (val < reg->umin_value || val > reg->umax_value)
13345 return 0;
4f7b3e82
AS
13346 break;
13347 case BPF_JNE:
13348 if (tnum_is_const(reg->var_off))
13349 return !tnum_equals_const(reg->var_off, val);
13fbcee5
YS
13350 else if (val < reg->umin_value || val > reg->umax_value)
13351 return 1;
4f7b3e82 13352 break;
960ea056
JK
13353 case BPF_JSET:
13354 if ((~reg->var_off.mask & reg->var_off.value) & val)
13355 return 1;
13356 if (!((reg->var_off.mask | reg->var_off.value) & val))
13357 return 0;
13358 break;
4f7b3e82
AS
13359 case BPF_JGT:
13360 if (reg->umin_value > val)
13361 return 1;
13362 else if (reg->umax_value <= val)
13363 return 0;
13364 break;
13365 case BPF_JSGT:
a72dafaf 13366 if (reg->smin_value > sval)
4f7b3e82 13367 return 1;
ee114dd6 13368 else if (reg->smax_value <= sval)
4f7b3e82
AS
13369 return 0;
13370 break;
13371 case BPF_JLT:
13372 if (reg->umax_value < val)
13373 return 1;
13374 else if (reg->umin_value >= val)
13375 return 0;
13376 break;
13377 case BPF_JSLT:
a72dafaf 13378 if (reg->smax_value < sval)
4f7b3e82 13379 return 1;
a72dafaf 13380 else if (reg->smin_value >= sval)
4f7b3e82
AS
13381 return 0;
13382 break;
13383 case BPF_JGE:
13384 if (reg->umin_value >= val)
13385 return 1;
13386 else if (reg->umax_value < val)
13387 return 0;
13388 break;
13389 case BPF_JSGE:
a72dafaf 13390 if (reg->smin_value >= sval)
4f7b3e82 13391 return 1;
a72dafaf 13392 else if (reg->smax_value < sval)
4f7b3e82
AS
13393 return 0;
13394 break;
13395 case BPF_JLE:
13396 if (reg->umax_value <= val)
13397 return 1;
13398 else if (reg->umin_value > val)
13399 return 0;
13400 break;
13401 case BPF_JSLE:
a72dafaf 13402 if (reg->smax_value <= sval)
4f7b3e82 13403 return 1;
a72dafaf 13404 else if (reg->smin_value > sval)
4f7b3e82
AS
13405 return 0;
13406 break;
13407 }
13408
13409 return -1;
13410}
13411
3f50f132
JF
13412/* compute branch direction of the expression "if (reg opcode val) goto target;"
13413 * and return:
13414 * 1 - branch will be taken and "goto target" will be executed
13415 * 0 - branch will not be taken and fall-through to next insn
13416 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13417 * range [0,10]
604dca5e 13418 */
3f50f132
JF
13419static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13420 bool is_jmp32)
604dca5e 13421{
cac616db 13422 if (__is_pointer_value(false, reg)) {
51302c95 13423 if (!reg_not_null(reg))
cac616db
JF
13424 return -1;
13425
13426 /* If pointer is valid tests against zero will fail so we can
13427 * use this to direct branch taken.
13428 */
13429 if (val != 0)
13430 return -1;
13431
13432 switch (opcode) {
13433 case BPF_JEQ:
13434 return 0;
13435 case BPF_JNE:
13436 return 1;
13437 default:
13438 return -1;
13439 }
13440 }
604dca5e 13441
3f50f132
JF
13442 if (is_jmp32)
13443 return is_branch32_taken(reg, val, opcode);
13444 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
13445}
13446
6d94e741
AS
13447static int flip_opcode(u32 opcode)
13448{
13449 /* How can we transform "a <op> b" into "b <op> a"? */
13450 static const u8 opcode_flip[16] = {
13451 /* these stay the same */
13452 [BPF_JEQ >> 4] = BPF_JEQ,
13453 [BPF_JNE >> 4] = BPF_JNE,
13454 [BPF_JSET >> 4] = BPF_JSET,
13455 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13456 [BPF_JGE >> 4] = BPF_JLE,
13457 [BPF_JGT >> 4] = BPF_JLT,
13458 [BPF_JLE >> 4] = BPF_JGE,
13459 [BPF_JLT >> 4] = BPF_JGT,
13460 [BPF_JSGE >> 4] = BPF_JSLE,
13461 [BPF_JSGT >> 4] = BPF_JSLT,
13462 [BPF_JSLE >> 4] = BPF_JSGE,
13463 [BPF_JSLT >> 4] = BPF_JSGT
13464 };
13465 return opcode_flip[opcode >> 4];
13466}
13467
13468static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13469 struct bpf_reg_state *src_reg,
13470 u8 opcode)
13471{
13472 struct bpf_reg_state *pkt;
13473
13474 if (src_reg->type == PTR_TO_PACKET_END) {
13475 pkt = dst_reg;
13476 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13477 pkt = src_reg;
13478 opcode = flip_opcode(opcode);
13479 } else {
13480 return -1;
13481 }
13482
13483 if (pkt->range >= 0)
13484 return -1;
13485
13486 switch (opcode) {
13487 case BPF_JLE:
13488 /* pkt <= pkt_end */
13489 fallthrough;
13490 case BPF_JGT:
13491 /* pkt > pkt_end */
13492 if (pkt->range == BEYOND_PKT_END)
13493 /* pkt has at last one extra byte beyond pkt_end */
13494 return opcode == BPF_JGT;
13495 break;
13496 case BPF_JLT:
13497 /* pkt < pkt_end */
13498 fallthrough;
13499 case BPF_JGE:
13500 /* pkt >= pkt_end */
13501 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13502 return opcode == BPF_JGE;
13503 break;
13504 }
13505 return -1;
13506}
13507
48461135
JB
13508/* Adjusts the register min/max values in the case that the dst_reg is the
13509 * variable register that we are working on, and src_reg is a constant or we're
13510 * simply doing a BPF_K check.
f1174f77 13511 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
13512 */
13513static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
13514 struct bpf_reg_state *false_reg,
13515 u64 val, u32 val32,
092ed096 13516 u8 opcode, bool is_jmp32)
48461135 13517{
3f50f132
JF
13518 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13519 struct tnum false_64off = false_reg->var_off;
13520 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13521 struct tnum true_64off = true_reg->var_off;
13522 s64 sval = (s64)val;
13523 s32 sval32 = (s32)val32;
a72dafaf 13524
f1174f77
EC
13525 /* If the dst_reg is a pointer, we can't learn anything about its
13526 * variable offset from the compare (unless src_reg were a pointer into
13527 * the same object, but we don't bother with that.
13528 * Since false_reg and true_reg have the same type by construction, we
13529 * only need to check one of them for pointerness.
13530 */
13531 if (__is_pointer_value(false, false_reg))
13532 return;
4cabc5b1 13533
48461135 13534 switch (opcode) {
a12ca627
DB
13535 /* JEQ/JNE comparison doesn't change the register equivalence.
13536 *
13537 * r1 = r2;
13538 * if (r1 == 42) goto label;
13539 * ...
13540 * label: // here both r1 and r2 are known to be 42.
13541 *
13542 * Hence when marking register as known preserve it's ID.
13543 */
48461135 13544 case BPF_JEQ:
a12ca627
DB
13545 if (is_jmp32) {
13546 __mark_reg32_known(true_reg, val32);
13547 true_32off = tnum_subreg(true_reg->var_off);
13548 } else {
13549 ___mark_reg_known(true_reg, val);
13550 true_64off = true_reg->var_off;
13551 }
13552 break;
48461135 13553 case BPF_JNE:
a12ca627
DB
13554 if (is_jmp32) {
13555 __mark_reg32_known(false_reg, val32);
13556 false_32off = tnum_subreg(false_reg->var_off);
13557 } else {
13558 ___mark_reg_known(false_reg, val);
13559 false_64off = false_reg->var_off;
13560 }
48461135 13561 break;
960ea056 13562 case BPF_JSET:
3f50f132
JF
13563 if (is_jmp32) {
13564 false_32off = tnum_and(false_32off, tnum_const(~val32));
13565 if (is_power_of_2(val32))
13566 true_32off = tnum_or(true_32off,
13567 tnum_const(val32));
13568 } else {
13569 false_64off = tnum_and(false_64off, tnum_const(~val));
13570 if (is_power_of_2(val))
13571 true_64off = tnum_or(true_64off,
13572 tnum_const(val));
13573 }
960ea056 13574 break;
48461135 13575 case BPF_JGE:
a72dafaf
JW
13576 case BPF_JGT:
13577 {
3f50f132
JF
13578 if (is_jmp32) {
13579 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13580 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13581
13582 false_reg->u32_max_value = min(false_reg->u32_max_value,
13583 false_umax);
13584 true_reg->u32_min_value = max(true_reg->u32_min_value,
13585 true_umin);
13586 } else {
13587 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13588 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13589
13590 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13591 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13592 }
b03c9f9f 13593 break;
a72dafaf 13594 }
48461135 13595 case BPF_JSGE:
a72dafaf
JW
13596 case BPF_JSGT:
13597 {
3f50f132
JF
13598 if (is_jmp32) {
13599 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13600 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 13601
3f50f132
JF
13602 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13603 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13604 } else {
13605 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13606 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13607
13608 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13609 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13610 }
48461135 13611 break;
a72dafaf 13612 }
b4e432f1 13613 case BPF_JLE:
a72dafaf
JW
13614 case BPF_JLT:
13615 {
3f50f132
JF
13616 if (is_jmp32) {
13617 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13618 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13619
13620 false_reg->u32_min_value = max(false_reg->u32_min_value,
13621 false_umin);
13622 true_reg->u32_max_value = min(true_reg->u32_max_value,
13623 true_umax);
13624 } else {
13625 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13626 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13627
13628 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13629 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13630 }
b4e432f1 13631 break;
a72dafaf 13632 }
b4e432f1 13633 case BPF_JSLE:
a72dafaf
JW
13634 case BPF_JSLT:
13635 {
3f50f132
JF
13636 if (is_jmp32) {
13637 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13638 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 13639
3f50f132
JF
13640 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13641 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13642 } else {
13643 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13644 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13645
13646 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13647 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13648 }
b4e432f1 13649 break;
a72dafaf 13650 }
48461135 13651 default:
0fc31b10 13652 return;
48461135
JB
13653 }
13654
3f50f132
JF
13655 if (is_jmp32) {
13656 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13657 tnum_subreg(false_32off));
13658 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13659 tnum_subreg(true_32off));
13660 __reg_combine_32_into_64(false_reg);
13661 __reg_combine_32_into_64(true_reg);
13662 } else {
13663 false_reg->var_off = false_64off;
13664 true_reg->var_off = true_64off;
13665 __reg_combine_64_into_32(false_reg);
13666 __reg_combine_64_into_32(true_reg);
13667 }
48461135
JB
13668}
13669
f1174f77
EC
13670/* Same as above, but for the case that dst_reg holds a constant and src_reg is
13671 * the variable reg.
48461135
JB
13672 */
13673static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
13674 struct bpf_reg_state *false_reg,
13675 u64 val, u32 val32,
092ed096 13676 u8 opcode, bool is_jmp32)
48461135 13677{
6d94e741 13678 opcode = flip_opcode(opcode);
0fc31b10
JH
13679 /* This uses zero as "not present in table"; luckily the zero opcode,
13680 * BPF_JA, can't get here.
b03c9f9f 13681 */
0fc31b10 13682 if (opcode)
3f50f132 13683 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
13684}
13685
13686/* Regs are known to be equal, so intersect their min/max/var_off */
13687static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13688 struct bpf_reg_state *dst_reg)
13689{
b03c9f9f
EC
13690 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13691 dst_reg->umin_value);
13692 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13693 dst_reg->umax_value);
13694 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13695 dst_reg->smin_value);
13696 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13697 dst_reg->smax_value);
f1174f77
EC
13698 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13699 dst_reg->var_off);
3844d153
DB
13700 reg_bounds_sync(src_reg);
13701 reg_bounds_sync(dst_reg);
f1174f77
EC
13702}
13703
13704static void reg_combine_min_max(struct bpf_reg_state *true_src,
13705 struct bpf_reg_state *true_dst,
13706 struct bpf_reg_state *false_src,
13707 struct bpf_reg_state *false_dst,
13708 u8 opcode)
13709{
13710 switch (opcode) {
13711 case BPF_JEQ:
13712 __reg_combine_min_max(true_src, true_dst);
13713 break;
13714 case BPF_JNE:
13715 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 13716 break;
4cabc5b1 13717 }
48461135
JB
13718}
13719
fd978bf7
JS
13720static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13721 struct bpf_reg_state *reg, u32 id,
840b9615 13722 bool is_null)
57a09bf0 13723{
c25b2ae1 13724 if (type_may_be_null(reg->type) && reg->id == id &&
fca1aa75 13725 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
df57f38a
KKD
13726 /* Old offset (both fixed and variable parts) should have been
13727 * known-zero, because we don't allow pointer arithmetic on
13728 * pointers that might be NULL. If we see this happening, don't
13729 * convert the register.
13730 *
13731 * But in some cases, some helpers that return local kptrs
13732 * advance offset for the returned pointer. In those cases, it
13733 * is fine to expect to see reg->off.
13734 */
13735 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13736 return;
6a3cd331
DM
13737 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13738 WARN_ON_ONCE(reg->off))
e60b0d12 13739 return;
6a3cd331 13740
f1174f77
EC
13741 if (is_null) {
13742 reg->type = SCALAR_VALUE;
1b986589
MKL
13743 /* We don't need id and ref_obj_id from this point
13744 * onwards anymore, thus we should better reset it,
13745 * so that state pruning has chances to take effect.
13746 */
13747 reg->id = 0;
13748 reg->ref_obj_id = 0;
4ddb7416
DB
13749
13750 return;
13751 }
13752
13753 mark_ptr_not_null_reg(reg);
13754
13755 if (!reg_may_point_to_spin_lock(reg)) {
1b986589 13756 /* For not-NULL ptr, reg->ref_obj_id will be reset
b239da34 13757 * in release_reference().
1b986589
MKL
13758 *
13759 * reg->id is still used by spin_lock ptr. Other
13760 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
13761 */
13762 reg->id = 0;
56f668df 13763 }
57a09bf0
TG
13764 }
13765}
13766
13767/* The logic is similar to find_good_pkt_pointers(), both could eventually
13768 * be folded together at some point.
13769 */
840b9615
JS
13770static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13771 bool is_null)
57a09bf0 13772{
f4d7e40a 13773 struct bpf_func_state *state = vstate->frame[vstate->curframe];
b239da34 13774 struct bpf_reg_state *regs = state->regs, *reg;
1b986589 13775 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 13776 u32 id = regs[regno].id;
57a09bf0 13777
1b986589
MKL
13778 if (ref_obj_id && ref_obj_id == id && is_null)
13779 /* regs[regno] is in the " == NULL" branch.
13780 * No one could have freed the reference state before
13781 * doing the NULL check.
13782 */
13783 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 13784
b239da34
KKD
13785 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13786 mark_ptr_or_null_reg(state, reg, id, is_null);
13787 }));
57a09bf0
TG
13788}
13789
5beca081
DB
13790static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13791 struct bpf_reg_state *dst_reg,
13792 struct bpf_reg_state *src_reg,
13793 struct bpf_verifier_state *this_branch,
13794 struct bpf_verifier_state *other_branch)
13795{
13796 if (BPF_SRC(insn->code) != BPF_X)
13797 return false;
13798
092ed096
JW
13799 /* Pointers are always 64-bit. */
13800 if (BPF_CLASS(insn->code) == BPF_JMP32)
13801 return false;
13802
5beca081
DB
13803 switch (BPF_OP(insn->code)) {
13804 case BPF_JGT:
13805 if ((dst_reg->type == PTR_TO_PACKET &&
13806 src_reg->type == PTR_TO_PACKET_END) ||
13807 (dst_reg->type == PTR_TO_PACKET_META &&
13808 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13809 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13810 find_good_pkt_pointers(this_branch, dst_reg,
13811 dst_reg->type, false);
6d94e741 13812 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
13813 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13814 src_reg->type == PTR_TO_PACKET) ||
13815 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13816 src_reg->type == PTR_TO_PACKET_META)) {
13817 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13818 find_good_pkt_pointers(other_branch, src_reg,
13819 src_reg->type, true);
6d94e741 13820 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
13821 } else {
13822 return false;
13823 }
13824 break;
13825 case BPF_JLT:
13826 if ((dst_reg->type == PTR_TO_PACKET &&
13827 src_reg->type == PTR_TO_PACKET_END) ||
13828 (dst_reg->type == PTR_TO_PACKET_META &&
13829 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13830 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13831 find_good_pkt_pointers(other_branch, dst_reg,
13832 dst_reg->type, true);
6d94e741 13833 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
13834 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13835 src_reg->type == PTR_TO_PACKET) ||
13836 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13837 src_reg->type == PTR_TO_PACKET_META)) {
13838 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13839 find_good_pkt_pointers(this_branch, src_reg,
13840 src_reg->type, false);
6d94e741 13841 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
13842 } else {
13843 return false;
13844 }
13845 break;
13846 case BPF_JGE:
13847 if ((dst_reg->type == PTR_TO_PACKET &&
13848 src_reg->type == PTR_TO_PACKET_END) ||
13849 (dst_reg->type == PTR_TO_PACKET_META &&
13850 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13851 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13852 find_good_pkt_pointers(this_branch, dst_reg,
13853 dst_reg->type, true);
6d94e741 13854 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
13855 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13856 src_reg->type == PTR_TO_PACKET) ||
13857 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13858 src_reg->type == PTR_TO_PACKET_META)) {
13859 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13860 find_good_pkt_pointers(other_branch, src_reg,
13861 src_reg->type, false);
6d94e741 13862 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
13863 } else {
13864 return false;
13865 }
13866 break;
13867 case BPF_JLE:
13868 if ((dst_reg->type == PTR_TO_PACKET &&
13869 src_reg->type == PTR_TO_PACKET_END) ||
13870 (dst_reg->type == PTR_TO_PACKET_META &&
13871 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13872 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13873 find_good_pkt_pointers(other_branch, dst_reg,
13874 dst_reg->type, false);
6d94e741 13875 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
13876 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13877 src_reg->type == PTR_TO_PACKET) ||
13878 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13879 src_reg->type == PTR_TO_PACKET_META)) {
13880 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13881 find_good_pkt_pointers(this_branch, src_reg,
13882 src_reg->type, true);
6d94e741 13883 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
13884 } else {
13885 return false;
13886 }
13887 break;
13888 default:
13889 return false;
13890 }
13891
13892 return true;
13893}
13894
75748837
AS
13895static void find_equal_scalars(struct bpf_verifier_state *vstate,
13896 struct bpf_reg_state *known_reg)
13897{
13898 struct bpf_func_state *state;
13899 struct bpf_reg_state *reg;
75748837 13900
b239da34
KKD
13901 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13902 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
71f656a5 13903 copy_register_state(reg, known_reg);
b239da34 13904 }));
75748837
AS
13905}
13906
58e2af8b 13907static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
13908 struct bpf_insn *insn, int *insn_idx)
13909{
f4d7e40a
AS
13910 struct bpf_verifier_state *this_branch = env->cur_state;
13911 struct bpf_verifier_state *other_branch;
13912 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 13913 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
befae758 13914 struct bpf_reg_state *eq_branch_regs;
17a52670 13915 u8 opcode = BPF_OP(insn->code);
092ed096 13916 bool is_jmp32;
fb8d251e 13917 int pred = -1;
17a52670
AS
13918 int err;
13919
092ed096
JW
13920 /* Only conditional jumps are expected to reach here. */
13921 if (opcode == BPF_JA || opcode > BPF_JSLE) {
13922 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
13923 return -EINVAL;
13924 }
13925
13926 if (BPF_SRC(insn->code) == BPF_X) {
13927 if (insn->imm != 0) {
092ed096 13928 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
13929 return -EINVAL;
13930 }
13931
13932 /* check src1 operand */
dc503a8a 13933 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13934 if (err)
13935 return err;
1be7f75d
AS
13936
13937 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 13938 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
13939 insn->src_reg);
13940 return -EACCES;
13941 }
fb8d251e 13942 src_reg = &regs[insn->src_reg];
17a52670
AS
13943 } else {
13944 if (insn->src_reg != BPF_REG_0) {
092ed096 13945 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
13946 return -EINVAL;
13947 }
13948 }
13949
13950 /* check src2 operand */
dc503a8a 13951 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13952 if (err)
13953 return err;
13954
1a0dc1ac 13955 dst_reg = &regs[insn->dst_reg];
092ed096 13956 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 13957
3f50f132
JF
13958 if (BPF_SRC(insn->code) == BPF_K) {
13959 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13960 } else if (src_reg->type == SCALAR_VALUE &&
13961 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13962 pred = is_branch_taken(dst_reg,
13963 tnum_subreg(src_reg->var_off).value,
13964 opcode,
13965 is_jmp32);
13966 } else if (src_reg->type == SCALAR_VALUE &&
13967 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13968 pred = is_branch_taken(dst_reg,
13969 src_reg->var_off.value,
13970 opcode,
13971 is_jmp32);
953d9f5b
YS
13972 } else if (dst_reg->type == SCALAR_VALUE &&
13973 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13974 pred = is_branch_taken(src_reg,
13975 tnum_subreg(dst_reg->var_off).value,
13976 flip_opcode(opcode),
13977 is_jmp32);
13978 } else if (dst_reg->type == SCALAR_VALUE &&
13979 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13980 pred = is_branch_taken(src_reg,
13981 dst_reg->var_off.value,
13982 flip_opcode(opcode),
13983 is_jmp32);
6d94e741
AS
13984 } else if (reg_is_pkt_pointer_any(dst_reg) &&
13985 reg_is_pkt_pointer_any(src_reg) &&
13986 !is_jmp32) {
13987 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
13988 }
13989
b5dc0163 13990 if (pred >= 0) {
cac616db
JF
13991 /* If we get here with a dst_reg pointer type it is because
13992 * above is_branch_taken() special cased the 0 comparison.
13993 */
13994 if (!__is_pointer_value(false, dst_reg))
13995 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
13996 if (BPF_SRC(insn->code) == BPF_X && !err &&
13997 !__is_pointer_value(false, src_reg))
b5dc0163
AS
13998 err = mark_chain_precision(env, insn->src_reg);
13999 if (err)
14000 return err;
14001 }
9183671a 14002
fb8d251e 14003 if (pred == 1) {
9183671a
DB
14004 /* Only follow the goto, ignore fall-through. If needed, push
14005 * the fall-through branch for simulation under speculative
14006 * execution.
14007 */
14008 if (!env->bypass_spec_v1 &&
14009 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14010 *insn_idx))
14011 return -EFAULT;
fb8d251e
AS
14012 *insn_idx += insn->off;
14013 return 0;
14014 } else if (pred == 0) {
9183671a
DB
14015 /* Only follow the fall-through branch, since that's where the
14016 * program will go. If needed, push the goto branch for
14017 * simulation under speculative execution.
fb8d251e 14018 */
9183671a
DB
14019 if (!env->bypass_spec_v1 &&
14020 !sanitize_speculative_path(env, insn,
14021 *insn_idx + insn->off + 1,
14022 *insn_idx))
14023 return -EFAULT;
fb8d251e 14024 return 0;
17a52670
AS
14025 }
14026
979d63d5
DB
14027 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14028 false);
17a52670
AS
14029 if (!other_branch)
14030 return -EFAULT;
f4d7e40a 14031 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 14032
48461135
JB
14033 /* detect if we are comparing against a constant value so we can adjust
14034 * our min/max values for our dst register.
f1174f77 14035 * this is only legit if both are scalars (or pointers to the same
befae758
EZ
14036 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14037 * because otherwise the different base pointers mean the offsets aren't
f1174f77 14038 * comparable.
48461135
JB
14039 */
14040 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 14041 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 14042
f1174f77 14043 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
14044 src_reg->type == SCALAR_VALUE) {
14045 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
14046 (is_jmp32 &&
14047 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 14048 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 14049 dst_reg,
3f50f132
JF
14050 src_reg->var_off.value,
14051 tnum_subreg(src_reg->var_off).value,
092ed096
JW
14052 opcode, is_jmp32);
14053 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
14054 (is_jmp32 &&
14055 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 14056 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 14057 src_reg,
3f50f132
JF
14058 dst_reg->var_off.value,
14059 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
14060 opcode, is_jmp32);
14061 else if (!is_jmp32 &&
14062 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 14063 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
14064 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14065 &other_branch_regs[insn->dst_reg],
092ed096 14066 src_reg, dst_reg, opcode);
e688c3db
AS
14067 if (src_reg->id &&
14068 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
14069 find_equal_scalars(this_branch, src_reg);
14070 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14071 }
14072
f1174f77
EC
14073 }
14074 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 14075 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
14076 dst_reg, insn->imm, (u32)insn->imm,
14077 opcode, is_jmp32);
48461135
JB
14078 }
14079
e688c3db
AS
14080 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14081 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
14082 find_equal_scalars(this_branch, dst_reg);
14083 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14084 }
14085
befae758
EZ
14086 /* if one pointer register is compared to another pointer
14087 * register check if PTR_MAYBE_NULL could be lifted.
14088 * E.g. register A - maybe null
14089 * register B - not null
14090 * for JNE A, B, ... - A is not null in the false branch;
14091 * for JEQ A, B, ... - A is not null in the true branch.
8374bfd5
HS
14092 *
14093 * Since PTR_TO_BTF_ID points to a kernel struct that does
14094 * not need to be null checked by the BPF program, i.e.,
14095 * could be null even without PTR_MAYBE_NULL marking, so
14096 * only propagate nullness when neither reg is that type.
befae758
EZ
14097 */
14098 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14099 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
8374bfd5
HS
14100 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14101 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14102 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
befae758
EZ
14103 eq_branch_regs = NULL;
14104 switch (opcode) {
14105 case BPF_JEQ:
14106 eq_branch_regs = other_branch_regs;
14107 break;
14108 case BPF_JNE:
14109 eq_branch_regs = regs;
14110 break;
14111 default:
14112 /* do nothing */
14113 break;
14114 }
14115 if (eq_branch_regs) {
14116 if (type_may_be_null(src_reg->type))
14117 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14118 else
14119 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14120 }
14121 }
14122
092ed096
JW
14123 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14124 * NOTE: these optimizations below are related with pointer comparison
14125 * which will never be JMP32.
14126 */
14127 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 14128 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
c25b2ae1 14129 type_may_be_null(dst_reg->type)) {
840b9615 14130 /* Mark all identical registers in each branch as either
57a09bf0
TG
14131 * safe or unknown depending R == 0 or R != 0 conditional.
14132 */
840b9615
JS
14133 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14134 opcode == BPF_JNE);
14135 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14136 opcode == BPF_JEQ);
5beca081
DB
14137 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14138 this_branch, other_branch) &&
14139 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
14140 verbose(env, "R%d pointer comparison prohibited\n",
14141 insn->dst_reg);
1be7f75d 14142 return -EACCES;
17a52670 14143 }
06ee7115 14144 if (env->log.level & BPF_LOG_LEVEL)
2e576648 14145 print_insn_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
14146 return 0;
14147}
14148
17a52670 14149/* verify BPF_LD_IMM64 instruction */
58e2af8b 14150static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 14151{
d8eca5bb 14152 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 14153 struct bpf_reg_state *regs = cur_regs(env);
4976b718 14154 struct bpf_reg_state *dst_reg;
d8eca5bb 14155 struct bpf_map *map;
17a52670
AS
14156 int err;
14157
14158 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 14159 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
14160 return -EINVAL;
14161 }
14162 if (insn->off != 0) {
61bd5218 14163 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
14164 return -EINVAL;
14165 }
14166
dc503a8a 14167 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
14168 if (err)
14169 return err;
14170
4976b718 14171 dst_reg = &regs[insn->dst_reg];
6b173873 14172 if (insn->src_reg == 0) {
6b173873
JK
14173 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14174
4976b718 14175 dst_reg->type = SCALAR_VALUE;
b03c9f9f 14176 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 14177 return 0;
6b173873 14178 }
17a52670 14179
d400a6cf
DB
14180 /* All special src_reg cases are listed below. From this point onwards
14181 * we either succeed and assign a corresponding dst_reg->type after
14182 * zeroing the offset, or fail and reject the program.
14183 */
14184 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 14185
d400a6cf 14186 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
4976b718 14187 dst_reg->type = aux->btf_var.reg_type;
34d3a78c 14188 switch (base_type(dst_reg->type)) {
4976b718
HL
14189 case PTR_TO_MEM:
14190 dst_reg->mem_size = aux->btf_var.mem_size;
14191 break;
14192 case PTR_TO_BTF_ID:
22dc4a0f 14193 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
14194 dst_reg->btf_id = aux->btf_var.btf_id;
14195 break;
14196 default:
14197 verbose(env, "bpf verifier is misconfigured\n");
14198 return -EFAULT;
14199 }
14200 return 0;
14201 }
14202
69c087ba
YS
14203 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14204 struct bpf_prog_aux *aux = env->prog->aux;
3990ed4c
MKL
14205 u32 subprogno = find_subprog(env,
14206 env->insn_idx + insn->imm + 1);
69c087ba
YS
14207
14208 if (!aux->func_info) {
14209 verbose(env, "missing btf func_info\n");
14210 return -EINVAL;
14211 }
14212 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14213 verbose(env, "callback function not static\n");
14214 return -EINVAL;
14215 }
14216
14217 dst_reg->type = PTR_TO_FUNC;
14218 dst_reg->subprogno = subprogno;
14219 return 0;
14220 }
14221
d8eca5bb 14222 map = env->used_maps[aux->map_index];
4976b718 14223 dst_reg->map_ptr = map;
d8eca5bb 14224
387544bf
AS
14225 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14226 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
4976b718
HL
14227 dst_reg->type = PTR_TO_MAP_VALUE;
14228 dst_reg->off = aux->map_off;
d0d78c1d
KKD
14229 WARN_ON_ONCE(map->max_entries != 1);
14230 /* We want reg->id to be same (0) as map_value is not distinct */
387544bf
AS
14231 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14232 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
4976b718 14233 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
14234 } else {
14235 verbose(env, "bpf verifier is misconfigured\n");
14236 return -EINVAL;
14237 }
17a52670 14238
17a52670
AS
14239 return 0;
14240}
14241
96be4325
DB
14242static bool may_access_skb(enum bpf_prog_type type)
14243{
14244 switch (type) {
14245 case BPF_PROG_TYPE_SOCKET_FILTER:
14246 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 14247 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
14248 return true;
14249 default:
14250 return false;
14251 }
14252}
14253
ddd872bc
AS
14254/* verify safety of LD_ABS|LD_IND instructions:
14255 * - they can only appear in the programs where ctx == skb
14256 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14257 * preserve R6-R9, and store return value into R0
14258 *
14259 * Implicit input:
14260 * ctx == skb == R6 == CTX
14261 *
14262 * Explicit input:
14263 * SRC == any register
14264 * IMM == 32-bit immediate
14265 *
14266 * Output:
14267 * R0 - 8/16/32-bit skb data converted to cpu endianness
14268 */
58e2af8b 14269static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 14270{
638f5b90 14271 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 14272 static const int ctx_reg = BPF_REG_6;
ddd872bc 14273 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
14274 int i, err;
14275
7e40781c 14276 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 14277 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
14278 return -EINVAL;
14279 }
14280
e0cea7ce
DB
14281 if (!env->ops->gen_ld_abs) {
14282 verbose(env, "bpf verifier is misconfigured\n");
14283 return -EINVAL;
14284 }
14285
ddd872bc 14286 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 14287 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 14288 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 14289 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
14290 return -EINVAL;
14291 }
14292
14293 /* check whether implicit source operand (register R6) is readable */
6d4f151a 14294 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
14295 if (err)
14296 return err;
14297
fd978bf7
JS
14298 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14299 * gen_ld_abs() may terminate the program at runtime, leading to
14300 * reference leak.
14301 */
14302 err = check_reference_leak(env);
14303 if (err) {
14304 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14305 return err;
14306 }
14307
d0d78c1d 14308 if (env->cur_state->active_lock.ptr) {
d83525ca
AS
14309 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14310 return -EINVAL;
14311 }
14312
9bb00b28
YS
14313 if (env->cur_state->active_rcu_lock) {
14314 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14315 return -EINVAL;
14316 }
14317
6d4f151a 14318 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
14319 verbose(env,
14320 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
14321 return -EINVAL;
14322 }
14323
14324 if (mode == BPF_IND) {
14325 /* check explicit source operand */
dc503a8a 14326 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
14327 if (err)
14328 return err;
14329 }
14330
be80a1d3 14331 err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
6d4f151a
DB
14332 if (err < 0)
14333 return err;
14334
ddd872bc 14335 /* reset caller saved regs to unreadable */
dc503a8a 14336 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 14337 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
14338 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14339 }
ddd872bc
AS
14340
14341 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
14342 * the value fetched from the packet.
14343 * Already marked as written above.
ddd872bc 14344 */
61bd5218 14345 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
14346 /* ld_abs load up to 32-bit skb data. */
14347 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
14348 return 0;
14349}
14350
390ee7e2
AS
14351static int check_return_code(struct bpf_verifier_env *env)
14352{
5cf1e914 14353 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 14354 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
14355 struct bpf_reg_state *reg;
14356 struct tnum range = tnum_range(0, 1);
7e40781c 14357 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 14358 int err;
bfc6bb74
AS
14359 struct bpf_func_state *frame = env->cur_state->frame[0];
14360 const bool is_subprog = frame->subprogno;
27ae7997 14361
9e4e01df 14362 /* LSM and struct_ops func-ptr's return type could be "void" */
d1a6edec
SF
14363 if (!is_subprog) {
14364 switch (prog_type) {
14365 case BPF_PROG_TYPE_LSM:
14366 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14367 /* See below, can be 0 or 0-1 depending on hook. */
14368 break;
14369 fallthrough;
14370 case BPF_PROG_TYPE_STRUCT_OPS:
14371 if (!prog->aux->attach_func_proto->type)
14372 return 0;
14373 break;
14374 default:
14375 break;
14376 }
14377 }
27ae7997 14378
8fb33b60 14379 /* eBPF calling convention is such that R0 is used
27ae7997
MKL
14380 * to return the value from eBPF program.
14381 * Make sure that it's readable at this time
14382 * of bpf_exit, which means that program wrote
14383 * something into it earlier
14384 */
14385 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14386 if (err)
14387 return err;
14388
14389 if (is_pointer_value(env, BPF_REG_0)) {
14390 verbose(env, "R0 leaks addr as return value\n");
14391 return -EACCES;
14392 }
390ee7e2 14393
f782e2c3 14394 reg = cur_regs(env) + BPF_REG_0;
bfc6bb74
AS
14395
14396 if (frame->in_async_callback_fn) {
14397 /* enforce return zero from async callbacks like timer */
14398 if (reg->type != SCALAR_VALUE) {
14399 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
c25b2ae1 14400 reg_type_str(env, reg->type));
bfc6bb74
AS
14401 return -EINVAL;
14402 }
14403
14404 if (!tnum_in(tnum_const(0), reg->var_off)) {
14405 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14406 return -EINVAL;
14407 }
14408 return 0;
14409 }
14410
f782e2c3
DB
14411 if (is_subprog) {
14412 if (reg->type != SCALAR_VALUE) {
14413 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
c25b2ae1 14414 reg_type_str(env, reg->type));
f782e2c3
DB
14415 return -EINVAL;
14416 }
14417 return 0;
14418 }
14419
7e40781c 14420 switch (prog_type) {
983695fa
DB
14421 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14422 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
14423 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14424 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14425 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14426 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14427 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 14428 range = tnum_range(1, 1);
77241217
SF
14429 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14430 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14431 range = tnum_range(0, 3);
ed4ed404 14432 break;
390ee7e2 14433 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 14434 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14435 range = tnum_range(0, 3);
14436 enforce_attach_type_range = tnum_range(2, 3);
14437 }
ed4ed404 14438 break;
390ee7e2
AS
14439 case BPF_PROG_TYPE_CGROUP_SOCK:
14440 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 14441 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 14442 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 14443 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 14444 break;
15ab09bd
AS
14445 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14446 if (!env->prog->aux->attach_btf_id)
14447 return 0;
14448 range = tnum_const(0);
14449 break;
15d83c4d 14450 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
14451 switch (env->prog->expected_attach_type) {
14452 case BPF_TRACE_FENTRY:
14453 case BPF_TRACE_FEXIT:
14454 range = tnum_const(0);
14455 break;
14456 case BPF_TRACE_RAW_TP:
14457 case BPF_MODIFY_RETURN:
15d83c4d 14458 return 0;
2ec0616e
DB
14459 case BPF_TRACE_ITER:
14460 break;
e92888c7
YS
14461 default:
14462 return -ENOTSUPP;
14463 }
15d83c4d 14464 break;
e9ddbb77
JS
14465 case BPF_PROG_TYPE_SK_LOOKUP:
14466 range = tnum_range(SK_DROP, SK_PASS);
14467 break;
69fd337a
SF
14468
14469 case BPF_PROG_TYPE_LSM:
14470 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14471 /* Regular BPF_PROG_TYPE_LSM programs can return
14472 * any value.
14473 */
14474 return 0;
14475 }
14476 if (!env->prog->aux->attach_func_proto->type) {
14477 /* Make sure programs that attach to void
14478 * hooks don't try to modify return value.
14479 */
14480 range = tnum_range(1, 1);
14481 }
14482 break;
14483
fd9c663b
FW
14484 case BPF_PROG_TYPE_NETFILTER:
14485 range = tnum_range(NF_DROP, NF_ACCEPT);
14486 break;
e92888c7
YS
14487 case BPF_PROG_TYPE_EXT:
14488 /* freplace program can return anything as its return value
14489 * depends on the to-be-replaced kernel func or bpf program.
14490 */
390ee7e2
AS
14491 default:
14492 return 0;
14493 }
14494
390ee7e2 14495 if (reg->type != SCALAR_VALUE) {
61bd5218 14496 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
c25b2ae1 14497 reg_type_str(env, reg->type));
390ee7e2
AS
14498 return -EINVAL;
14499 }
14500
14501 if (!tnum_in(range, reg->var_off)) {
bc2591d6 14502 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
69fd337a 14503 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
d1a6edec 14504 prog_type == BPF_PROG_TYPE_LSM &&
69fd337a
SF
14505 !prog->aux->attach_func_proto->type)
14506 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
390ee7e2
AS
14507 return -EINVAL;
14508 }
5cf1e914 14509
14510 if (!tnum_is_unknown(enforce_attach_type_range) &&
14511 tnum_in(enforce_attach_type_range, reg->var_off))
14512 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
14513 return 0;
14514}
14515
475fb78f
AS
14516/* non-recursive DFS pseudo code
14517 * 1 procedure DFS-iterative(G,v):
14518 * 2 label v as discovered
14519 * 3 let S be a stack
14520 * 4 S.push(v)
14521 * 5 while S is not empty
b6d20799 14522 * 6 t <- S.peek()
475fb78f
AS
14523 * 7 if t is what we're looking for:
14524 * 8 return t
14525 * 9 for all edges e in G.adjacentEdges(t) do
14526 * 10 if edge e is already labelled
14527 * 11 continue with the next edge
14528 * 12 w <- G.adjacentVertex(t,e)
14529 * 13 if vertex w is not discovered and not explored
14530 * 14 label e as tree-edge
14531 * 15 label w as discovered
14532 * 16 S.push(w)
14533 * 17 continue at 5
14534 * 18 else if vertex w is discovered
14535 * 19 label e as back-edge
14536 * 20 else
14537 * 21 // vertex w is explored
14538 * 22 label e as forward- or cross-edge
14539 * 23 label t as explored
14540 * 24 S.pop()
14541 *
14542 * convention:
14543 * 0x10 - discovered
14544 * 0x11 - discovered and fall-through edge labelled
14545 * 0x12 - discovered and fall-through and branch edges labelled
14546 * 0x20 - explored
14547 */
14548
14549enum {
14550 DISCOVERED = 0x10,
14551 EXPLORED = 0x20,
14552 FALLTHROUGH = 1,
14553 BRANCH = 2,
14554};
14555
dc2a4ebc
AS
14556static u32 state_htab_size(struct bpf_verifier_env *env)
14557{
14558 return env->prog->len;
14559}
14560
5d839021
AS
14561static struct bpf_verifier_state_list **explored_state(
14562 struct bpf_verifier_env *env,
14563 int idx)
14564{
dc2a4ebc
AS
14565 struct bpf_verifier_state *cur = env->cur_state;
14566 struct bpf_func_state *state = cur->frame[cur->curframe];
14567
14568 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
14569}
14570
bffdeaa8 14571static void mark_prune_point(struct bpf_verifier_env *env, int idx)
5d839021 14572{
a8f500af 14573 env->insn_aux_data[idx].prune_point = true;
5d839021 14574}
f1bca824 14575
bffdeaa8
AN
14576static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14577{
14578 return env->insn_aux_data[insn_idx].prune_point;
14579}
14580
4b5ce570
AN
14581static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14582{
14583 env->insn_aux_data[idx].force_checkpoint = true;
14584}
14585
14586static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14587{
14588 return env->insn_aux_data[insn_idx].force_checkpoint;
14589}
14590
14591
59e2e27d
WAF
14592enum {
14593 DONE_EXPLORING = 0,
14594 KEEP_EXPLORING = 1,
14595};
14596
475fb78f
AS
14597/* t, w, e - match pseudo-code above:
14598 * t - index of current instruction
14599 * w - next instruction
14600 * e - edge
14601 */
2589726d
AS
14602static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14603 bool loop_ok)
475fb78f 14604{
7df737e9
AS
14605 int *insn_stack = env->cfg.insn_stack;
14606 int *insn_state = env->cfg.insn_state;
14607
475fb78f 14608 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 14609 return DONE_EXPLORING;
475fb78f
AS
14610
14611 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 14612 return DONE_EXPLORING;
475fb78f
AS
14613
14614 if (w < 0 || w >= env->prog->len) {
d9762e84 14615 verbose_linfo(env, t, "%d: ", t);
61bd5218 14616 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
14617 return -EINVAL;
14618 }
14619
bffdeaa8 14620 if (e == BRANCH) {
f1bca824 14621 /* mark branch target for state pruning */
bffdeaa8
AN
14622 mark_prune_point(env, w);
14623 mark_jmp_point(env, w);
14624 }
f1bca824 14625
475fb78f
AS
14626 if (insn_state[w] == 0) {
14627 /* tree-edge */
14628 insn_state[t] = DISCOVERED | e;
14629 insn_state[w] = DISCOVERED;
7df737e9 14630 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 14631 return -E2BIG;
7df737e9 14632 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 14633 return KEEP_EXPLORING;
475fb78f 14634 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 14635 if (loop_ok && env->bpf_capable)
59e2e27d 14636 return DONE_EXPLORING;
d9762e84
MKL
14637 verbose_linfo(env, t, "%d: ", t);
14638 verbose_linfo(env, w, "%d: ", w);
61bd5218 14639 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
14640 return -EINVAL;
14641 } else if (insn_state[w] == EXPLORED) {
14642 /* forward- or cross-edge */
14643 insn_state[t] = DISCOVERED | e;
14644 } else {
61bd5218 14645 verbose(env, "insn state internal bug\n");
475fb78f
AS
14646 return -EFAULT;
14647 }
59e2e27d
WAF
14648 return DONE_EXPLORING;
14649}
14650
dcb2288b 14651static int visit_func_call_insn(int t, struct bpf_insn *insns,
efdb22de
YS
14652 struct bpf_verifier_env *env,
14653 bool visit_callee)
14654{
14655 int ret;
14656
14657 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14658 if (ret)
14659 return ret;
14660
618945fb
AN
14661 mark_prune_point(env, t + 1);
14662 /* when we exit from subprog, we need to record non-linear history */
14663 mark_jmp_point(env, t + 1);
14664
efdb22de 14665 if (visit_callee) {
bffdeaa8 14666 mark_prune_point(env, t);
86fc6ee6
AS
14667 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14668 /* It's ok to allow recursion from CFG point of
14669 * view. __check_func_call() will do the actual
14670 * check.
14671 */
14672 bpf_pseudo_func(insns + t));
efdb22de
YS
14673 }
14674 return ret;
14675}
14676
59e2e27d
WAF
14677/* Visits the instruction at index t and returns one of the following:
14678 * < 0 - an error occurred
14679 * DONE_EXPLORING - the instruction was fully explored
14680 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14681 */
dcb2288b 14682static int visit_insn(int t, struct bpf_verifier_env *env)
59e2e27d 14683{
653ae3a8 14684 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
59e2e27d
WAF
14685 int ret;
14686
653ae3a8 14687 if (bpf_pseudo_func(insn))
dcb2288b 14688 return visit_func_call_insn(t, insns, env, true);
69c087ba 14689
59e2e27d 14690 /* All non-branch instructions have a single fall-through edge. */
653ae3a8
AN
14691 if (BPF_CLASS(insn->code) != BPF_JMP &&
14692 BPF_CLASS(insn->code) != BPF_JMP32)
59e2e27d
WAF
14693 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14694
653ae3a8 14695 switch (BPF_OP(insn->code)) {
59e2e27d
WAF
14696 case BPF_EXIT:
14697 return DONE_EXPLORING;
14698
14699 case BPF_CALL:
c1ee85a9 14700 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
618945fb
AN
14701 /* Mark this call insn as a prune point to trigger
14702 * is_state_visited() check before call itself is
14703 * processed by __check_func_call(). Otherwise new
14704 * async state will be pushed for further exploration.
bfc6bb74 14705 */
bffdeaa8 14706 mark_prune_point(env, t);
06accc87
AN
14707 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14708 struct bpf_kfunc_call_arg_meta meta;
14709
14710 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
4b5ce570 14711 if (ret == 0 && is_iter_next_kfunc(&meta)) {
06accc87 14712 mark_prune_point(env, t);
4b5ce570
AN
14713 /* Checking and saving state checkpoints at iter_next() call
14714 * is crucial for fast convergence of open-coded iterator loop
14715 * logic, so we need to force it. If we don't do that,
14716 * is_state_visited() might skip saving a checkpoint, causing
14717 * unnecessarily long sequence of not checkpointed
14718 * instructions and jumps, leading to exhaustion of jump
14719 * history buffer, and potentially other undesired outcomes.
14720 * It is expected that with correct open-coded iterators
14721 * convergence will happen quickly, so we don't run a risk of
14722 * exhausting memory.
14723 */
14724 mark_force_checkpoint(env, t);
14725 }
06accc87 14726 }
653ae3a8 14727 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
14728
14729 case BPF_JA:
653ae3a8 14730 if (BPF_SRC(insn->code) != BPF_K)
59e2e27d
WAF
14731 return -EINVAL;
14732
14733 /* unconditional jump with single edge */
653ae3a8 14734 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
59e2e27d
WAF
14735 true);
14736 if (ret)
14737 return ret;
14738
653ae3a8
AN
14739 mark_prune_point(env, t + insn->off + 1);
14740 mark_jmp_point(env, t + insn->off + 1);
59e2e27d
WAF
14741
14742 return ret;
14743
14744 default:
14745 /* conditional jump with two edges */
bffdeaa8 14746 mark_prune_point(env, t);
618945fb 14747
59e2e27d
WAF
14748 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14749 if (ret)
14750 return ret;
14751
653ae3a8 14752 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
59e2e27d 14753 }
475fb78f
AS
14754}
14755
14756/* non-recursive depth-first-search to detect loops in BPF program
14757 * loop == back-edge in directed graph
14758 */
58e2af8b 14759static int check_cfg(struct bpf_verifier_env *env)
475fb78f 14760{
475fb78f 14761 int insn_cnt = env->prog->len;
7df737e9 14762 int *insn_stack, *insn_state;
475fb78f 14763 int ret = 0;
59e2e27d 14764 int i;
475fb78f 14765
7df737e9 14766 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
14767 if (!insn_state)
14768 return -ENOMEM;
14769
7df737e9 14770 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 14771 if (!insn_stack) {
71dde681 14772 kvfree(insn_state);
475fb78f
AS
14773 return -ENOMEM;
14774 }
14775
14776 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14777 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 14778 env->cfg.cur_stack = 1;
475fb78f 14779
59e2e27d
WAF
14780 while (env->cfg.cur_stack > 0) {
14781 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 14782
dcb2288b 14783 ret = visit_insn(t, env);
59e2e27d
WAF
14784 switch (ret) {
14785 case DONE_EXPLORING:
14786 insn_state[t] = EXPLORED;
14787 env->cfg.cur_stack--;
14788 break;
14789 case KEEP_EXPLORING:
14790 break;
14791 default:
14792 if (ret > 0) {
14793 verbose(env, "visit_insn internal bug\n");
14794 ret = -EFAULT;
475fb78f 14795 }
475fb78f 14796 goto err_free;
59e2e27d 14797 }
475fb78f
AS
14798 }
14799
59e2e27d 14800 if (env->cfg.cur_stack < 0) {
61bd5218 14801 verbose(env, "pop stack internal bug\n");
475fb78f
AS
14802 ret = -EFAULT;
14803 goto err_free;
14804 }
475fb78f 14805
475fb78f
AS
14806 for (i = 0; i < insn_cnt; i++) {
14807 if (insn_state[i] != EXPLORED) {
61bd5218 14808 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
14809 ret = -EINVAL;
14810 goto err_free;
14811 }
14812 }
14813 ret = 0; /* cfg looks good */
14814
14815err_free:
71dde681
AS
14816 kvfree(insn_state);
14817 kvfree(insn_stack);
7df737e9 14818 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
14819 return ret;
14820}
14821
09b28d76
AS
14822static int check_abnormal_return(struct bpf_verifier_env *env)
14823{
14824 int i;
14825
14826 for (i = 1; i < env->subprog_cnt; i++) {
14827 if (env->subprog_info[i].has_ld_abs) {
14828 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14829 return -EINVAL;
14830 }
14831 if (env->subprog_info[i].has_tail_call) {
14832 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14833 return -EINVAL;
14834 }
14835 }
14836 return 0;
14837}
14838
838e9690
YS
14839/* The minimum supported BTF func info size */
14840#define MIN_BPF_FUNCINFO_SIZE 8
14841#define MAX_FUNCINFO_REC_SIZE 252
14842
c454a46b
MKL
14843static int check_btf_func(struct bpf_verifier_env *env,
14844 const union bpf_attr *attr,
af2ac3e1 14845 bpfptr_t uattr)
838e9690 14846{
09b28d76 14847 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 14848 u32 i, nfuncs, urec_size, min_size;
838e9690 14849 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 14850 struct bpf_func_info *krecord;
8c1b6e69 14851 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
14852 struct bpf_prog *prog;
14853 const struct btf *btf;
af2ac3e1 14854 bpfptr_t urecord;
d0b2818e 14855 u32 prev_offset = 0;
09b28d76 14856 bool scalar_return;
e7ed83d6 14857 int ret = -ENOMEM;
838e9690
YS
14858
14859 nfuncs = attr->func_info_cnt;
09b28d76
AS
14860 if (!nfuncs) {
14861 if (check_abnormal_return(env))
14862 return -EINVAL;
838e9690 14863 return 0;
09b28d76 14864 }
838e9690
YS
14865
14866 if (nfuncs != env->subprog_cnt) {
14867 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14868 return -EINVAL;
14869 }
14870
14871 urec_size = attr->func_info_rec_size;
14872 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14873 urec_size > MAX_FUNCINFO_REC_SIZE ||
14874 urec_size % sizeof(u32)) {
14875 verbose(env, "invalid func info rec size %u\n", urec_size);
14876 return -EINVAL;
14877 }
14878
c454a46b
MKL
14879 prog = env->prog;
14880 btf = prog->aux->btf;
838e9690 14881
af2ac3e1 14882 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
838e9690
YS
14883 min_size = min_t(u32, krec_size, urec_size);
14884
ba64e7d8 14885 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
14886 if (!krecord)
14887 return -ENOMEM;
8c1b6e69
AS
14888 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14889 if (!info_aux)
14890 goto err_free;
ba64e7d8 14891
838e9690
YS
14892 for (i = 0; i < nfuncs; i++) {
14893 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14894 if (ret) {
14895 if (ret == -E2BIG) {
14896 verbose(env, "nonzero tailing record in func info");
14897 /* set the size kernel expects so loader can zero
14898 * out the rest of the record.
14899 */
af2ac3e1
AS
14900 if (copy_to_bpfptr_offset(uattr,
14901 offsetof(union bpf_attr, func_info_rec_size),
14902 &min_size, sizeof(min_size)))
838e9690
YS
14903 ret = -EFAULT;
14904 }
c454a46b 14905 goto err_free;
838e9690
YS
14906 }
14907
af2ac3e1 14908 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
838e9690 14909 ret = -EFAULT;
c454a46b 14910 goto err_free;
838e9690
YS
14911 }
14912
d30d42e0 14913 /* check insn_off */
09b28d76 14914 ret = -EINVAL;
838e9690 14915 if (i == 0) {
d30d42e0 14916 if (krecord[i].insn_off) {
838e9690 14917 verbose(env,
d30d42e0
MKL
14918 "nonzero insn_off %u for the first func info record",
14919 krecord[i].insn_off);
c454a46b 14920 goto err_free;
838e9690 14921 }
d30d42e0 14922 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
14923 verbose(env,
14924 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 14925 krecord[i].insn_off, prev_offset);
c454a46b 14926 goto err_free;
838e9690
YS
14927 }
14928
d30d42e0 14929 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 14930 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 14931 goto err_free;
838e9690
YS
14932 }
14933
14934 /* check type_id */
ba64e7d8 14935 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 14936 if (!type || !btf_type_is_func(type)) {
838e9690 14937 verbose(env, "invalid type id %d in func info",
ba64e7d8 14938 krecord[i].type_id);
c454a46b 14939 goto err_free;
838e9690 14940 }
51c39bb1 14941 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
14942
14943 func_proto = btf_type_by_id(btf, type->type);
14944 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14945 /* btf_func_check() already verified it during BTF load */
14946 goto err_free;
14947 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14948 scalar_return =
6089fb32 14949 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
09b28d76
AS
14950 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14951 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14952 goto err_free;
14953 }
14954 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14955 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14956 goto err_free;
14957 }
14958
d30d42e0 14959 prev_offset = krecord[i].insn_off;
af2ac3e1 14960 bpfptr_add(&urecord, urec_size);
838e9690
YS
14961 }
14962
ba64e7d8
YS
14963 prog->aux->func_info = krecord;
14964 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 14965 prog->aux->func_info_aux = info_aux;
838e9690
YS
14966 return 0;
14967
c454a46b 14968err_free:
ba64e7d8 14969 kvfree(krecord);
8c1b6e69 14970 kfree(info_aux);
838e9690
YS
14971 return ret;
14972}
14973
ba64e7d8
YS
14974static void adjust_btf_func(struct bpf_verifier_env *env)
14975{
8c1b6e69 14976 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
14977 int i;
14978
8c1b6e69 14979 if (!aux->func_info)
ba64e7d8
YS
14980 return;
14981
14982 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 14983 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
14984}
14985
1b773d00 14986#define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
c454a46b
MKL
14987#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
14988
14989static int check_btf_line(struct bpf_verifier_env *env,
14990 const union bpf_attr *attr,
af2ac3e1 14991 bpfptr_t uattr)
c454a46b
MKL
14992{
14993 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14994 struct bpf_subprog_info *sub;
14995 struct bpf_line_info *linfo;
14996 struct bpf_prog *prog;
14997 const struct btf *btf;
af2ac3e1 14998 bpfptr_t ulinfo;
c454a46b
MKL
14999 int err;
15000
15001 nr_linfo = attr->line_info_cnt;
15002 if (!nr_linfo)
15003 return 0;
0e6491b5
BC
15004 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15005 return -EINVAL;
c454a46b
MKL
15006
15007 rec_size = attr->line_info_rec_size;
15008 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15009 rec_size > MAX_LINEINFO_REC_SIZE ||
15010 rec_size & (sizeof(u32) - 1))
15011 return -EINVAL;
15012
15013 /* Need to zero it in case the userspace may
15014 * pass in a smaller bpf_line_info object.
15015 */
15016 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15017 GFP_KERNEL | __GFP_NOWARN);
15018 if (!linfo)
15019 return -ENOMEM;
15020
15021 prog = env->prog;
15022 btf = prog->aux->btf;
15023
15024 s = 0;
15025 sub = env->subprog_info;
af2ac3e1 15026 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
c454a46b
MKL
15027 expected_size = sizeof(struct bpf_line_info);
15028 ncopy = min_t(u32, expected_size, rec_size);
15029 for (i = 0; i < nr_linfo; i++) {
15030 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15031 if (err) {
15032 if (err == -E2BIG) {
15033 verbose(env, "nonzero tailing record in line_info");
af2ac3e1
AS
15034 if (copy_to_bpfptr_offset(uattr,
15035 offsetof(union bpf_attr, line_info_rec_size),
15036 &expected_size, sizeof(expected_size)))
c454a46b
MKL
15037 err = -EFAULT;
15038 }
15039 goto err_free;
15040 }
15041
af2ac3e1 15042 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
c454a46b
MKL
15043 err = -EFAULT;
15044 goto err_free;
15045 }
15046
15047 /*
15048 * Check insn_off to ensure
15049 * 1) strictly increasing AND
15050 * 2) bounded by prog->len
15051 *
15052 * The linfo[0].insn_off == 0 check logically falls into
15053 * the later "missing bpf_line_info for func..." case
15054 * because the first linfo[0].insn_off must be the
15055 * first sub also and the first sub must have
15056 * subprog_info[0].start == 0.
15057 */
15058 if ((i && linfo[i].insn_off <= prev_offset) ||
15059 linfo[i].insn_off >= prog->len) {
15060 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15061 i, linfo[i].insn_off, prev_offset,
15062 prog->len);
15063 err = -EINVAL;
15064 goto err_free;
15065 }
15066
fdbaa0be
MKL
15067 if (!prog->insnsi[linfo[i].insn_off].code) {
15068 verbose(env,
15069 "Invalid insn code at line_info[%u].insn_off\n",
15070 i);
15071 err = -EINVAL;
15072 goto err_free;
15073 }
15074
23127b33
MKL
15075 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15076 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
15077 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15078 err = -EINVAL;
15079 goto err_free;
15080 }
15081
15082 if (s != env->subprog_cnt) {
15083 if (linfo[i].insn_off == sub[s].start) {
15084 sub[s].linfo_idx = i;
15085 s++;
15086 } else if (sub[s].start < linfo[i].insn_off) {
15087 verbose(env, "missing bpf_line_info for func#%u\n", s);
15088 err = -EINVAL;
15089 goto err_free;
15090 }
15091 }
15092
15093 prev_offset = linfo[i].insn_off;
af2ac3e1 15094 bpfptr_add(&ulinfo, rec_size);
c454a46b
MKL
15095 }
15096
15097 if (s != env->subprog_cnt) {
15098 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15099 env->subprog_cnt - s, s);
15100 err = -EINVAL;
15101 goto err_free;
15102 }
15103
15104 prog->aux->linfo = linfo;
15105 prog->aux->nr_linfo = nr_linfo;
15106
15107 return 0;
15108
15109err_free:
15110 kvfree(linfo);
15111 return err;
15112}
15113
fbd94c7a
AS
15114#define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15115#define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15116
15117static int check_core_relo(struct bpf_verifier_env *env,
15118 const union bpf_attr *attr,
15119 bpfptr_t uattr)
15120{
15121 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15122 struct bpf_core_relo core_relo = {};
15123 struct bpf_prog *prog = env->prog;
15124 const struct btf *btf = prog->aux->btf;
15125 struct bpf_core_ctx ctx = {
15126 .log = &env->log,
15127 .btf = btf,
15128 };
15129 bpfptr_t u_core_relo;
15130 int err;
15131
15132 nr_core_relo = attr->core_relo_cnt;
15133 if (!nr_core_relo)
15134 return 0;
15135 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15136 return -EINVAL;
15137
15138 rec_size = attr->core_relo_rec_size;
15139 if (rec_size < MIN_CORE_RELO_SIZE ||
15140 rec_size > MAX_CORE_RELO_SIZE ||
15141 rec_size % sizeof(u32))
15142 return -EINVAL;
15143
15144 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15145 expected_size = sizeof(struct bpf_core_relo);
15146 ncopy = min_t(u32, expected_size, rec_size);
15147
15148 /* Unlike func_info and line_info, copy and apply each CO-RE
15149 * relocation record one at a time.
15150 */
15151 for (i = 0; i < nr_core_relo; i++) {
15152 /* future proofing when sizeof(bpf_core_relo) changes */
15153 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15154 if (err) {
15155 if (err == -E2BIG) {
15156 verbose(env, "nonzero tailing record in core_relo");
15157 if (copy_to_bpfptr_offset(uattr,
15158 offsetof(union bpf_attr, core_relo_rec_size),
15159 &expected_size, sizeof(expected_size)))
15160 err = -EFAULT;
15161 }
15162 break;
15163 }
15164
15165 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15166 err = -EFAULT;
15167 break;
15168 }
15169
15170 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15171 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15172 i, core_relo.insn_off, prog->len);
15173 err = -EINVAL;
15174 break;
15175 }
15176
15177 err = bpf_core_apply(&ctx, &core_relo, i,
15178 &prog->insnsi[core_relo.insn_off / 8]);
15179 if (err)
15180 break;
15181 bpfptr_add(&u_core_relo, rec_size);
15182 }
15183 return err;
15184}
15185
c454a46b
MKL
15186static int check_btf_info(struct bpf_verifier_env *env,
15187 const union bpf_attr *attr,
af2ac3e1 15188 bpfptr_t uattr)
c454a46b
MKL
15189{
15190 struct btf *btf;
15191 int err;
15192
09b28d76
AS
15193 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15194 if (check_abnormal_return(env))
15195 return -EINVAL;
c454a46b 15196 return 0;
09b28d76 15197 }
c454a46b
MKL
15198
15199 btf = btf_get_by_fd(attr->prog_btf_fd);
15200 if (IS_ERR(btf))
15201 return PTR_ERR(btf);
350a5c4d
AS
15202 if (btf_is_kernel(btf)) {
15203 btf_put(btf);
15204 return -EACCES;
15205 }
c454a46b
MKL
15206 env->prog->aux->btf = btf;
15207
15208 err = check_btf_func(env, attr, uattr);
15209 if (err)
15210 return err;
15211
15212 err = check_btf_line(env, attr, uattr);
15213 if (err)
15214 return err;
15215
fbd94c7a
AS
15216 err = check_core_relo(env, attr, uattr);
15217 if (err)
15218 return err;
15219
c454a46b 15220 return 0;
ba64e7d8
YS
15221}
15222
f1174f77
EC
15223/* check %cur's range satisfies %old's */
15224static bool range_within(struct bpf_reg_state *old,
15225 struct bpf_reg_state *cur)
15226{
b03c9f9f
EC
15227 return old->umin_value <= cur->umin_value &&
15228 old->umax_value >= cur->umax_value &&
15229 old->smin_value <= cur->smin_value &&
fd675184
DB
15230 old->smax_value >= cur->smax_value &&
15231 old->u32_min_value <= cur->u32_min_value &&
15232 old->u32_max_value >= cur->u32_max_value &&
15233 old->s32_min_value <= cur->s32_min_value &&
15234 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
15235}
15236
f1174f77
EC
15237/* If in the old state two registers had the same id, then they need to have
15238 * the same id in the new state as well. But that id could be different from
15239 * the old state, so we need to track the mapping from old to new ids.
15240 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15241 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15242 * regs with a different old id could still have new id 9, we don't care about
15243 * that.
15244 * So we look through our idmap to see if this old id has been seen before. If
15245 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 15246 */
1ffc85d9 15247static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
969bf05e 15248{
1ffc85d9 15249 struct bpf_id_pair *map = idmap->map;
f1174f77 15250 unsigned int i;
969bf05e 15251
4633a006
AN
15252 /* either both IDs should be set or both should be zero */
15253 if (!!old_id != !!cur_id)
15254 return false;
15255
15256 if (old_id == 0) /* cur_id == 0 as well */
15257 return true;
15258
c9e73e3d 15259 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
1ffc85d9 15260 if (!map[i].old) {
f1174f77 15261 /* Reached an empty slot; haven't seen this id before */
1ffc85d9
EZ
15262 map[i].old = old_id;
15263 map[i].cur = cur_id;
f1174f77
EC
15264 return true;
15265 }
1ffc85d9
EZ
15266 if (map[i].old == old_id)
15267 return map[i].cur == cur_id;
15268 if (map[i].cur == cur_id)
15269 return false;
f1174f77
EC
15270 }
15271 /* We ran out of idmap slots, which should be impossible */
15272 WARN_ON_ONCE(1);
15273 return false;
15274}
15275
1ffc85d9
EZ
15276/* Similar to check_ids(), but allocate a unique temporary ID
15277 * for 'old_id' or 'cur_id' of zero.
15278 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15279 */
15280static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15281{
15282 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15283 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15284
15285 return check_ids(old_id, cur_id, idmap);
15286}
15287
9242b5f5
AS
15288static void clean_func_state(struct bpf_verifier_env *env,
15289 struct bpf_func_state *st)
15290{
15291 enum bpf_reg_liveness live;
15292 int i, j;
15293
15294 for (i = 0; i < BPF_REG_FP; i++) {
15295 live = st->regs[i].live;
15296 /* liveness must not touch this register anymore */
15297 st->regs[i].live |= REG_LIVE_DONE;
15298 if (!(live & REG_LIVE_READ))
15299 /* since the register is unused, clear its state
15300 * to make further comparison simpler
15301 */
f54c7898 15302 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
15303 }
15304
15305 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15306 live = st->stack[i].spilled_ptr.live;
15307 /* liveness must not touch this stack slot anymore */
15308 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15309 if (!(live & REG_LIVE_READ)) {
f54c7898 15310 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
15311 for (j = 0; j < BPF_REG_SIZE; j++)
15312 st->stack[i].slot_type[j] = STACK_INVALID;
15313 }
15314 }
15315}
15316
15317static void clean_verifier_state(struct bpf_verifier_env *env,
15318 struct bpf_verifier_state *st)
15319{
15320 int i;
15321
15322 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15323 /* all regs in this state in all frames were already marked */
15324 return;
15325
15326 for (i = 0; i <= st->curframe; i++)
15327 clean_func_state(env, st->frame[i]);
15328}
15329
15330/* the parentage chains form a tree.
15331 * the verifier states are added to state lists at given insn and
15332 * pushed into state stack for future exploration.
15333 * when the verifier reaches bpf_exit insn some of the verifer states
15334 * stored in the state lists have their final liveness state already,
15335 * but a lot of states will get revised from liveness point of view when
15336 * the verifier explores other branches.
15337 * Example:
15338 * 1: r0 = 1
15339 * 2: if r1 == 100 goto pc+1
15340 * 3: r0 = 2
15341 * 4: exit
15342 * when the verifier reaches exit insn the register r0 in the state list of
15343 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15344 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15345 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15346 *
15347 * Since the verifier pushes the branch states as it sees them while exploring
15348 * the program the condition of walking the branch instruction for the second
15349 * time means that all states below this branch were already explored and
8fb33b60 15350 * their final liveness marks are already propagated.
9242b5f5
AS
15351 * Hence when the verifier completes the search of state list in is_state_visited()
15352 * we can call this clean_live_states() function to mark all liveness states
15353 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15354 * will not be used.
15355 * This function also clears the registers and stack for states that !READ
15356 * to simplify state merging.
15357 *
15358 * Important note here that walking the same branch instruction in the callee
15359 * doesn't meant that the states are DONE. The verifier has to compare
15360 * the callsites
15361 */
15362static void clean_live_states(struct bpf_verifier_env *env, int insn,
15363 struct bpf_verifier_state *cur)
15364{
15365 struct bpf_verifier_state_list *sl;
15366 int i;
15367
5d839021 15368 sl = *explored_state(env, insn);
a8f500af 15369 while (sl) {
2589726d
AS
15370 if (sl->state.branches)
15371 goto next;
dc2a4ebc
AS
15372 if (sl->state.insn_idx != insn ||
15373 sl->state.curframe != cur->curframe)
9242b5f5
AS
15374 goto next;
15375 for (i = 0; i <= cur->curframe; i++)
15376 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15377 goto next;
15378 clean_verifier_state(env, &sl->state);
15379next:
15380 sl = sl->next;
15381 }
15382}
15383
4a95c85c 15384static bool regs_exact(const struct bpf_reg_state *rold,
4633a006 15385 const struct bpf_reg_state *rcur,
1ffc85d9 15386 struct bpf_idmap *idmap)
4a95c85c 15387{
d2dcc67d 15388 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4633a006
AN
15389 check_ids(rold->id, rcur->id, idmap) &&
15390 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
4a95c85c
AN
15391}
15392
f1174f77 15393/* Returns true if (rold safe implies rcur safe) */
e042aa53 15394static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
1ffc85d9 15395 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
f1174f77 15396{
dc503a8a
EC
15397 if (!(rold->live & REG_LIVE_READ))
15398 /* explored state didn't use this */
15399 return true;
f1174f77
EC
15400 if (rold->type == NOT_INIT)
15401 /* explored state can't have used this */
969bf05e 15402 return true;
f1174f77
EC
15403 if (rcur->type == NOT_INIT)
15404 return false;
7f4ce97c 15405
910f6999
AN
15406 /* Enforce that register types have to match exactly, including their
15407 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15408 * rule.
15409 *
15410 * One can make a point that using a pointer register as unbounded
15411 * SCALAR would be technically acceptable, but this could lead to
15412 * pointer leaks because scalars are allowed to leak while pointers
15413 * are not. We could make this safe in special cases if root is
15414 * calling us, but it's probably not worth the hassle.
15415 *
15416 * Also, register types that are *not* MAYBE_NULL could technically be
15417 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15418 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15419 * to the same map).
7f4ce97c
AN
15420 * However, if the old MAYBE_NULL register then got NULL checked,
15421 * doing so could have affected others with the same id, and we can't
15422 * check for that because we lost the id when we converted to
15423 * a non-MAYBE_NULL variant.
15424 * So, as a general rule we don't allow mixing MAYBE_NULL and
910f6999 15425 * non-MAYBE_NULL registers as well.
7f4ce97c 15426 */
910f6999 15427 if (rold->type != rcur->type)
7f4ce97c
AN
15428 return false;
15429
c25b2ae1 15430 switch (base_type(rold->type)) {
f1174f77 15431 case SCALAR_VALUE:
1ffc85d9
EZ
15432 if (env->explore_alu_limits) {
15433 /* explore_alu_limits disables tnum_in() and range_within()
15434 * logic and requires everything to be strict
15435 */
15436 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15437 check_scalar_ids(rold->id, rcur->id, idmap);
15438 }
910f6999
AN
15439 if (!rold->precise)
15440 return true;
1ffc85d9
EZ
15441 /* Why check_ids() for scalar registers?
15442 *
15443 * Consider the following BPF code:
15444 * 1: r6 = ... unbound scalar, ID=a ...
15445 * 2: r7 = ... unbound scalar, ID=b ...
15446 * 3: if (r6 > r7) goto +1
15447 * 4: r6 = r7
15448 * 5: if (r6 > X) goto ...
15449 * 6: ... memory operation using r7 ...
15450 *
15451 * First verification path is [1-6]:
15452 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15453 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15454 * r7 <= X, because r6 and r7 share same id.
15455 * Next verification path is [1-4, 6].
15456 *
15457 * Instruction (6) would be reached in two states:
15458 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15459 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15460 *
15461 * Use check_ids() to distinguish these states.
15462 * ---
15463 * Also verify that new value satisfies old value range knowledge.
15464 */
910f6999 15465 return range_within(rold, rcur) &&
1ffc85d9
EZ
15466 tnum_in(rold->var_off, rcur->var_off) &&
15467 check_scalar_ids(rold->id, rcur->id, idmap);
69c087ba 15468 case PTR_TO_MAP_KEY:
f1174f77 15469 case PTR_TO_MAP_VALUE:
567da5d2
AN
15470 case PTR_TO_MEM:
15471 case PTR_TO_BUF:
15472 case PTR_TO_TP_BUFFER:
1b688a19
EC
15473 /* If the new min/max/var_off satisfy the old ones and
15474 * everything else matches, we are OK.
1b688a19 15475 */
a73bf9f2 15476 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
1b688a19 15477 range_within(rold, rcur) &&
4ea2bb15 15478 tnum_in(rold->var_off, rcur->var_off) &&
567da5d2
AN
15479 check_ids(rold->id, rcur->id, idmap) &&
15480 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
de8f3a83 15481 case PTR_TO_PACKET_META:
f1174f77 15482 case PTR_TO_PACKET:
f1174f77
EC
15483 /* We must have at least as much range as the old ptr
15484 * did, so that any accesses which were safe before are
15485 * still safe. This is true even if old range < old off,
15486 * since someone could have accessed through (ptr - k), or
15487 * even done ptr -= k in a register, to get a safe access.
15488 */
15489 if (rold->range > rcur->range)
15490 return false;
15491 /* If the offsets don't match, we can't trust our alignment;
15492 * nor can we be sure that we won't fall out of range.
15493 */
15494 if (rold->off != rcur->off)
15495 return false;
15496 /* id relations must be preserved */
4633a006 15497 if (!check_ids(rold->id, rcur->id, idmap))
f1174f77
EC
15498 return false;
15499 /* new val must satisfy old val knowledge */
15500 return range_within(rold, rcur) &&
15501 tnum_in(rold->var_off, rcur->var_off);
7c884339
EZ
15502 case PTR_TO_STACK:
15503 /* two stack pointers are equal only if they're pointing to
15504 * the same stack frame, since fp-8 in foo != fp-8 in bar
f1174f77 15505 */
4633a006 15506 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
f1174f77 15507 default:
4633a006 15508 return regs_exact(rold, rcur, idmap);
f1174f77 15509 }
969bf05e
AS
15510}
15511
e042aa53 15512static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
1ffc85d9 15513 struct bpf_func_state *cur, struct bpf_idmap *idmap)
638f5b90
AS
15514{
15515 int i, spi;
15516
638f5b90
AS
15517 /* walk slots of the explored stack and ignore any additional
15518 * slots in the current stack, since explored(safe) state
15519 * didn't use them
15520 */
15521 for (i = 0; i < old->allocated_stack; i++) {
06accc87
AN
15522 struct bpf_reg_state *old_reg, *cur_reg;
15523
638f5b90
AS
15524 spi = i / BPF_REG_SIZE;
15525
b233920c
AS
15526 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15527 i += BPF_REG_SIZE - 1;
cc2b14d5 15528 /* explored state didn't use this */
fd05e57b 15529 continue;
b233920c 15530 }
cc2b14d5 15531
638f5b90
AS
15532 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15533 continue;
19e2dbb7 15534
6715df8d
EZ
15535 if (env->allow_uninit_stack &&
15536 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15537 continue;
15538
19e2dbb7
AS
15539 /* explored stack has more populated slots than current stack
15540 * and these slots were used
15541 */
15542 if (i >= cur->allocated_stack)
15543 return false;
15544
cc2b14d5
AS
15545 /* if old state was safe with misc data in the stack
15546 * it will be safe with zero-initialized stack.
15547 * The opposite is not true
15548 */
15549 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15550 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15551 continue;
638f5b90
AS
15552 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15553 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15554 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 15555 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
15556 * this verifier states are not equivalent,
15557 * return false to continue verification of this path
15558 */
15559 return false;
27113c59 15560 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
638f5b90 15561 continue;
d6fefa11
KKD
15562 /* Both old and cur are having same slot_type */
15563 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15564 case STACK_SPILL:
638f5b90
AS
15565 /* when explored and current stack slot are both storing
15566 * spilled registers, check that stored pointers types
15567 * are the same as well.
15568 * Ex: explored safe path could have stored
15569 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15570 * but current path has stored:
15571 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15572 * such verifier states are not equivalent.
15573 * return false to continue verification of this path
15574 */
d6fefa11
KKD
15575 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15576 &cur->stack[spi].spilled_ptr, idmap))
15577 return false;
15578 break;
15579 case STACK_DYNPTR:
d6fefa11
KKD
15580 old_reg = &old->stack[spi].spilled_ptr;
15581 cur_reg = &cur->stack[spi].spilled_ptr;
15582 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15583 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15584 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15585 return false;
15586 break;
06accc87
AN
15587 case STACK_ITER:
15588 old_reg = &old->stack[spi].spilled_ptr;
15589 cur_reg = &cur->stack[spi].spilled_ptr;
15590 /* iter.depth is not compared between states as it
15591 * doesn't matter for correctness and would otherwise
15592 * prevent convergence; we maintain it only to prevent
15593 * infinite loop check triggering, see
15594 * iter_active_depths_differ()
15595 */
15596 if (old_reg->iter.btf != cur_reg->iter.btf ||
15597 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15598 old_reg->iter.state != cur_reg->iter.state ||
15599 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15600 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15601 return false;
15602 break;
d6fefa11
KKD
15603 case STACK_MISC:
15604 case STACK_ZERO:
15605 case STACK_INVALID:
15606 continue;
15607 /* Ensure that new unhandled slot types return false by default */
15608 default:
638f5b90 15609 return false;
d6fefa11 15610 }
638f5b90
AS
15611 }
15612 return true;
15613}
15614
e8f55fcf 15615static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
1ffc85d9 15616 struct bpf_idmap *idmap)
fd978bf7 15617{
e8f55fcf
AN
15618 int i;
15619
fd978bf7
JS
15620 if (old->acquired_refs != cur->acquired_refs)
15621 return false;
e8f55fcf
AN
15622
15623 for (i = 0; i < old->acquired_refs; i++) {
15624 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15625 return false;
15626 }
15627
15628 return true;
fd978bf7
JS
15629}
15630
f1bca824
AS
15631/* compare two verifier states
15632 *
15633 * all states stored in state_list are known to be valid, since
15634 * verifier reached 'bpf_exit' instruction through them
15635 *
15636 * this function is called when verifier exploring different branches of
15637 * execution popped from the state stack. If it sees an old state that has
15638 * more strict register state and more strict stack state then this execution
15639 * branch doesn't need to be explored further, since verifier already
15640 * concluded that more strict state leads to valid finish.
15641 *
15642 * Therefore two states are equivalent if register state is more conservative
15643 * and explored stack state is more conservative than the current one.
15644 * Example:
15645 * explored current
15646 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15647 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15648 *
15649 * In other words if current stack state (one being explored) has more
15650 * valid slots than old one that already passed validation, it means
15651 * the verifier can stop exploring and conclude that current state is valid too
15652 *
15653 * Similarly with registers. If explored state has register type as invalid
15654 * whereas register type in current state is meaningful, it means that
15655 * the current state will reach 'bpf_exit' instruction safely
15656 */
c9e73e3d 15657static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
f4d7e40a 15658 struct bpf_func_state *cur)
f1bca824
AS
15659{
15660 int i;
15661
c9e73e3d 15662 for (i = 0; i < MAX_BPF_REG; i++)
e042aa53 15663 if (!regsafe(env, &old->regs[i], &cur->regs[i],
1ffc85d9 15664 &env->idmap_scratch))
c9e73e3d 15665 return false;
f1bca824 15666
1ffc85d9 15667 if (!stacksafe(env, old, cur, &env->idmap_scratch))
c9e73e3d 15668 return false;
fd978bf7 15669
1ffc85d9 15670 if (!refsafe(old, cur, &env->idmap_scratch))
c9e73e3d
LB
15671 return false;
15672
15673 return true;
f1bca824
AS
15674}
15675
f4d7e40a
AS
15676static bool states_equal(struct bpf_verifier_env *env,
15677 struct bpf_verifier_state *old,
15678 struct bpf_verifier_state *cur)
15679{
15680 int i;
15681
15682 if (old->curframe != cur->curframe)
15683 return false;
15684
1ffc85d9
EZ
15685 env->idmap_scratch.tmp_id_gen = env->id_gen;
15686 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
5dd9cdbc 15687
979d63d5
DB
15688 /* Verification state from speculative execution simulation
15689 * must never prune a non-speculative execution one.
15690 */
15691 if (old->speculative && !cur->speculative)
15692 return false;
15693
4ea2bb15
EZ
15694 if (old->active_lock.ptr != cur->active_lock.ptr)
15695 return false;
15696
15697 /* Old and cur active_lock's have to be either both present
15698 * or both absent.
15699 */
15700 if (!!old->active_lock.id != !!cur->active_lock.id)
15701 return false;
15702
15703 if (old->active_lock.id &&
1ffc85d9 15704 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
d83525ca
AS
15705 return false;
15706
9bb00b28 15707 if (old->active_rcu_lock != cur->active_rcu_lock)
d83525ca
AS
15708 return false;
15709
f4d7e40a
AS
15710 /* for states to be equal callsites have to be the same
15711 * and all frame states need to be equivalent
15712 */
15713 for (i = 0; i <= old->curframe; i++) {
15714 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15715 return false;
c9e73e3d 15716 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
f4d7e40a
AS
15717 return false;
15718 }
15719 return true;
15720}
15721
5327ed3d
JW
15722/* Return 0 if no propagation happened. Return negative error code if error
15723 * happened. Otherwise, return the propagated bit.
15724 */
55e7f3b5
JW
15725static int propagate_liveness_reg(struct bpf_verifier_env *env,
15726 struct bpf_reg_state *reg,
15727 struct bpf_reg_state *parent_reg)
15728{
5327ed3d
JW
15729 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15730 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
15731 int err;
15732
5327ed3d
JW
15733 /* When comes here, read flags of PARENT_REG or REG could be any of
15734 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15735 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15736 */
15737 if (parent_flag == REG_LIVE_READ64 ||
15738 /* Or if there is no read flag from REG. */
15739 !flag ||
15740 /* Or if the read flag from REG is the same as PARENT_REG. */
15741 parent_flag == flag)
55e7f3b5
JW
15742 return 0;
15743
5327ed3d 15744 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
15745 if (err)
15746 return err;
15747
5327ed3d 15748 return flag;
55e7f3b5
JW
15749}
15750
8e9cd9ce 15751/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
15752 * straight-line code between a state and its parent. When we arrive at an
15753 * equivalent state (jump target or such) we didn't arrive by the straight-line
15754 * code, so read marks in the state must propagate to the parent regardless
15755 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 15756 * in mark_reg_read() is for.
8e9cd9ce 15757 */
f4d7e40a
AS
15758static int propagate_liveness(struct bpf_verifier_env *env,
15759 const struct bpf_verifier_state *vstate,
15760 struct bpf_verifier_state *vparent)
dc503a8a 15761{
3f8cafa4 15762 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 15763 struct bpf_func_state *state, *parent;
3f8cafa4 15764 int i, frame, err = 0;
dc503a8a 15765
f4d7e40a
AS
15766 if (vparent->curframe != vstate->curframe) {
15767 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15768 vparent->curframe, vstate->curframe);
15769 return -EFAULT;
15770 }
dc503a8a
EC
15771 /* Propagate read liveness of registers... */
15772 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 15773 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
15774 parent = vparent->frame[frame];
15775 state = vstate->frame[frame];
15776 parent_reg = parent->regs;
15777 state_reg = state->regs;
83d16312
JK
15778 /* We don't need to worry about FP liveness, it's read-only */
15779 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
15780 err = propagate_liveness_reg(env, &state_reg[i],
15781 &parent_reg[i]);
5327ed3d 15782 if (err < 0)
3f8cafa4 15783 return err;
5327ed3d
JW
15784 if (err == REG_LIVE_READ64)
15785 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 15786 }
f4d7e40a 15787
1b04aee7 15788 /* Propagate stack slots. */
f4d7e40a
AS
15789 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15790 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
15791 parent_reg = &parent->stack[i].spilled_ptr;
15792 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
15793 err = propagate_liveness_reg(env, state_reg,
15794 parent_reg);
5327ed3d 15795 if (err < 0)
3f8cafa4 15796 return err;
dc503a8a
EC
15797 }
15798 }
5327ed3d 15799 return 0;
dc503a8a
EC
15800}
15801
a3ce685d
AS
15802/* find precise scalars in the previous equivalent state and
15803 * propagate them into the current state
15804 */
15805static int propagate_precision(struct bpf_verifier_env *env,
15806 const struct bpf_verifier_state *old)
15807{
15808 struct bpf_reg_state *state_reg;
15809 struct bpf_func_state *state;
529409ea 15810 int i, err = 0, fr;
f655badf 15811 bool first;
a3ce685d 15812
529409ea
AN
15813 for (fr = old->curframe; fr >= 0; fr--) {
15814 state = old->frame[fr];
15815 state_reg = state->regs;
f655badf 15816 first = true;
529409ea
AN
15817 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15818 if (state_reg->type != SCALAR_VALUE ||
52c2b005
AN
15819 !state_reg->precise ||
15820 !(state_reg->live & REG_LIVE_READ))
529409ea 15821 continue;
f655badf
AN
15822 if (env->log.level & BPF_LOG_LEVEL2) {
15823 if (first)
15824 verbose(env, "frame %d: propagating r%d", fr, i);
15825 else
15826 verbose(env, ",r%d", i);
15827 }
15828 bt_set_frame_reg(&env->bt, fr, i);
15829 first = false;
529409ea 15830 }
a3ce685d 15831
529409ea
AN
15832 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15833 if (!is_spilled_reg(&state->stack[i]))
15834 continue;
15835 state_reg = &state->stack[i].spilled_ptr;
15836 if (state_reg->type != SCALAR_VALUE ||
52c2b005
AN
15837 !state_reg->precise ||
15838 !(state_reg->live & REG_LIVE_READ))
529409ea 15839 continue;
f655badf
AN
15840 if (env->log.level & BPF_LOG_LEVEL2) {
15841 if (first)
15842 verbose(env, "frame %d: propagating fp%d",
15843 fr, (-i - 1) * BPF_REG_SIZE);
15844 else
15845 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15846 }
15847 bt_set_frame_slot(&env->bt, fr, i);
15848 first = false;
529409ea 15849 }
f655badf
AN
15850 if (!first)
15851 verbose(env, "\n");
a3ce685d 15852 }
f655badf
AN
15853
15854 err = mark_chain_precision_batch(env);
15855 if (err < 0)
15856 return err;
15857
a3ce685d
AS
15858 return 0;
15859}
15860
2589726d
AS
15861static bool states_maybe_looping(struct bpf_verifier_state *old,
15862 struct bpf_verifier_state *cur)
15863{
15864 struct bpf_func_state *fold, *fcur;
15865 int i, fr = cur->curframe;
15866
15867 if (old->curframe != fr)
15868 return false;
15869
15870 fold = old->frame[fr];
15871 fcur = cur->frame[fr];
15872 for (i = 0; i < MAX_BPF_REG; i++)
15873 if (memcmp(&fold->regs[i], &fcur->regs[i],
15874 offsetof(struct bpf_reg_state, parent)))
15875 return false;
15876 return true;
15877}
15878
06accc87
AN
15879static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15880{
15881 return env->insn_aux_data[insn_idx].is_iter_next;
15882}
15883
15884/* is_state_visited() handles iter_next() (see process_iter_next_call() for
15885 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15886 * states to match, which otherwise would look like an infinite loop. So while
15887 * iter_next() calls are taken care of, we still need to be careful and
15888 * prevent erroneous and too eager declaration of "ininite loop", when
15889 * iterators are involved.
15890 *
15891 * Here's a situation in pseudo-BPF assembly form:
15892 *
15893 * 0: again: ; set up iter_next() call args
15894 * 1: r1 = &it ; <CHECKPOINT HERE>
15895 * 2: call bpf_iter_num_next ; this is iter_next() call
15896 * 3: if r0 == 0 goto done
15897 * 4: ... something useful here ...
15898 * 5: goto again ; another iteration
15899 * 6: done:
15900 * 7: r1 = &it
15901 * 8: call bpf_iter_num_destroy ; clean up iter state
15902 * 9: exit
15903 *
15904 * This is a typical loop. Let's assume that we have a prune point at 1:,
15905 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15906 * again`, assuming other heuristics don't get in a way).
15907 *
15908 * When we first time come to 1:, let's say we have some state X. We proceed
15909 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15910 * Now we come back to validate that forked ACTIVE state. We proceed through
15911 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15912 * are converging. But the problem is that we don't know that yet, as this
15913 * convergence has to happen at iter_next() call site only. So if nothing is
15914 * done, at 1: verifier will use bounded loop logic and declare infinite
15915 * looping (and would be *technically* correct, if not for iterator's
15916 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15917 * don't want that. So what we do in process_iter_next_call() when we go on
15918 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15919 * a different iteration. So when we suspect an infinite loop, we additionally
15920 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15921 * pretend we are not looping and wait for next iter_next() call.
15922 *
15923 * This only applies to ACTIVE state. In DRAINED state we don't expect to
15924 * loop, because that would actually mean infinite loop, as DRAINED state is
15925 * "sticky", and so we'll keep returning into the same instruction with the
15926 * same state (at least in one of possible code paths).
15927 *
15928 * This approach allows to keep infinite loop heuristic even in the face of
15929 * active iterator. E.g., C snippet below is and will be detected as
15930 * inifintely looping:
15931 *
15932 * struct bpf_iter_num it;
15933 * int *p, x;
15934 *
15935 * bpf_iter_num_new(&it, 0, 10);
15936 * while ((p = bpf_iter_num_next(&t))) {
15937 * x = p;
15938 * while (x--) {} // <<-- infinite loop here
15939 * }
15940 *
15941 */
15942static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15943{
15944 struct bpf_reg_state *slot, *cur_slot;
15945 struct bpf_func_state *state;
15946 int i, fr;
15947
15948 for (fr = old->curframe; fr >= 0; fr--) {
15949 state = old->frame[fr];
15950 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15951 if (state->stack[i].slot_type[0] != STACK_ITER)
15952 continue;
15953
15954 slot = &state->stack[i].spilled_ptr;
15955 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15956 continue;
15957
15958 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15959 if (cur_slot->iter.depth != slot->iter.depth)
15960 return true;
15961 }
15962 }
15963 return false;
15964}
2589726d 15965
58e2af8b 15966static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 15967{
58e2af8b 15968 struct bpf_verifier_state_list *new_sl;
9f4686c4 15969 struct bpf_verifier_state_list *sl, **pprev;
679c782d 15970 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 15971 int i, j, err, states_cnt = 0;
4b5ce570
AN
15972 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15973 bool add_new_state = force_new_state;
f1bca824 15974
2589726d
AS
15975 /* bpf progs typically have pruning point every 4 instructions
15976 * http://vger.kernel.org/bpfconf2019.html#session-1
15977 * Do not add new state for future pruning if the verifier hasn't seen
15978 * at least 2 jumps and at least 8 instructions.
15979 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15980 * In tests that amounts to up to 50% reduction into total verifier
15981 * memory consumption and 20% verifier time speedup.
15982 */
15983 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15984 env->insn_processed - env->prev_insn_processed >= 8)
15985 add_new_state = true;
15986
a8f500af
AS
15987 pprev = explored_state(env, insn_idx);
15988 sl = *pprev;
15989
9242b5f5
AS
15990 clean_live_states(env, insn_idx, cur);
15991
a8f500af 15992 while (sl) {
dc2a4ebc
AS
15993 states_cnt++;
15994 if (sl->state.insn_idx != insn_idx)
15995 goto next;
bfc6bb74 15996
2589726d 15997 if (sl->state.branches) {
bfc6bb74
AS
15998 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15999
16000 if (frame->in_async_callback_fn &&
16001 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16002 /* Different async_entry_cnt means that the verifier is
16003 * processing another entry into async callback.
16004 * Seeing the same state is not an indication of infinite
16005 * loop or infinite recursion.
16006 * But finding the same state doesn't mean that it's safe
16007 * to stop processing the current state. The previous state
16008 * hasn't yet reached bpf_exit, since state.branches > 0.
16009 * Checking in_async_callback_fn alone is not enough either.
16010 * Since the verifier still needs to catch infinite loops
16011 * inside async callbacks.
16012 */
06accc87
AN
16013 goto skip_inf_loop_check;
16014 }
16015 /* BPF open-coded iterators loop detection is special.
16016 * states_maybe_looping() logic is too simplistic in detecting
16017 * states that *might* be equivalent, because it doesn't know
16018 * about ID remapping, so don't even perform it.
16019 * See process_iter_next_call() and iter_active_depths_differ()
16020 * for overview of the logic. When current and one of parent
16021 * states are detected as equivalent, it's a good thing: we prove
16022 * convergence and can stop simulating further iterations.
16023 * It's safe to assume that iterator loop will finish, taking into
16024 * account iter_next() contract of eventually returning
16025 * sticky NULL result.
16026 */
16027 if (is_iter_next_insn(env, insn_idx)) {
16028 if (states_equal(env, &sl->state, cur)) {
16029 struct bpf_func_state *cur_frame;
16030 struct bpf_reg_state *iter_state, *iter_reg;
16031 int spi;
16032
16033 cur_frame = cur->frame[cur->curframe];
16034 /* btf_check_iter_kfuncs() enforces that
16035 * iter state pointer is always the first arg
16036 */
16037 iter_reg = &cur_frame->regs[BPF_REG_1];
16038 /* current state is valid due to states_equal(),
16039 * so we can assume valid iter and reg state,
16040 * no need for extra (re-)validations
16041 */
16042 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16043 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16044 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16045 goto hit;
16046 }
16047 goto skip_inf_loop_check;
16048 }
16049 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16050 if (states_maybe_looping(&sl->state, cur) &&
16051 states_equal(env, &sl->state, cur) &&
16052 !iter_active_depths_differ(&sl->state, cur)) {
2589726d
AS
16053 verbose_linfo(env, insn_idx, "; ");
16054 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16055 return -EINVAL;
16056 }
16057 /* if the verifier is processing a loop, avoid adding new state
16058 * too often, since different loop iterations have distinct
16059 * states and may not help future pruning.
16060 * This threshold shouldn't be too low to make sure that
16061 * a loop with large bound will be rejected quickly.
16062 * The most abusive loop will be:
16063 * r1 += 1
16064 * if r1 < 1000000 goto pc-2
16065 * 1M insn_procssed limit / 100 == 10k peak states.
16066 * This threshold shouldn't be too high either, since states
16067 * at the end of the loop are likely to be useful in pruning.
16068 */
06accc87 16069skip_inf_loop_check:
4b5ce570 16070 if (!force_new_state &&
98ddcf38 16071 env->jmps_processed - env->prev_jmps_processed < 20 &&
2589726d
AS
16072 env->insn_processed - env->prev_insn_processed < 100)
16073 add_new_state = false;
16074 goto miss;
16075 }
638f5b90 16076 if (states_equal(env, &sl->state, cur)) {
06accc87 16077hit:
9f4686c4 16078 sl->hit_cnt++;
f1bca824 16079 /* reached equivalent register/stack state,
dc503a8a
EC
16080 * prune the search.
16081 * Registers read by the continuation are read by us.
8e9cd9ce
EC
16082 * If we have any write marks in env->cur_state, they
16083 * will prevent corresponding reads in the continuation
16084 * from reaching our parent (an explored_state). Our
16085 * own state will get the read marks recorded, but
16086 * they'll be immediately forgotten as we're pruning
16087 * this state and will pop a new one.
f1bca824 16088 */
f4d7e40a 16089 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
16090
16091 /* if previous state reached the exit with precision and
16092 * current state is equivalent to it (except precsion marks)
16093 * the precision needs to be propagated back in
16094 * the current state.
16095 */
16096 err = err ? : push_jmp_history(env, cur);
16097 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
16098 if (err)
16099 return err;
f1bca824 16100 return 1;
dc503a8a 16101 }
2589726d
AS
16102miss:
16103 /* when new state is not going to be added do not increase miss count.
16104 * Otherwise several loop iterations will remove the state
16105 * recorded earlier. The goal of these heuristics is to have
16106 * states from some iterations of the loop (some in the beginning
16107 * and some at the end) to help pruning.
16108 */
16109 if (add_new_state)
16110 sl->miss_cnt++;
9f4686c4
AS
16111 /* heuristic to determine whether this state is beneficial
16112 * to keep checking from state equivalence point of view.
16113 * Higher numbers increase max_states_per_insn and verification time,
16114 * but do not meaningfully decrease insn_processed.
16115 */
16116 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16117 /* the state is unlikely to be useful. Remove it to
16118 * speed up verification
16119 */
16120 *pprev = sl->next;
16121 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
16122 u32 br = sl->state.branches;
16123
16124 WARN_ONCE(br,
16125 "BUG live_done but branches_to_explore %d\n",
16126 br);
9f4686c4
AS
16127 free_verifier_state(&sl->state, false);
16128 kfree(sl);
16129 env->peak_states--;
16130 } else {
16131 /* cannot free this state, since parentage chain may
16132 * walk it later. Add it for free_list instead to
16133 * be freed at the end of verification
16134 */
16135 sl->next = env->free_list;
16136 env->free_list = sl;
16137 }
16138 sl = *pprev;
16139 continue;
16140 }
dc2a4ebc 16141next:
9f4686c4
AS
16142 pprev = &sl->next;
16143 sl = *pprev;
f1bca824
AS
16144 }
16145
06ee7115
AS
16146 if (env->max_states_per_insn < states_cnt)
16147 env->max_states_per_insn = states_cnt;
16148
2c78ee89 16149 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
a095f421 16150 return 0;
ceefbc96 16151
2589726d 16152 if (!add_new_state)
a095f421 16153 return 0;
ceefbc96 16154
2589726d
AS
16155 /* There were no equivalent states, remember the current one.
16156 * Technically the current state is not proven to be safe yet,
f4d7e40a 16157 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 16158 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 16159 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
16160 * again on the way to bpf_exit.
16161 * When looping the sl->state.branches will be > 0 and this state
16162 * will not be considered for equivalence until branches == 0.
f1bca824 16163 */
638f5b90 16164 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
16165 if (!new_sl)
16166 return -ENOMEM;
06ee7115
AS
16167 env->total_states++;
16168 env->peak_states++;
2589726d
AS
16169 env->prev_jmps_processed = env->jmps_processed;
16170 env->prev_insn_processed = env->insn_processed;
f1bca824 16171
7a830b53
AN
16172 /* forget precise markings we inherited, see __mark_chain_precision */
16173 if (env->bpf_capable)
16174 mark_all_scalars_imprecise(env, cur);
16175
f1bca824 16176 /* add new state to the head of linked list */
679c782d
EC
16177 new = &new_sl->state;
16178 err = copy_verifier_state(new, cur);
1969db47 16179 if (err) {
679c782d 16180 free_verifier_state(new, false);
1969db47
AS
16181 kfree(new_sl);
16182 return err;
16183 }
dc2a4ebc 16184 new->insn_idx = insn_idx;
2589726d
AS
16185 WARN_ONCE(new->branches != 1,
16186 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 16187
2589726d 16188 cur->parent = new;
b5dc0163
AS
16189 cur->first_insn_idx = insn_idx;
16190 clear_jmp_history(cur);
5d839021
AS
16191 new_sl->next = *explored_state(env, insn_idx);
16192 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
16193 /* connect new state to parentage chain. Current frame needs all
16194 * registers connected. Only r6 - r9 of the callers are alive (pushed
16195 * to the stack implicitly by JITs) so in callers' frames connect just
16196 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16197 * the state of the call instruction (with WRITTEN set), and r0 comes
16198 * from callee with its full parentage chain, anyway.
16199 */
8e9cd9ce
EC
16200 /* clear write marks in current state: the writes we did are not writes
16201 * our child did, so they don't screen off its reads from us.
16202 * (There are no read marks in current state, because reads always mark
16203 * their parent and current state never has children yet. Only
16204 * explored_states can get read marks.)
16205 */
eea1c227
AS
16206 for (j = 0; j <= cur->curframe; j++) {
16207 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16208 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16209 for (i = 0; i < BPF_REG_FP; i++)
16210 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16211 }
f4d7e40a
AS
16212
16213 /* all stack frames are accessible from callee, clear them all */
16214 for (j = 0; j <= cur->curframe; j++) {
16215 struct bpf_func_state *frame = cur->frame[j];
679c782d 16216 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 16217
679c782d 16218 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 16219 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
16220 frame->stack[i].spilled_ptr.parent =
16221 &newframe->stack[i].spilled_ptr;
16222 }
f4d7e40a 16223 }
f1bca824
AS
16224 return 0;
16225}
16226
c64b7983
JS
16227/* Return true if it's OK to have the same insn return a different type. */
16228static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16229{
c25b2ae1 16230 switch (base_type(type)) {
c64b7983
JS
16231 case PTR_TO_CTX:
16232 case PTR_TO_SOCKET:
46f8bc92 16233 case PTR_TO_SOCK_COMMON:
655a51e5 16234 case PTR_TO_TCP_SOCK:
fada7fdc 16235 case PTR_TO_XDP_SOCK:
2a02759e 16236 case PTR_TO_BTF_ID:
c64b7983
JS
16237 return false;
16238 default:
16239 return true;
16240 }
16241}
16242
16243/* If an instruction was previously used with particular pointer types, then we
16244 * need to be careful to avoid cases such as the below, where it may be ok
16245 * for one branch accessing the pointer, but not ok for the other branch:
16246 *
16247 * R1 = sock_ptr
16248 * goto X;
16249 * ...
16250 * R1 = some_other_valid_ptr;
16251 * goto X;
16252 * ...
16253 * R2 = *(u32 *)(R1 + 0);
16254 */
16255static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16256{
16257 return src != prev && (!reg_type_mismatch_ok(src) ||
16258 !reg_type_mismatch_ok(prev));
16259}
16260
0d80a619
EZ
16261static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16262 bool allow_trust_missmatch)
16263{
16264 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16265
16266 if (*prev_type == NOT_INIT) {
16267 /* Saw a valid insn
16268 * dst_reg = *(u32 *)(src_reg + off)
16269 * save type to validate intersecting paths
16270 */
16271 *prev_type = type;
16272 } else if (reg_type_mismatch(type, *prev_type)) {
16273 /* Abuser program is trying to use the same insn
16274 * dst_reg = *(u32*) (src_reg + off)
16275 * with different pointer types:
16276 * src_reg == ctx in one branch and
16277 * src_reg == stack|map in some other branch.
16278 * Reject it.
16279 */
16280 if (allow_trust_missmatch &&
16281 base_type(type) == PTR_TO_BTF_ID &&
16282 base_type(*prev_type) == PTR_TO_BTF_ID) {
16283 /*
16284 * Have to support a use case when one path through
16285 * the program yields TRUSTED pointer while another
16286 * is UNTRUSTED. Fallback to UNTRUSTED to generate
1f9a1ea8 16287 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
0d80a619
EZ
16288 */
16289 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16290 } else {
16291 verbose(env, "same insn cannot be used with different pointers\n");
16292 return -EINVAL;
16293 }
16294 }
16295
16296 return 0;
16297}
16298
58e2af8b 16299static int do_check(struct bpf_verifier_env *env)
17a52670 16300{
6f8a57cc 16301 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 16302 struct bpf_verifier_state *state = env->cur_state;
17a52670 16303 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 16304 struct bpf_reg_state *regs;
06ee7115 16305 int insn_cnt = env->prog->len;
17a52670 16306 bool do_print_state = false;
b5dc0163 16307 int prev_insn_idx = -1;
17a52670 16308
17a52670
AS
16309 for (;;) {
16310 struct bpf_insn *insn;
16311 u8 class;
16312 int err;
16313
b5dc0163 16314 env->prev_insn_idx = prev_insn_idx;
c08435ec 16315 if (env->insn_idx >= insn_cnt) {
61bd5218 16316 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 16317 env->insn_idx, insn_cnt);
17a52670
AS
16318 return -EFAULT;
16319 }
16320
c08435ec 16321 insn = &insns[env->insn_idx];
17a52670
AS
16322 class = BPF_CLASS(insn->code);
16323
06ee7115 16324 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
16325 verbose(env,
16326 "BPF program is too large. Processed %d insn\n",
06ee7115 16327 env->insn_processed);
17a52670
AS
16328 return -E2BIG;
16329 }
16330
a095f421
AN
16331 state->last_insn_idx = env->prev_insn_idx;
16332
16333 if (is_prune_point(env, env->insn_idx)) {
16334 err = is_state_visited(env, env->insn_idx);
16335 if (err < 0)
16336 return err;
16337 if (err == 1) {
16338 /* found equivalent state, can prune the search */
16339 if (env->log.level & BPF_LOG_LEVEL) {
16340 if (do_print_state)
16341 verbose(env, "\nfrom %d to %d%s: safe\n",
16342 env->prev_insn_idx, env->insn_idx,
16343 env->cur_state->speculative ?
16344 " (speculative execution)" : "");
16345 else
16346 verbose(env, "%d: safe\n", env->insn_idx);
16347 }
16348 goto process_bpf_exit;
f1bca824 16349 }
a095f421
AN
16350 }
16351
16352 if (is_jmp_point(env, env->insn_idx)) {
16353 err = push_jmp_history(env, state);
16354 if (err)
16355 return err;
f1bca824
AS
16356 }
16357
c3494801
AS
16358 if (signal_pending(current))
16359 return -EAGAIN;
16360
3c2ce60b
DB
16361 if (need_resched())
16362 cond_resched();
16363
2e576648
CL
16364 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16365 verbose(env, "\nfrom %d to %d%s:",
16366 env->prev_insn_idx, env->insn_idx,
16367 env->cur_state->speculative ?
16368 " (speculative execution)" : "");
16369 print_verifier_state(env, state->frame[state->curframe], true);
17a52670
AS
16370 do_print_state = false;
16371 }
16372
06ee7115 16373 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 16374 const struct bpf_insn_cbs cbs = {
e6ac2450 16375 .cb_call = disasm_kfunc_name,
7105e828 16376 .cb_print = verbose,
abe08840 16377 .private_data = env,
7105e828
DB
16378 };
16379
2e576648
CL
16380 if (verifier_state_scratched(env))
16381 print_insn_state(env, state->frame[state->curframe]);
16382
c08435ec 16383 verbose_linfo(env, env->insn_idx, "; ");
12166409 16384 env->prev_log_pos = env->log.end_pos;
c08435ec 16385 verbose(env, "%d: ", env->insn_idx);
abe08840 16386 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12166409
AN
16387 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16388 env->prev_log_pos = env->log.end_pos;
17a52670
AS
16389 }
16390
9d03ebc7 16391 if (bpf_prog_is_offloaded(env->prog->aux)) {
c08435ec
DB
16392 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16393 env->prev_insn_idx);
cae1927c
JK
16394 if (err)
16395 return err;
16396 }
13a27dfc 16397
638f5b90 16398 regs = cur_regs(env);
fe9a5ca7 16399 sanitize_mark_insn_seen(env);
b5dc0163 16400 prev_insn_idx = env->insn_idx;
fd978bf7 16401
17a52670 16402 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 16403 err = check_alu_op(env, insn);
17a52670
AS
16404 if (err)
16405 return err;
16406
16407 } else if (class == BPF_LDX) {
0d80a619 16408 enum bpf_reg_type src_reg_type;
9bac3d6d
AS
16409
16410 /* check for reserved fields is already done */
16411
17a52670 16412 /* check src operand */
dc503a8a 16413 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
16414 if (err)
16415 return err;
16416
dc503a8a 16417 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
16418 if (err)
16419 return err;
16420
725f9dcd
AS
16421 src_reg_type = regs[insn->src_reg].type;
16422
17a52670
AS
16423 /* check that memory (src_reg + off) is readable,
16424 * the state of dst_reg will be updated by this func
16425 */
c08435ec
DB
16426 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16427 insn->off, BPF_SIZE(insn->code),
1f9a1ea8
YS
16428 BPF_READ, insn->dst_reg, false,
16429 BPF_MODE(insn->code) == BPF_MEMSX);
17a52670
AS
16430 if (err)
16431 return err;
16432
0d80a619
EZ
16433 err = save_aux_ptr_type(env, src_reg_type, true);
16434 if (err)
16435 return err;
17a52670 16436 } else if (class == BPF_STX) {
0d80a619 16437 enum bpf_reg_type dst_reg_type;
d691f9e8 16438
91c960b0
BJ
16439 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16440 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
16441 if (err)
16442 return err;
c08435ec 16443 env->insn_idx++;
17a52670
AS
16444 continue;
16445 }
16446
5ca419f2
BJ
16447 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16448 verbose(env, "BPF_STX uses reserved fields\n");
16449 return -EINVAL;
16450 }
16451
17a52670 16452 /* check src1 operand */
dc503a8a 16453 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
16454 if (err)
16455 return err;
16456 /* check src2 operand */
dc503a8a 16457 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
16458 if (err)
16459 return err;
16460
d691f9e8
AS
16461 dst_reg_type = regs[insn->dst_reg].type;
16462
17a52670 16463 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
16464 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16465 insn->off, BPF_SIZE(insn->code),
1f9a1ea8 16466 BPF_WRITE, insn->src_reg, false, false);
17a52670
AS
16467 if (err)
16468 return err;
16469
0d80a619
EZ
16470 err = save_aux_ptr_type(env, dst_reg_type, false);
16471 if (err)
16472 return err;
17a52670 16473 } else if (class == BPF_ST) {
0d80a619
EZ
16474 enum bpf_reg_type dst_reg_type;
16475
17a52670
AS
16476 if (BPF_MODE(insn->code) != BPF_MEM ||
16477 insn->src_reg != BPF_REG_0) {
61bd5218 16478 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
16479 return -EINVAL;
16480 }
16481 /* check src operand */
dc503a8a 16482 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
16483 if (err)
16484 return err;
16485
0d80a619 16486 dst_reg_type = regs[insn->dst_reg].type;
f37a8cb8 16487
17a52670 16488 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
16489 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16490 insn->off, BPF_SIZE(insn->code),
1f9a1ea8 16491 BPF_WRITE, -1, false, false);
17a52670
AS
16492 if (err)
16493 return err;
16494
0d80a619
EZ
16495 err = save_aux_ptr_type(env, dst_reg_type, false);
16496 if (err)
16497 return err;
092ed096 16498 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
16499 u8 opcode = BPF_OP(insn->code);
16500
2589726d 16501 env->jmps_processed++;
17a52670
AS
16502 if (opcode == BPF_CALL) {
16503 if (BPF_SRC(insn->code) != BPF_K ||
2357672c
KKD
16504 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16505 && insn->off != 0) ||
f4d7e40a 16506 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
16507 insn->src_reg != BPF_PSEUDO_CALL &&
16508 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
16509 insn->dst_reg != BPF_REG_0 ||
16510 class == BPF_JMP32) {
61bd5218 16511 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
16512 return -EINVAL;
16513 }
16514
8cab76ec
KKD
16515 if (env->cur_state->active_lock.ptr) {
16516 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16517 (insn->src_reg == BPF_PSEUDO_CALL) ||
16518 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
cd6791b4 16519 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
8cab76ec
KKD
16520 verbose(env, "function calls are not allowed while holding a lock\n");
16521 return -EINVAL;
16522 }
d83525ca 16523 }
f4d7e40a 16524 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 16525 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450 16526 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
5c073f26 16527 err = check_kfunc_call(env, insn, &env->insn_idx);
f4d7e40a 16528 else
69c087ba 16529 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
16530 if (err)
16531 return err;
553a64a8
AN
16532
16533 mark_reg_scratched(env, BPF_REG_0);
17a52670
AS
16534 } else if (opcode == BPF_JA) {
16535 if (BPF_SRC(insn->code) != BPF_K ||
16536 insn->imm != 0 ||
16537 insn->src_reg != BPF_REG_0 ||
092ed096
JW
16538 insn->dst_reg != BPF_REG_0 ||
16539 class == BPF_JMP32) {
61bd5218 16540 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
16541 return -EINVAL;
16542 }
16543
c08435ec 16544 env->insn_idx += insn->off + 1;
17a52670
AS
16545 continue;
16546
16547 } else if (opcode == BPF_EXIT) {
16548 if (BPF_SRC(insn->code) != BPF_K ||
16549 insn->imm != 0 ||
16550 insn->src_reg != BPF_REG_0 ||
092ed096
JW
16551 insn->dst_reg != BPF_REG_0 ||
16552 class == BPF_JMP32) {
61bd5218 16553 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
16554 return -EINVAL;
16555 }
16556
5d92ddc3
DM
16557 if (env->cur_state->active_lock.ptr &&
16558 !in_rbtree_lock_required_cb(env)) {
d83525ca
AS
16559 verbose(env, "bpf_spin_unlock is missing\n");
16560 return -EINVAL;
16561 }
16562
9bb00b28
YS
16563 if (env->cur_state->active_rcu_lock) {
16564 verbose(env, "bpf_rcu_read_unlock is missing\n");
16565 return -EINVAL;
16566 }
16567
9d9d00ac
KKD
16568 /* We must do check_reference_leak here before
16569 * prepare_func_exit to handle the case when
16570 * state->curframe > 0, it may be a callback
16571 * function, for which reference_state must
16572 * match caller reference state when it exits.
16573 */
16574 err = check_reference_leak(env);
16575 if (err)
16576 return err;
16577
f4d7e40a
AS
16578 if (state->curframe) {
16579 /* exit from nested function */
c08435ec 16580 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
16581 if (err)
16582 return err;
16583 do_print_state = true;
16584 continue;
16585 }
16586
390ee7e2
AS
16587 err = check_return_code(env);
16588 if (err)
16589 return err;
f1bca824 16590process_bpf_exit:
0f55f9ed 16591 mark_verifier_state_scratched(env);
2589726d 16592 update_branch_counts(env, env->cur_state);
b5dc0163 16593 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 16594 &env->insn_idx, pop_log);
638f5b90
AS
16595 if (err < 0) {
16596 if (err != -ENOENT)
16597 return err;
17a52670
AS
16598 break;
16599 } else {
16600 do_print_state = true;
16601 continue;
16602 }
16603 } else {
c08435ec 16604 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
16605 if (err)
16606 return err;
16607 }
16608 } else if (class == BPF_LD) {
16609 u8 mode = BPF_MODE(insn->code);
16610
16611 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
16612 err = check_ld_abs(env, insn);
16613 if (err)
16614 return err;
16615
17a52670
AS
16616 } else if (mode == BPF_IMM) {
16617 err = check_ld_imm(env, insn);
16618 if (err)
16619 return err;
16620
c08435ec 16621 env->insn_idx++;
fe9a5ca7 16622 sanitize_mark_insn_seen(env);
17a52670 16623 } else {
61bd5218 16624 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
16625 return -EINVAL;
16626 }
16627 } else {
61bd5218 16628 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
16629 return -EINVAL;
16630 }
16631
c08435ec 16632 env->insn_idx++;
17a52670
AS
16633 }
16634
16635 return 0;
16636}
16637
541c3bad
AN
16638static int find_btf_percpu_datasec(struct btf *btf)
16639{
16640 const struct btf_type *t;
16641 const char *tname;
16642 int i, n;
16643
16644 /*
16645 * Both vmlinux and module each have their own ".data..percpu"
16646 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16647 * types to look at only module's own BTF types.
16648 */
16649 n = btf_nr_types(btf);
16650 if (btf_is_module(btf))
16651 i = btf_nr_types(btf_vmlinux);
16652 else
16653 i = 1;
16654
16655 for(; i < n; i++) {
16656 t = btf_type_by_id(btf, i);
16657 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16658 continue;
16659
16660 tname = btf_name_by_offset(btf, t->name_off);
16661 if (!strcmp(tname, ".data..percpu"))
16662 return i;
16663 }
16664
16665 return -ENOENT;
16666}
16667
4976b718
HL
16668/* replace pseudo btf_id with kernel symbol address */
16669static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16670 struct bpf_insn *insn,
16671 struct bpf_insn_aux_data *aux)
16672{
eaa6bcb7
HL
16673 const struct btf_var_secinfo *vsi;
16674 const struct btf_type *datasec;
541c3bad 16675 struct btf_mod_pair *btf_mod;
4976b718
HL
16676 const struct btf_type *t;
16677 const char *sym_name;
eaa6bcb7 16678 bool percpu = false;
f16e6313 16679 u32 type, id = insn->imm;
541c3bad 16680 struct btf *btf;
f16e6313 16681 s32 datasec_id;
4976b718 16682 u64 addr;
541c3bad 16683 int i, btf_fd, err;
4976b718 16684
541c3bad
AN
16685 btf_fd = insn[1].imm;
16686 if (btf_fd) {
16687 btf = btf_get_by_fd(btf_fd);
16688 if (IS_ERR(btf)) {
16689 verbose(env, "invalid module BTF object FD specified.\n");
16690 return -EINVAL;
16691 }
16692 } else {
16693 if (!btf_vmlinux) {
16694 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16695 return -EINVAL;
16696 }
16697 btf = btf_vmlinux;
16698 btf_get(btf);
4976b718
HL
16699 }
16700
541c3bad 16701 t = btf_type_by_id(btf, id);
4976b718
HL
16702 if (!t) {
16703 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
16704 err = -ENOENT;
16705 goto err_put;
4976b718
HL
16706 }
16707
58aa2afb
AS
16708 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16709 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
541c3bad
AN
16710 err = -EINVAL;
16711 goto err_put;
4976b718
HL
16712 }
16713
541c3bad 16714 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
16715 addr = kallsyms_lookup_name(sym_name);
16716 if (!addr) {
16717 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16718 sym_name);
541c3bad
AN
16719 err = -ENOENT;
16720 goto err_put;
4976b718 16721 }
58aa2afb
AS
16722 insn[0].imm = (u32)addr;
16723 insn[1].imm = addr >> 32;
16724
16725 if (btf_type_is_func(t)) {
16726 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16727 aux->btf_var.mem_size = 0;
16728 goto check_btf;
16729 }
4976b718 16730
541c3bad 16731 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 16732 if (datasec_id > 0) {
541c3bad 16733 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
16734 for_each_vsi(i, datasec, vsi) {
16735 if (vsi->type == id) {
16736 percpu = true;
16737 break;
16738 }
16739 }
16740 }
16741
4976b718 16742 type = t->type;
541c3bad 16743 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7 16744 if (percpu) {
5844101a 16745 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
541c3bad 16746 aux->btf_var.btf = btf;
eaa6bcb7
HL
16747 aux->btf_var.btf_id = type;
16748 } else if (!btf_type_is_struct(t)) {
4976b718
HL
16749 const struct btf_type *ret;
16750 const char *tname;
16751 u32 tsize;
16752
16753 /* resolve the type size of ksym. */
541c3bad 16754 ret = btf_resolve_size(btf, t, &tsize);
4976b718 16755 if (IS_ERR(ret)) {
541c3bad 16756 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
16757 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16758 tname, PTR_ERR(ret));
541c3bad
AN
16759 err = -EINVAL;
16760 goto err_put;
4976b718 16761 }
34d3a78c 16762 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
4976b718
HL
16763 aux->btf_var.mem_size = tsize;
16764 } else {
16765 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 16766 aux->btf_var.btf = btf;
4976b718
HL
16767 aux->btf_var.btf_id = type;
16768 }
58aa2afb 16769check_btf:
541c3bad
AN
16770 /* check whether we recorded this BTF (and maybe module) already */
16771 for (i = 0; i < env->used_btf_cnt; i++) {
16772 if (env->used_btfs[i].btf == btf) {
16773 btf_put(btf);
16774 return 0;
16775 }
16776 }
16777
16778 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16779 err = -E2BIG;
16780 goto err_put;
16781 }
16782
16783 btf_mod = &env->used_btfs[env->used_btf_cnt];
16784 btf_mod->btf = btf;
16785 btf_mod->module = NULL;
16786
16787 /* if we reference variables from kernel module, bump its refcount */
16788 if (btf_is_module(btf)) {
16789 btf_mod->module = btf_try_get_module(btf);
16790 if (!btf_mod->module) {
16791 err = -ENXIO;
16792 goto err_put;
16793 }
16794 }
16795
16796 env->used_btf_cnt++;
16797
4976b718 16798 return 0;
541c3bad
AN
16799err_put:
16800 btf_put(btf);
16801 return err;
4976b718
HL
16802}
16803
d83525ca
AS
16804static bool is_tracing_prog_type(enum bpf_prog_type type)
16805{
16806 switch (type) {
16807 case BPF_PROG_TYPE_KPROBE:
16808 case BPF_PROG_TYPE_TRACEPOINT:
16809 case BPF_PROG_TYPE_PERF_EVENT:
16810 case BPF_PROG_TYPE_RAW_TRACEPOINT:
5002615a 16811 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
d83525ca
AS
16812 return true;
16813 default:
16814 return false;
16815 }
16816}
16817
61bd5218
JK
16818static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16819 struct bpf_map *map,
fdc15d38
AS
16820 struct bpf_prog *prog)
16821
16822{
7e40781c 16823 enum bpf_prog_type prog_type = resolve_prog_type(prog);
a3884572 16824
9c395c1b
DM
16825 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16826 btf_record_has_field(map->record, BPF_RB_ROOT)) {
f0c5941f 16827 if (is_tracing_prog_type(prog_type)) {
9c395c1b 16828 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
f0c5941f
KKD
16829 return -EINVAL;
16830 }
16831 }
16832
db559117 16833 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
9e7a4d98
KS
16834 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16835 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16836 return -EINVAL;
16837 }
16838
16839 if (is_tracing_prog_type(prog_type)) {
16840 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16841 return -EINVAL;
16842 }
16843
16844 if (prog->aux->sleepable) {
16845 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16846 return -EINVAL;
16847 }
d83525ca
AS
16848 }
16849
db559117 16850 if (btf_record_has_field(map->record, BPF_TIMER)) {
5e0bc308
DB
16851 if (is_tracing_prog_type(prog_type)) {
16852 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16853 return -EINVAL;
16854 }
16855 }
16856
9d03ebc7 16857 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
09728266 16858 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
16859 verbose(env, "offload device mismatch between prog and map\n");
16860 return -EINVAL;
16861 }
16862
85d33df3
MKL
16863 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16864 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16865 return -EINVAL;
16866 }
16867
1e6c62a8
AS
16868 if (prog->aux->sleepable)
16869 switch (map->map_type) {
16870 case BPF_MAP_TYPE_HASH:
16871 case BPF_MAP_TYPE_LRU_HASH:
16872 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
16873 case BPF_MAP_TYPE_PERCPU_HASH:
16874 case BPF_MAP_TYPE_PERCPU_ARRAY:
16875 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16876 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16877 case BPF_MAP_TYPE_HASH_OF_MAPS:
ba90c2cc 16878 case BPF_MAP_TYPE_RINGBUF:
583c1f42 16879 case BPF_MAP_TYPE_USER_RINGBUF:
0fe4b381
KS
16880 case BPF_MAP_TYPE_INODE_STORAGE:
16881 case BPF_MAP_TYPE_SK_STORAGE:
16882 case BPF_MAP_TYPE_TASK_STORAGE:
2c40d97d 16883 case BPF_MAP_TYPE_CGRP_STORAGE:
ba90c2cc 16884 break;
1e6c62a8
AS
16885 default:
16886 verbose(env,
2c40d97d 16887 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
1e6c62a8
AS
16888 return -EINVAL;
16889 }
16890
fdc15d38
AS
16891 return 0;
16892}
16893
b741f163
RG
16894static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16895{
16896 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16897 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16898}
16899
4976b718
HL
16900/* find and rewrite pseudo imm in ld_imm64 instructions:
16901 *
16902 * 1. if it accesses map FD, replace it with actual map pointer.
16903 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16904 *
16905 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 16906 */
4976b718 16907static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
16908{
16909 struct bpf_insn *insn = env->prog->insnsi;
16910 int insn_cnt = env->prog->len;
fdc15d38 16911 int i, j, err;
0246e64d 16912
f1f7714e 16913 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
16914 if (err)
16915 return err;
16916
0246e64d 16917 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 16918 if (BPF_CLASS(insn->code) == BPF_LDX &&
1f9a1ea8
YS
16919 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
16920 insn->imm != 0)) {
61bd5218 16921 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
16922 return -EINVAL;
16923 }
16924
0246e64d 16925 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 16926 struct bpf_insn_aux_data *aux;
0246e64d
AS
16927 struct bpf_map *map;
16928 struct fd f;
d8eca5bb 16929 u64 addr;
387544bf 16930 u32 fd;
0246e64d
AS
16931
16932 if (i == insn_cnt - 1 || insn[1].code != 0 ||
16933 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16934 insn[1].off != 0) {
61bd5218 16935 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
16936 return -EINVAL;
16937 }
16938
d8eca5bb 16939 if (insn[0].src_reg == 0)
0246e64d
AS
16940 /* valid generic load 64-bit imm */
16941 goto next_insn;
16942
4976b718
HL
16943 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16944 aux = &env->insn_aux_data[i];
16945 err = check_pseudo_btf_id(env, insn, aux);
16946 if (err)
16947 return err;
16948 goto next_insn;
16949 }
16950
69c087ba
YS
16951 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16952 aux = &env->insn_aux_data[i];
16953 aux->ptr_type = PTR_TO_FUNC;
16954 goto next_insn;
16955 }
16956
d8eca5bb
DB
16957 /* In final convert_pseudo_ld_imm64() step, this is
16958 * converted into regular 64-bit imm load insn.
16959 */
387544bf
AS
16960 switch (insn[0].src_reg) {
16961 case BPF_PSEUDO_MAP_VALUE:
16962 case BPF_PSEUDO_MAP_IDX_VALUE:
16963 break;
16964 case BPF_PSEUDO_MAP_FD:
16965 case BPF_PSEUDO_MAP_IDX:
16966 if (insn[1].imm == 0)
16967 break;
16968 fallthrough;
16969 default:
16970 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
16971 return -EINVAL;
16972 }
16973
387544bf
AS
16974 switch (insn[0].src_reg) {
16975 case BPF_PSEUDO_MAP_IDX_VALUE:
16976 case BPF_PSEUDO_MAP_IDX:
16977 if (bpfptr_is_null(env->fd_array)) {
16978 verbose(env, "fd_idx without fd_array is invalid\n");
16979 return -EPROTO;
16980 }
16981 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16982 insn[0].imm * sizeof(fd),
16983 sizeof(fd)))
16984 return -EFAULT;
16985 break;
16986 default:
16987 fd = insn[0].imm;
16988 break;
16989 }
16990
16991 f = fdget(fd);
c2101297 16992 map = __bpf_map_get(f);
0246e64d 16993 if (IS_ERR(map)) {
61bd5218 16994 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 16995 insn[0].imm);
0246e64d
AS
16996 return PTR_ERR(map);
16997 }
16998
61bd5218 16999 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
17000 if (err) {
17001 fdput(f);
17002 return err;
17003 }
17004
d8eca5bb 17005 aux = &env->insn_aux_data[i];
387544bf
AS
17006 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17007 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
d8eca5bb
DB
17008 addr = (unsigned long)map;
17009 } else {
17010 u32 off = insn[1].imm;
17011
17012 if (off >= BPF_MAX_VAR_OFF) {
17013 verbose(env, "direct value offset of %u is not allowed\n", off);
17014 fdput(f);
17015 return -EINVAL;
17016 }
17017
17018 if (!map->ops->map_direct_value_addr) {
17019 verbose(env, "no direct value access support for this map type\n");
17020 fdput(f);
17021 return -EINVAL;
17022 }
17023
17024 err = map->ops->map_direct_value_addr(map, &addr, off);
17025 if (err) {
17026 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17027 map->value_size, off);
17028 fdput(f);
17029 return err;
17030 }
17031
17032 aux->map_off = off;
17033 addr += off;
17034 }
17035
17036 insn[0].imm = (u32)addr;
17037 insn[1].imm = addr >> 32;
0246e64d
AS
17038
17039 /* check whether we recorded this map already */
d8eca5bb 17040 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 17041 if (env->used_maps[j] == map) {
d8eca5bb 17042 aux->map_index = j;
0246e64d
AS
17043 fdput(f);
17044 goto next_insn;
17045 }
d8eca5bb 17046 }
0246e64d
AS
17047
17048 if (env->used_map_cnt >= MAX_USED_MAPS) {
17049 fdput(f);
17050 return -E2BIG;
17051 }
17052
0246e64d
AS
17053 /* hold the map. If the program is rejected by verifier,
17054 * the map will be released by release_maps() or it
17055 * will be used by the valid program until it's unloaded
ab7f5bf0 17056 * and all maps are released in free_used_maps()
0246e64d 17057 */
1e0bd5a0 17058 bpf_map_inc(map);
d8eca5bb
DB
17059
17060 aux->map_index = env->used_map_cnt;
92117d84
AS
17061 env->used_maps[env->used_map_cnt++] = map;
17062
b741f163 17063 if (bpf_map_is_cgroup_storage(map) &&
e4730423 17064 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 17065 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
17066 fdput(f);
17067 return -EBUSY;
17068 }
17069
0246e64d
AS
17070 fdput(f);
17071next_insn:
17072 insn++;
17073 i++;
5e581dad
DB
17074 continue;
17075 }
17076
17077 /* Basic sanity check before we invest more work here. */
17078 if (!bpf_opcode_in_insntable(insn->code)) {
17079 verbose(env, "unknown opcode %02x\n", insn->code);
17080 return -EINVAL;
0246e64d
AS
17081 }
17082 }
17083
17084 /* now all pseudo BPF_LD_IMM64 instructions load valid
17085 * 'struct bpf_map *' into a register instead of user map_fd.
17086 * These pointers will be used later by verifier to validate map access.
17087 */
17088 return 0;
17089}
17090
17091/* drop refcnt of maps used by the rejected program */
58e2af8b 17092static void release_maps(struct bpf_verifier_env *env)
0246e64d 17093{
a2ea0746
DB
17094 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17095 env->used_map_cnt);
0246e64d
AS
17096}
17097
541c3bad
AN
17098/* drop refcnt of maps used by the rejected program */
17099static void release_btfs(struct bpf_verifier_env *env)
17100{
17101 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17102 env->used_btf_cnt);
17103}
17104
0246e64d 17105/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 17106static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
17107{
17108 struct bpf_insn *insn = env->prog->insnsi;
17109 int insn_cnt = env->prog->len;
17110 int i;
17111
69c087ba
YS
17112 for (i = 0; i < insn_cnt; i++, insn++) {
17113 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17114 continue;
17115 if (insn->src_reg == BPF_PSEUDO_FUNC)
17116 continue;
17117 insn->src_reg = 0;
17118 }
0246e64d
AS
17119}
17120
8041902d
AS
17121/* single env->prog->insni[off] instruction was replaced with the range
17122 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17123 * [0, off) and [off, end) to new locations, so the patched range stays zero
17124 */
75f0fc7b
HF
17125static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17126 struct bpf_insn_aux_data *new_data,
17127 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d 17128{
75f0fc7b 17129 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
b325fbca 17130 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 17131 u32 old_seen = old_data[off].seen;
b325fbca 17132 u32 prog_len;
c131187d 17133 int i;
8041902d 17134
b325fbca
JW
17135 /* aux info at OFF always needs adjustment, no matter fast path
17136 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17137 * original insn at old prog.
17138 */
17139 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17140
8041902d 17141 if (cnt == 1)
75f0fc7b 17142 return;
b325fbca 17143 prog_len = new_prog->len;
75f0fc7b 17144
8041902d
AS
17145 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17146 memcpy(new_data + off + cnt - 1, old_data + off,
17147 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 17148 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
17149 /* Expand insni[off]'s seen count to the patched range. */
17150 new_data[i].seen = old_seen;
b325fbca
JW
17151 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17152 }
8041902d
AS
17153 env->insn_aux_data = new_data;
17154 vfree(old_data);
8041902d
AS
17155}
17156
cc8b0b92
AS
17157static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17158{
17159 int i;
17160
17161 if (len == 1)
17162 return;
4cb3d99c
JW
17163 /* NOTE: fake 'exit' subprog should be updated as well. */
17164 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 17165 if (env->subprog_info[i].start <= off)
cc8b0b92 17166 continue;
9c8105bd 17167 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
17168 }
17169}
17170
7506d211 17171static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
a748c697
MF
17172{
17173 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17174 int i, sz = prog->aux->size_poke_tab;
17175 struct bpf_jit_poke_descriptor *desc;
17176
17177 for (i = 0; i < sz; i++) {
17178 desc = &tab[i];
7506d211
JF
17179 if (desc->insn_idx <= off)
17180 continue;
a748c697
MF
17181 desc->insn_idx += len - 1;
17182 }
17183}
17184
8041902d
AS
17185static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17186 const struct bpf_insn *patch, u32 len)
17187{
17188 struct bpf_prog *new_prog;
75f0fc7b
HF
17189 struct bpf_insn_aux_data *new_data = NULL;
17190
17191 if (len > 1) {
17192 new_data = vzalloc(array_size(env->prog->len + len - 1,
17193 sizeof(struct bpf_insn_aux_data)));
17194 if (!new_data)
17195 return NULL;
17196 }
8041902d
AS
17197
17198 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
17199 if (IS_ERR(new_prog)) {
17200 if (PTR_ERR(new_prog) == -ERANGE)
17201 verbose(env,
17202 "insn %d cannot be patched due to 16-bit range\n",
17203 env->insn_aux_data[off].orig_idx);
75f0fc7b 17204 vfree(new_data);
8041902d 17205 return NULL;
4f73379e 17206 }
75f0fc7b 17207 adjust_insn_aux_data(env, new_data, new_prog, off, len);
cc8b0b92 17208 adjust_subprog_starts(env, off, len);
7506d211 17209 adjust_poke_descs(new_prog, off, len);
8041902d
AS
17210 return new_prog;
17211}
17212
52875a04
JK
17213static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17214 u32 off, u32 cnt)
17215{
17216 int i, j;
17217
17218 /* find first prog starting at or after off (first to remove) */
17219 for (i = 0; i < env->subprog_cnt; i++)
17220 if (env->subprog_info[i].start >= off)
17221 break;
17222 /* find first prog starting at or after off + cnt (first to stay) */
17223 for (j = i; j < env->subprog_cnt; j++)
17224 if (env->subprog_info[j].start >= off + cnt)
17225 break;
17226 /* if j doesn't start exactly at off + cnt, we are just removing
17227 * the front of previous prog
17228 */
17229 if (env->subprog_info[j].start != off + cnt)
17230 j--;
17231
17232 if (j > i) {
17233 struct bpf_prog_aux *aux = env->prog->aux;
17234 int move;
17235
17236 /* move fake 'exit' subprog as well */
17237 move = env->subprog_cnt + 1 - j;
17238
17239 memmove(env->subprog_info + i,
17240 env->subprog_info + j,
17241 sizeof(*env->subprog_info) * move);
17242 env->subprog_cnt -= j - i;
17243
17244 /* remove func_info */
17245 if (aux->func_info) {
17246 move = aux->func_info_cnt - j;
17247
17248 memmove(aux->func_info + i,
17249 aux->func_info + j,
17250 sizeof(*aux->func_info) * move);
17251 aux->func_info_cnt -= j - i;
17252 /* func_info->insn_off is set after all code rewrites,
17253 * in adjust_btf_func() - no need to adjust
17254 */
17255 }
17256 } else {
17257 /* convert i from "first prog to remove" to "first to adjust" */
17258 if (env->subprog_info[i].start == off)
17259 i++;
17260 }
17261
17262 /* update fake 'exit' subprog as well */
17263 for (; i <= env->subprog_cnt; i++)
17264 env->subprog_info[i].start -= cnt;
17265
17266 return 0;
17267}
17268
17269static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17270 u32 cnt)
17271{
17272 struct bpf_prog *prog = env->prog;
17273 u32 i, l_off, l_cnt, nr_linfo;
17274 struct bpf_line_info *linfo;
17275
17276 nr_linfo = prog->aux->nr_linfo;
17277 if (!nr_linfo)
17278 return 0;
17279
17280 linfo = prog->aux->linfo;
17281
17282 /* find first line info to remove, count lines to be removed */
17283 for (i = 0; i < nr_linfo; i++)
17284 if (linfo[i].insn_off >= off)
17285 break;
17286
17287 l_off = i;
17288 l_cnt = 0;
17289 for (; i < nr_linfo; i++)
17290 if (linfo[i].insn_off < off + cnt)
17291 l_cnt++;
17292 else
17293 break;
17294
17295 /* First live insn doesn't match first live linfo, it needs to "inherit"
17296 * last removed linfo. prog is already modified, so prog->len == off
17297 * means no live instructions after (tail of the program was removed).
17298 */
17299 if (prog->len != off && l_cnt &&
17300 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17301 l_cnt--;
17302 linfo[--i].insn_off = off + cnt;
17303 }
17304
17305 /* remove the line info which refer to the removed instructions */
17306 if (l_cnt) {
17307 memmove(linfo + l_off, linfo + i,
17308 sizeof(*linfo) * (nr_linfo - i));
17309
17310 prog->aux->nr_linfo -= l_cnt;
17311 nr_linfo = prog->aux->nr_linfo;
17312 }
17313
17314 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17315 for (i = l_off; i < nr_linfo; i++)
17316 linfo[i].insn_off -= cnt;
17317
17318 /* fix up all subprogs (incl. 'exit') which start >= off */
17319 for (i = 0; i <= env->subprog_cnt; i++)
17320 if (env->subprog_info[i].linfo_idx > l_off) {
17321 /* program may have started in the removed region but
17322 * may not be fully removed
17323 */
17324 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17325 env->subprog_info[i].linfo_idx -= l_cnt;
17326 else
17327 env->subprog_info[i].linfo_idx = l_off;
17328 }
17329
17330 return 0;
17331}
17332
17333static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17334{
17335 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17336 unsigned int orig_prog_len = env->prog->len;
17337 int err;
17338
9d03ebc7 17339 if (bpf_prog_is_offloaded(env->prog->aux))
08ca90af
JK
17340 bpf_prog_offload_remove_insns(env, off, cnt);
17341
52875a04
JK
17342 err = bpf_remove_insns(env->prog, off, cnt);
17343 if (err)
17344 return err;
17345
17346 err = adjust_subprog_starts_after_remove(env, off, cnt);
17347 if (err)
17348 return err;
17349
17350 err = bpf_adj_linfo_after_remove(env, off, cnt);
17351 if (err)
17352 return err;
17353
17354 memmove(aux_data + off, aux_data + off + cnt,
17355 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17356
17357 return 0;
17358}
17359
2a5418a1
DB
17360/* The verifier does more data flow analysis than llvm and will not
17361 * explore branches that are dead at run time. Malicious programs can
17362 * have dead code too. Therefore replace all dead at-run-time code
17363 * with 'ja -1'.
17364 *
17365 * Just nops are not optimal, e.g. if they would sit at the end of the
17366 * program and through another bug we would manage to jump there, then
17367 * we'd execute beyond program memory otherwise. Returning exception
17368 * code also wouldn't work since we can have subprogs where the dead
17369 * code could be located.
c131187d
AS
17370 */
17371static void sanitize_dead_code(struct bpf_verifier_env *env)
17372{
17373 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 17374 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
17375 struct bpf_insn *insn = env->prog->insnsi;
17376 const int insn_cnt = env->prog->len;
17377 int i;
17378
17379 for (i = 0; i < insn_cnt; i++) {
17380 if (aux_data[i].seen)
17381 continue;
2a5418a1 17382 memcpy(insn + i, &trap, sizeof(trap));
45c709f8 17383 aux_data[i].zext_dst = false;
c131187d
AS
17384 }
17385}
17386
e2ae4ca2
JK
17387static bool insn_is_cond_jump(u8 code)
17388{
17389 u8 op;
17390
092ed096
JW
17391 if (BPF_CLASS(code) == BPF_JMP32)
17392 return true;
17393
e2ae4ca2
JK
17394 if (BPF_CLASS(code) != BPF_JMP)
17395 return false;
17396
17397 op = BPF_OP(code);
17398 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17399}
17400
17401static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17402{
17403 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17404 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17405 struct bpf_insn *insn = env->prog->insnsi;
17406 const int insn_cnt = env->prog->len;
17407 int i;
17408
17409 for (i = 0; i < insn_cnt; i++, insn++) {
17410 if (!insn_is_cond_jump(insn->code))
17411 continue;
17412
17413 if (!aux_data[i + 1].seen)
17414 ja.off = insn->off;
17415 else if (!aux_data[i + 1 + insn->off].seen)
17416 ja.off = 0;
17417 else
17418 continue;
17419
9d03ebc7 17420 if (bpf_prog_is_offloaded(env->prog->aux))
08ca90af
JK
17421 bpf_prog_offload_replace_insn(env, i, &ja);
17422
e2ae4ca2
JK
17423 memcpy(insn, &ja, sizeof(ja));
17424 }
17425}
17426
52875a04
JK
17427static int opt_remove_dead_code(struct bpf_verifier_env *env)
17428{
17429 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17430 int insn_cnt = env->prog->len;
17431 int i, err;
17432
17433 for (i = 0; i < insn_cnt; i++) {
17434 int j;
17435
17436 j = 0;
17437 while (i + j < insn_cnt && !aux_data[i + j].seen)
17438 j++;
17439 if (!j)
17440 continue;
17441
17442 err = verifier_remove_insns(env, i, j);
17443 if (err)
17444 return err;
17445 insn_cnt = env->prog->len;
17446 }
17447
17448 return 0;
17449}
17450
a1b14abc
JK
17451static int opt_remove_nops(struct bpf_verifier_env *env)
17452{
17453 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17454 struct bpf_insn *insn = env->prog->insnsi;
17455 int insn_cnt = env->prog->len;
17456 int i, err;
17457
17458 for (i = 0; i < insn_cnt; i++) {
17459 if (memcmp(&insn[i], &ja, sizeof(ja)))
17460 continue;
17461
17462 err = verifier_remove_insns(env, i, 1);
17463 if (err)
17464 return err;
17465 insn_cnt--;
17466 i--;
17467 }
17468
17469 return 0;
17470}
17471
d6c2308c
JW
17472static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17473 const union bpf_attr *attr)
a4b1d3c1 17474{
d6c2308c 17475 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 17476 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 17477 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 17478 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 17479 struct bpf_prog *new_prog;
d6c2308c 17480 bool rnd_hi32;
a4b1d3c1 17481
d6c2308c 17482 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 17483 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
17484 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17485 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17486 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
17487 for (i = 0; i < len; i++) {
17488 int adj_idx = i + delta;
17489 struct bpf_insn insn;
83a28819 17490 int load_reg;
a4b1d3c1 17491
d6c2308c 17492 insn = insns[adj_idx];
83a28819 17493 load_reg = insn_def_regno(&insn);
d6c2308c
JW
17494 if (!aux[adj_idx].zext_dst) {
17495 u8 code, class;
17496 u32 imm_rnd;
17497
17498 if (!rnd_hi32)
17499 continue;
17500
17501 code = insn.code;
17502 class = BPF_CLASS(code);
83a28819 17503 if (load_reg == -1)
d6c2308c
JW
17504 continue;
17505
17506 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
17507 * BPF_STX + SRC_OP, so it is safe to pass NULL
17508 * here.
d6c2308c 17509 */
83a28819 17510 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
17511 if (class == BPF_LD &&
17512 BPF_MODE(code) == BPF_IMM)
17513 i++;
17514 continue;
17515 }
17516
17517 /* ctx load could be transformed into wider load. */
17518 if (class == BPF_LDX &&
17519 aux[adj_idx].ptr_type == PTR_TO_CTX)
17520 continue;
17521
a251c17a 17522 imm_rnd = get_random_u32();
d6c2308c
JW
17523 rnd_hi32_patch[0] = insn;
17524 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 17525 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
17526 patch = rnd_hi32_patch;
17527 patch_len = 4;
17528 goto apply_patch_buffer;
17529 }
17530
39491867
BJ
17531 /* Add in an zero-extend instruction if a) the JIT has requested
17532 * it or b) it's a CMPXCHG.
17533 *
17534 * The latter is because: BPF_CMPXCHG always loads a value into
17535 * R0, therefore always zero-extends. However some archs'
17536 * equivalent instruction only does this load when the
17537 * comparison is successful. This detail of CMPXCHG is
17538 * orthogonal to the general zero-extension behaviour of the
17539 * CPU, so it's treated independently of bpf_jit_needs_zext.
17540 */
17541 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
17542 continue;
17543
d35af0a7
BT
17544 /* Zero-extension is done by the caller. */
17545 if (bpf_pseudo_kfunc_call(&insn))
17546 continue;
17547
83a28819
IL
17548 if (WARN_ON(load_reg == -1)) {
17549 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17550 return -EFAULT;
b2e37a71
IL
17551 }
17552
a4b1d3c1 17553 zext_patch[0] = insn;
b2e37a71
IL
17554 zext_patch[1].dst_reg = load_reg;
17555 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
17556 patch = zext_patch;
17557 patch_len = 2;
17558apply_patch_buffer:
17559 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
17560 if (!new_prog)
17561 return -ENOMEM;
17562 env->prog = new_prog;
17563 insns = new_prog->insnsi;
17564 aux = env->insn_aux_data;
d6c2308c 17565 delta += patch_len - 1;
a4b1d3c1
JW
17566 }
17567
17568 return 0;
17569}
17570
c64b7983
JS
17571/* convert load instructions that access fields of a context type into a
17572 * sequence of instructions that access fields of the underlying structure:
17573 * struct __sk_buff -> struct sk_buff
17574 * struct bpf_sock_ops -> struct sock
9bac3d6d 17575 */
58e2af8b 17576static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 17577{
00176a34 17578 const struct bpf_verifier_ops *ops = env->ops;
f96da094 17579 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 17580 const int insn_cnt = env->prog->len;
36bbef52 17581 struct bpf_insn insn_buf[16], *insn;
46f53a65 17582 u32 target_size, size_default, off;
9bac3d6d 17583 struct bpf_prog *new_prog;
d691f9e8 17584 enum bpf_access_type type;
f96da094 17585 bool is_narrower_load;
9bac3d6d 17586
b09928b9
DB
17587 if (ops->gen_prologue || env->seen_direct_write) {
17588 if (!ops->gen_prologue) {
17589 verbose(env, "bpf verifier is misconfigured\n");
17590 return -EINVAL;
17591 }
36bbef52
DB
17592 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17593 env->prog);
17594 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 17595 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
17596 return -EINVAL;
17597 } else if (cnt) {
8041902d 17598 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
17599 if (!new_prog)
17600 return -ENOMEM;
8041902d 17601
36bbef52 17602 env->prog = new_prog;
3df126f3 17603 delta += cnt - 1;
36bbef52
DB
17604 }
17605 }
17606
9d03ebc7 17607 if (bpf_prog_is_offloaded(env->prog->aux))
9bac3d6d
AS
17608 return 0;
17609
3df126f3 17610 insn = env->prog->insnsi + delta;
36bbef52 17611
9bac3d6d 17612 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
17613 bpf_convert_ctx_access_t convert_ctx_access;
17614
62c7989b
DB
17615 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17616 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17617 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
1f9a1ea8
YS
17618 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17619 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17620 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17621 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
d691f9e8 17622 type = BPF_READ;
2039f26f
DB
17623 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17624 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17625 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17626 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17627 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17628 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17629 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17630 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
d691f9e8 17631 type = BPF_WRITE;
2039f26f 17632 } else {
9bac3d6d 17633 continue;
2039f26f 17634 }
9bac3d6d 17635
af86ca4e 17636 if (type == BPF_WRITE &&
2039f26f 17637 env->insn_aux_data[i + delta].sanitize_stack_spill) {
af86ca4e 17638 struct bpf_insn patch[] = {
af86ca4e 17639 *insn,
2039f26f 17640 BPF_ST_NOSPEC(),
af86ca4e
AS
17641 };
17642
17643 cnt = ARRAY_SIZE(patch);
17644 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17645 if (!new_prog)
17646 return -ENOMEM;
17647
17648 delta += cnt - 1;
17649 env->prog = new_prog;
17650 insn = new_prog->insnsi + i + delta;
17651 continue;
17652 }
17653
6efe152d 17654 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
c64b7983
JS
17655 case PTR_TO_CTX:
17656 if (!ops->convert_ctx_access)
17657 continue;
17658 convert_ctx_access = ops->convert_ctx_access;
17659 break;
17660 case PTR_TO_SOCKET:
46f8bc92 17661 case PTR_TO_SOCK_COMMON:
c64b7983
JS
17662 convert_ctx_access = bpf_sock_convert_ctx_access;
17663 break;
655a51e5
MKL
17664 case PTR_TO_TCP_SOCK:
17665 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17666 break;
fada7fdc
JL
17667 case PTR_TO_XDP_SOCK:
17668 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17669 break;
2a02759e 17670 case PTR_TO_BTF_ID:
6efe152d 17671 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
282de143
KKD
17672 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17673 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17674 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17675 * any faults for loads into such types. BPF_WRITE is disallowed
17676 * for this case.
17677 */
17678 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
27ae7997 17679 if (type == BPF_READ) {
1f9a1ea8
YS
17680 if (BPF_MODE(insn->code) == BPF_MEM)
17681 insn->code = BPF_LDX | BPF_PROBE_MEM |
17682 BPF_SIZE((insn)->code);
17683 else
17684 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17685 BPF_SIZE((insn)->code);
27ae7997 17686 env->prog->aux->num_exentries++;
2a02759e 17687 }
2a02759e 17688 continue;
c64b7983 17689 default:
9bac3d6d 17690 continue;
c64b7983 17691 }
9bac3d6d 17692
31fd8581 17693 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 17694 size = BPF_LDST_BYTES(insn);
31fd8581
YS
17695
17696 /* If the read access is a narrower load of the field,
17697 * convert to a 4/8-byte load, to minimum program type specific
17698 * convert_ctx_access changes. If conversion is successful,
17699 * we will apply proper mask to the result.
17700 */
f96da094 17701 is_narrower_load = size < ctx_field_size;
46f53a65
AI
17702 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17703 off = insn->off;
31fd8581 17704 if (is_narrower_load) {
f96da094
DB
17705 u8 size_code;
17706
17707 if (type == BPF_WRITE) {
61bd5218 17708 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
17709 return -EINVAL;
17710 }
31fd8581 17711
f96da094 17712 size_code = BPF_H;
31fd8581
YS
17713 if (ctx_field_size == 4)
17714 size_code = BPF_W;
17715 else if (ctx_field_size == 8)
17716 size_code = BPF_DW;
f96da094 17717
bc23105c 17718 insn->off = off & ~(size_default - 1);
31fd8581
YS
17719 insn->code = BPF_LDX | BPF_MEM | size_code;
17720 }
f96da094
DB
17721
17722 target_size = 0;
c64b7983
JS
17723 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17724 &target_size);
f96da094
DB
17725 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17726 (ctx_field_size && !target_size)) {
61bd5218 17727 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
17728 return -EINVAL;
17729 }
f96da094
DB
17730
17731 if (is_narrower_load && size < target_size) {
d895a0f1
IL
17732 u8 shift = bpf_ctx_narrow_access_offset(
17733 off, size, size_default) * 8;
d7af7e49
AI
17734 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17735 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17736 return -EINVAL;
17737 }
46f53a65
AI
17738 if (ctx_field_size <= 4) {
17739 if (shift)
17740 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17741 insn->dst_reg,
17742 shift);
31fd8581 17743 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 17744 (1 << size * 8) - 1);
46f53a65
AI
17745 } else {
17746 if (shift)
17747 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17748 insn->dst_reg,
17749 shift);
0613d8ca 17750 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 17751 (1ULL << size * 8) - 1);
46f53a65 17752 }
31fd8581 17753 }
9bac3d6d 17754
8041902d 17755 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
17756 if (!new_prog)
17757 return -ENOMEM;
17758
3df126f3 17759 delta += cnt - 1;
9bac3d6d
AS
17760
17761 /* keep walking new program and skip insns we just inserted */
17762 env->prog = new_prog;
3df126f3 17763 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
17764 }
17765
17766 return 0;
17767}
17768
1c2a088a
AS
17769static int jit_subprogs(struct bpf_verifier_env *env)
17770{
17771 struct bpf_prog *prog = env->prog, **func, *tmp;
17772 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 17773 struct bpf_map *map_ptr;
7105e828 17774 struct bpf_insn *insn;
1c2a088a 17775 void *old_bpf_func;
c4c0bdc0 17776 int err, num_exentries;
1c2a088a 17777
f910cefa 17778 if (env->subprog_cnt <= 1)
1c2a088a
AS
17779 return 0;
17780
7105e828 17781 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
3990ed4c 17782 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
69c087ba 17783 continue;
69c087ba 17784
c7a89784
DB
17785 /* Upon error here we cannot fall back to interpreter but
17786 * need a hard reject of the program. Thus -EFAULT is
17787 * propagated in any case.
17788 */
1c2a088a
AS
17789 subprog = find_subprog(env, i + insn->imm + 1);
17790 if (subprog < 0) {
17791 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17792 i + insn->imm + 1);
17793 return -EFAULT;
17794 }
17795 /* temporarily remember subprog id inside insn instead of
17796 * aux_data, since next loop will split up all insns into funcs
17797 */
f910cefa 17798 insn->off = subprog;
1c2a088a
AS
17799 /* remember original imm in case JIT fails and fallback
17800 * to interpreter will be needed
17801 */
17802 env->insn_aux_data[i].call_imm = insn->imm;
17803 /* point imm to __bpf_call_base+1 from JITs point of view */
17804 insn->imm = 1;
3990ed4c
MKL
17805 if (bpf_pseudo_func(insn))
17806 /* jit (e.g. x86_64) may emit fewer instructions
17807 * if it learns a u32 imm is the same as a u64 imm.
17808 * Force a non zero here.
17809 */
17810 insn[1].imm = 1;
1c2a088a
AS
17811 }
17812
c454a46b
MKL
17813 err = bpf_prog_alloc_jited_linfo(prog);
17814 if (err)
17815 goto out_undo_insn;
17816
17817 err = -ENOMEM;
6396bb22 17818 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 17819 if (!func)
c7a89784 17820 goto out_undo_insn;
1c2a088a 17821
f910cefa 17822 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 17823 subprog_start = subprog_end;
4cb3d99c 17824 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
17825
17826 len = subprog_end - subprog_start;
fb7dd8bc 17827 /* bpf_prog_run() doesn't call subprogs directly,
492ecee8
AS
17828 * hence main prog stats include the runtime of subprogs.
17829 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 17830 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
17831 */
17832 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
17833 if (!func[i])
17834 goto out_free;
17835 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17836 len * sizeof(struct bpf_insn));
4f74d809 17837 func[i]->type = prog->type;
1c2a088a 17838 func[i]->len = len;
4f74d809
DB
17839 if (bpf_prog_calc_tag(func[i]))
17840 goto out_free;
1c2a088a 17841 func[i]->is_func = 1;
ba64e7d8 17842 func[i]->aux->func_idx = i;
f263a814 17843 /* Below members will be freed only at prog->aux */
ba64e7d8
YS
17844 func[i]->aux->btf = prog->aux->btf;
17845 func[i]->aux->func_info = prog->aux->func_info;
9c7c48d6 17846 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
f263a814
JF
17847 func[i]->aux->poke_tab = prog->aux->poke_tab;
17848 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
ba64e7d8 17849
a748c697 17850 for (j = 0; j < prog->aux->size_poke_tab; j++) {
f263a814 17851 struct bpf_jit_poke_descriptor *poke;
a748c697 17852
f263a814
JF
17853 poke = &prog->aux->poke_tab[j];
17854 if (poke->insn_idx < subprog_end &&
17855 poke->insn_idx >= subprog_start)
17856 poke->aux = func[i]->aux;
a748c697
MF
17857 }
17858
1c2a088a 17859 func[i]->aux->name[0] = 'F';
9c8105bd 17860 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 17861 func[i]->jit_requested = 1;
d2a3b7c5 17862 func[i]->blinding_requested = prog->blinding_requested;
e6ac2450 17863 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
2357672c 17864 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
c454a46b
MKL
17865 func[i]->aux->linfo = prog->aux->linfo;
17866 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17867 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17868 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
17869 num_exentries = 0;
17870 insn = func[i]->insnsi;
17871 for (j = 0; j < func[i]->len; j++, insn++) {
17872 if (BPF_CLASS(insn->code) == BPF_LDX &&
1f9a1ea8
YS
17873 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
17874 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
c4c0bdc0
YS
17875 num_exentries++;
17876 }
17877 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 17878 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
17879 func[i] = bpf_int_jit_compile(func[i]);
17880 if (!func[i]->jited) {
17881 err = -ENOTSUPP;
17882 goto out_free;
17883 }
17884 cond_resched();
17885 }
a748c697 17886
1c2a088a
AS
17887 /* at this point all bpf functions were successfully JITed
17888 * now populate all bpf_calls with correct addresses and
17889 * run last pass of JIT
17890 */
f910cefa 17891 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
17892 insn = func[i]->insnsi;
17893 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba 17894 if (bpf_pseudo_func(insn)) {
3990ed4c 17895 subprog = insn->off;
69c087ba
YS
17896 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17897 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17898 continue;
17899 }
23a2d70c 17900 if (!bpf_pseudo_call(insn))
1c2a088a
AS
17901 continue;
17902 subprog = insn->off;
3d717fad 17903 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
1c2a088a 17904 }
2162fed4
SD
17905
17906 /* we use the aux data to keep a list of the start addresses
17907 * of the JITed images for each function in the program
17908 *
17909 * for some architectures, such as powerpc64, the imm field
17910 * might not be large enough to hold the offset of the start
17911 * address of the callee's JITed image from __bpf_call_base
17912 *
17913 * in such cases, we can lookup the start address of a callee
17914 * by using its subprog id, available from the off field of
17915 * the call instruction, as an index for this list
17916 */
17917 func[i]->aux->func = func;
17918 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 17919 }
f910cefa 17920 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
17921 old_bpf_func = func[i]->bpf_func;
17922 tmp = bpf_int_jit_compile(func[i]);
17923 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17924 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 17925 err = -ENOTSUPP;
1c2a088a
AS
17926 goto out_free;
17927 }
17928 cond_resched();
17929 }
17930
17931 /* finally lock prog and jit images for all functions and
0108a4e9
KJ
17932 * populate kallsysm. Begin at the first subprogram, since
17933 * bpf_prog_load will add the kallsyms for the main program.
1c2a088a 17934 */
0108a4e9 17935 for (i = 1; i < env->subprog_cnt; i++) {
1c2a088a
AS
17936 bpf_prog_lock_ro(func[i]);
17937 bpf_prog_kallsyms_add(func[i]);
17938 }
7105e828
DB
17939
17940 /* Last step: make now unused interpreter insns from main
17941 * prog consistent for later dump requests, so they can
17942 * later look the same as if they were interpreted only.
17943 */
17944 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
17945 if (bpf_pseudo_func(insn)) {
17946 insn[0].imm = env->insn_aux_data[i].call_imm;
3990ed4c
MKL
17947 insn[1].imm = insn->off;
17948 insn->off = 0;
69c087ba
YS
17949 continue;
17950 }
23a2d70c 17951 if (!bpf_pseudo_call(insn))
7105e828
DB
17952 continue;
17953 insn->off = env->insn_aux_data[i].call_imm;
17954 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 17955 insn->imm = subprog;
7105e828
DB
17956 }
17957
1c2a088a
AS
17958 prog->jited = 1;
17959 prog->bpf_func = func[0]->bpf_func;
d00c6473 17960 prog->jited_len = func[0]->jited_len;
0108a4e9
KJ
17961 prog->aux->extable = func[0]->aux->extable;
17962 prog->aux->num_exentries = func[0]->aux->num_exentries;
1c2a088a 17963 prog->aux->func = func;
f910cefa 17964 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 17965 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
17966 return 0;
17967out_free:
f263a814
JF
17968 /* We failed JIT'ing, so at this point we need to unregister poke
17969 * descriptors from subprogs, so that kernel is not attempting to
17970 * patch it anymore as we're freeing the subprog JIT memory.
17971 */
17972 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17973 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17974 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17975 }
17976 /* At this point we're guaranteed that poke descriptors are not
17977 * live anymore. We can just unlink its descriptor table as it's
17978 * released with the main prog.
17979 */
a748c697
MF
17980 for (i = 0; i < env->subprog_cnt; i++) {
17981 if (!func[i])
17982 continue;
f263a814 17983 func[i]->aux->poke_tab = NULL;
a748c697
MF
17984 bpf_jit_free(func[i]);
17985 }
1c2a088a 17986 kfree(func);
c7a89784 17987out_undo_insn:
1c2a088a
AS
17988 /* cleanup main prog to be interpreted */
17989 prog->jit_requested = 0;
d2a3b7c5 17990 prog->blinding_requested = 0;
1c2a088a 17991 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 17992 if (!bpf_pseudo_call(insn))
1c2a088a
AS
17993 continue;
17994 insn->off = 0;
17995 insn->imm = env->insn_aux_data[i].call_imm;
17996 }
e16301fb 17997 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
17998 return err;
17999}
18000
1ea47e01
AS
18001static int fixup_call_args(struct bpf_verifier_env *env)
18002{
19d28fbd 18003#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
18004 struct bpf_prog *prog = env->prog;
18005 struct bpf_insn *insn = prog->insnsi;
e6ac2450 18006 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 18007 int i, depth;
19d28fbd 18008#endif
e4052d06 18009 int err = 0;
1ea47e01 18010
e4052d06 18011 if (env->prog->jit_requested &&
9d03ebc7 18012 !bpf_prog_is_offloaded(env->prog->aux)) {
19d28fbd
DM
18013 err = jit_subprogs(env);
18014 if (err == 0)
1c2a088a 18015 return 0;
c7a89784
DB
18016 if (err == -EFAULT)
18017 return err;
19d28fbd
DM
18018 }
18019#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
18020 if (has_kfunc_call) {
18021 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18022 return -EINVAL;
18023 }
e411901c
MF
18024 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18025 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18026 * have to be rejected, since interpreter doesn't support them yet.
18027 */
18028 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18029 return -EINVAL;
18030 }
1ea47e01 18031 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
18032 if (bpf_pseudo_func(insn)) {
18033 /* When JIT fails the progs with callback calls
18034 * have to be rejected, since interpreter doesn't support them yet.
18035 */
18036 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18037 return -EINVAL;
18038 }
18039
23a2d70c 18040 if (!bpf_pseudo_call(insn))
1ea47e01
AS
18041 continue;
18042 depth = get_callee_stack_depth(env, insn, i);
18043 if (depth < 0)
18044 return depth;
18045 bpf_patch_call_args(insn, depth);
18046 }
19d28fbd
DM
18047 err = 0;
18048#endif
18049 return err;
1ea47e01
AS
18050}
18051
1cf3bfc6
IL
18052/* replace a generic kfunc with a specialized version if necessary */
18053static void specialize_kfunc(struct bpf_verifier_env *env,
18054 u32 func_id, u16 offset, unsigned long *addr)
18055{
18056 struct bpf_prog *prog = env->prog;
18057 bool seen_direct_write;
18058 void *xdp_kfunc;
18059 bool is_rdonly;
18060
18061 if (bpf_dev_bound_kfunc_id(func_id)) {
18062 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18063 if (xdp_kfunc) {
18064 *addr = (unsigned long)xdp_kfunc;
18065 return;
18066 }
18067 /* fallback to default kfunc when not supported by netdev */
18068 }
18069
18070 if (offset)
18071 return;
18072
18073 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18074 seen_direct_write = env->seen_direct_write;
18075 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18076
18077 if (is_rdonly)
18078 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18079
18080 /* restore env->seen_direct_write to its original value, since
18081 * may_access_direct_pkt_data mutates it
18082 */
18083 env->seen_direct_write = seen_direct_write;
18084 }
18085}
18086
d2dcc67d
DM
18087static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18088 u16 struct_meta_reg,
18089 u16 node_offset_reg,
18090 struct bpf_insn *insn,
18091 struct bpf_insn *insn_buf,
18092 int *cnt)
18093{
18094 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18095 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18096
18097 insn_buf[0] = addr[0];
18098 insn_buf[1] = addr[1];
18099 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18100 insn_buf[3] = *insn;
18101 *cnt = 4;
18102}
18103
958cf2e2
KKD
18104static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18105 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
e6ac2450
MKL
18106{
18107 const struct bpf_kfunc_desc *desc;
18108
a5d82727
KKD
18109 if (!insn->imm) {
18110 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18111 return -EINVAL;
18112 }
18113
3d76a4d3
SF
18114 *cnt = 0;
18115
1cf3bfc6
IL
18116 /* insn->imm has the btf func_id. Replace it with an offset relative to
18117 * __bpf_call_base, unless the JIT needs to call functions that are
18118 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
e6ac2450 18119 */
2357672c 18120 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
e6ac2450
MKL
18121 if (!desc) {
18122 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18123 insn->imm);
18124 return -EFAULT;
18125 }
18126
1cf3bfc6
IL
18127 if (!bpf_jit_supports_far_kfunc_call())
18128 insn->imm = BPF_CALL_IMM(desc->addr);
958cf2e2
KKD
18129 if (insn->off)
18130 return 0;
18131 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18132 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18133 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18134 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
e6ac2450 18135
958cf2e2
KKD
18136 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18137 insn_buf[1] = addr[0];
18138 insn_buf[2] = addr[1];
18139 insn_buf[3] = *insn;
18140 *cnt = 4;
7c50b1cb
DM
18141 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18142 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
ac9f0605
KKD
18143 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18144 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18145
18146 insn_buf[0] = addr[0];
18147 insn_buf[1] = addr[1];
18148 insn_buf[2] = *insn;
18149 *cnt = 3;
d2dcc67d
DM
18150 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18151 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18152 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18153 int struct_meta_reg = BPF_REG_3;
18154 int node_offset_reg = BPF_REG_4;
18155
18156 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18157 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18158 struct_meta_reg = BPF_REG_4;
18159 node_offset_reg = BPF_REG_5;
18160 }
18161
18162 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18163 node_offset_reg, insn, insn_buf, cnt);
a35b9af4
YS
18164 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18165 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
fd264ca0
YS
18166 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18167 *cnt = 1;
958cf2e2 18168 }
e6ac2450
MKL
18169 return 0;
18170}
18171
e6ac5933
BJ
18172/* Do various post-verification rewrites in a single program pass.
18173 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 18174 */
e6ac5933 18175static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 18176{
79741b3b 18177 struct bpf_prog *prog = env->prog;
f92c1e18 18178 enum bpf_attach_type eatype = prog->expected_attach_type;
9b99edca 18179 enum bpf_prog_type prog_type = resolve_prog_type(prog);
79741b3b 18180 struct bpf_insn *insn = prog->insnsi;
e245c5c6 18181 const struct bpf_func_proto *fn;
79741b3b 18182 const int insn_cnt = prog->len;
09772d92 18183 const struct bpf_map_ops *ops;
c93552c4 18184 struct bpf_insn_aux_data *aux;
81ed18ab
AS
18185 struct bpf_insn insn_buf[16];
18186 struct bpf_prog *new_prog;
18187 struct bpf_map *map_ptr;
d2e4c1e6 18188 int i, ret, cnt, delta = 0;
e245c5c6 18189
79741b3b 18190 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 18191 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
18192 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18193 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18194 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 18195 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 18196 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
18197 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18198 struct bpf_insn *patchlet;
18199 struct bpf_insn chk_and_div[] = {
9b00f1b7 18200 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
18201 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18202 BPF_JNE | BPF_K, insn->src_reg,
18203 0, 2, 0),
f6b1b3bf
DB
18204 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18205 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18206 *insn,
18207 };
e88b2c6e 18208 struct bpf_insn chk_and_mod[] = {
9b00f1b7 18209 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
18210 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18211 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 18212 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 18213 *insn,
9b00f1b7
DB
18214 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18215 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 18216 };
f6b1b3bf 18217
e88b2c6e
DB
18218 patchlet = isdiv ? chk_and_div : chk_and_mod;
18219 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 18220 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
18221
18222 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
18223 if (!new_prog)
18224 return -ENOMEM;
18225
18226 delta += cnt - 1;
18227 env->prog = prog = new_prog;
18228 insn = new_prog->insnsi + i + delta;
18229 continue;
18230 }
18231
e6ac5933 18232 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
18233 if (BPF_CLASS(insn->code) == BPF_LD &&
18234 (BPF_MODE(insn->code) == BPF_ABS ||
18235 BPF_MODE(insn->code) == BPF_IND)) {
18236 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18237 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18238 verbose(env, "bpf verifier is misconfigured\n");
18239 return -EINVAL;
18240 }
18241
18242 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18243 if (!new_prog)
18244 return -ENOMEM;
18245
18246 delta += cnt - 1;
18247 env->prog = prog = new_prog;
18248 insn = new_prog->insnsi + i + delta;
18249 continue;
18250 }
18251
e6ac5933 18252 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
18253 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18254 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18255 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18256 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 18257 struct bpf_insn *patch = &insn_buf[0];
801c6058 18258 bool issrc, isneg, isimm;
979d63d5
DB
18259 u32 off_reg;
18260
18261 aux = &env->insn_aux_data[i + delta];
3612af78
DB
18262 if (!aux->alu_state ||
18263 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
18264 continue;
18265
18266 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18267 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18268 BPF_ALU_SANITIZE_SRC;
801c6058 18269 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
18270
18271 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
18272 if (isimm) {
18273 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18274 } else {
18275 if (isneg)
18276 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18277 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18278 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18279 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18280 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18281 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18282 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18283 }
b9b34ddb
DB
18284 if (!issrc)
18285 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18286 insn->src_reg = BPF_REG_AX;
979d63d5
DB
18287 if (isneg)
18288 insn->code = insn->code == code_add ?
18289 code_sub : code_add;
18290 *patch++ = *insn;
801c6058 18291 if (issrc && isneg && !isimm)
979d63d5
DB
18292 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18293 cnt = patch - insn_buf;
18294
18295 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18296 if (!new_prog)
18297 return -ENOMEM;
18298
18299 delta += cnt - 1;
18300 env->prog = prog = new_prog;
18301 insn = new_prog->insnsi + i + delta;
18302 continue;
18303 }
18304
79741b3b
AS
18305 if (insn->code != (BPF_JMP | BPF_CALL))
18306 continue;
cc8b0b92
AS
18307 if (insn->src_reg == BPF_PSEUDO_CALL)
18308 continue;
e6ac2450 18309 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
958cf2e2 18310 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
e6ac2450
MKL
18311 if (ret)
18312 return ret;
958cf2e2
KKD
18313 if (cnt == 0)
18314 continue;
18315
18316 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18317 if (!new_prog)
18318 return -ENOMEM;
18319
18320 delta += cnt - 1;
18321 env->prog = prog = new_prog;
18322 insn = new_prog->insnsi + i + delta;
e6ac2450
MKL
18323 continue;
18324 }
e245c5c6 18325
79741b3b
AS
18326 if (insn->imm == BPF_FUNC_get_route_realm)
18327 prog->dst_needed = 1;
18328 if (insn->imm == BPF_FUNC_get_prandom_u32)
18329 bpf_user_rnd_init_once();
9802d865
JB
18330 if (insn->imm == BPF_FUNC_override_return)
18331 prog->kprobe_override = 1;
79741b3b 18332 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
18333 /* If we tail call into other programs, we
18334 * cannot make any assumptions since they can
18335 * be replaced dynamically during runtime in
18336 * the program array.
18337 */
18338 prog->cb_access = 1;
e411901c
MF
18339 if (!allow_tail_call_in_subprogs(env))
18340 prog->aux->stack_depth = MAX_BPF_STACK;
18341 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 18342
79741b3b 18343 /* mark bpf_tail_call as different opcode to avoid
8fb33b60 18344 * conditional branch in the interpreter for every normal
79741b3b
AS
18345 * call and to prevent accidental JITing by JIT compiler
18346 * that doesn't support bpf_tail_call yet
e245c5c6 18347 */
79741b3b 18348 insn->imm = 0;
71189fa9 18349 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 18350
c93552c4 18351 aux = &env->insn_aux_data[i + delta];
d2a3b7c5 18352 if (env->bpf_capable && !prog->blinding_requested &&
cc52d914 18353 prog->jit_requested &&
d2e4c1e6
DB
18354 !bpf_map_key_poisoned(aux) &&
18355 !bpf_map_ptr_poisoned(aux) &&
18356 !bpf_map_ptr_unpriv(aux)) {
18357 struct bpf_jit_poke_descriptor desc = {
18358 .reason = BPF_POKE_REASON_TAIL_CALL,
18359 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18360 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 18361 .insn_idx = i + delta,
d2e4c1e6
DB
18362 };
18363
18364 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18365 if (ret < 0) {
18366 verbose(env, "adding tail call poke descriptor failed\n");
18367 return ret;
18368 }
18369
18370 insn->imm = ret + 1;
18371 continue;
18372 }
18373
c93552c4
DB
18374 if (!bpf_map_ptr_unpriv(aux))
18375 continue;
18376
b2157399
AS
18377 /* instead of changing every JIT dealing with tail_call
18378 * emit two extra insns:
18379 * if (index >= max_entries) goto out;
18380 * index &= array->index_mask;
18381 * to avoid out-of-bounds cpu speculation
18382 */
c93552c4 18383 if (bpf_map_ptr_poisoned(aux)) {
40950343 18384 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
18385 return -EINVAL;
18386 }
c93552c4 18387
d2e4c1e6 18388 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
18389 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18390 map_ptr->max_entries, 2);
18391 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18392 container_of(map_ptr,
18393 struct bpf_array,
18394 map)->index_mask);
18395 insn_buf[2] = *insn;
18396 cnt = 3;
18397 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18398 if (!new_prog)
18399 return -ENOMEM;
18400
18401 delta += cnt - 1;
18402 env->prog = prog = new_prog;
18403 insn = new_prog->insnsi + i + delta;
79741b3b
AS
18404 continue;
18405 }
e245c5c6 18406
b00628b1
AS
18407 if (insn->imm == BPF_FUNC_timer_set_callback) {
18408 /* The verifier will process callback_fn as many times as necessary
18409 * with different maps and the register states prepared by
18410 * set_timer_callback_state will be accurate.
18411 *
18412 * The following use case is valid:
18413 * map1 is shared by prog1, prog2, prog3.
18414 * prog1 calls bpf_timer_init for some map1 elements
18415 * prog2 calls bpf_timer_set_callback for some map1 elements.
18416 * Those that were not bpf_timer_init-ed will return -EINVAL.
18417 * prog3 calls bpf_timer_start for some map1 elements.
18418 * Those that were not both bpf_timer_init-ed and
18419 * bpf_timer_set_callback-ed will return -EINVAL.
18420 */
18421 struct bpf_insn ld_addrs[2] = {
18422 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18423 };
18424
18425 insn_buf[0] = ld_addrs[0];
18426 insn_buf[1] = ld_addrs[1];
18427 insn_buf[2] = *insn;
18428 cnt = 3;
18429
18430 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18431 if (!new_prog)
18432 return -ENOMEM;
18433
18434 delta += cnt - 1;
18435 env->prog = prog = new_prog;
18436 insn = new_prog->insnsi + i + delta;
18437 goto patch_call_imm;
18438 }
18439
9bb00b28
YS
18440 if (is_storage_get_function(insn->imm)) {
18441 if (!env->prog->aux->sleepable ||
18442 env->insn_aux_data[i + delta].storage_get_func_atomic)
d56c9fe6 18443 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
9bb00b28
YS
18444 else
18445 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
b00fa38a
JK
18446 insn_buf[1] = *insn;
18447 cnt = 2;
18448
18449 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18450 if (!new_prog)
18451 return -ENOMEM;
18452
18453 delta += cnt - 1;
18454 env->prog = prog = new_prog;
18455 insn = new_prog->insnsi + i + delta;
18456 goto patch_call_imm;
18457 }
18458
89c63074 18459 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
18460 * and other inlining handlers are currently limited to 64 bit
18461 * only.
89c63074 18462 */
60b58afc 18463 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
18464 (insn->imm == BPF_FUNC_map_lookup_elem ||
18465 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
18466 insn->imm == BPF_FUNC_map_delete_elem ||
18467 insn->imm == BPF_FUNC_map_push_elem ||
18468 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f 18469 insn->imm == BPF_FUNC_map_peek_elem ||
0640c77c 18470 insn->imm == BPF_FUNC_redirect_map ||
07343110
FZ
18471 insn->imm == BPF_FUNC_for_each_map_elem ||
18472 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
c93552c4
DB
18473 aux = &env->insn_aux_data[i + delta];
18474 if (bpf_map_ptr_poisoned(aux))
18475 goto patch_call_imm;
18476
d2e4c1e6 18477 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
18478 ops = map_ptr->ops;
18479 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18480 ops->map_gen_lookup) {
18481 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
18482 if (cnt == -EOPNOTSUPP)
18483 goto patch_map_ops_generic;
18484 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
18485 verbose(env, "bpf verifier is misconfigured\n");
18486 return -EINVAL;
18487 }
81ed18ab 18488
09772d92
DB
18489 new_prog = bpf_patch_insn_data(env, i + delta,
18490 insn_buf, cnt);
18491 if (!new_prog)
18492 return -ENOMEM;
81ed18ab 18493
09772d92
DB
18494 delta += cnt - 1;
18495 env->prog = prog = new_prog;
18496 insn = new_prog->insnsi + i + delta;
18497 continue;
18498 }
81ed18ab 18499
09772d92
DB
18500 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18501 (void *(*)(struct bpf_map *map, void *key))NULL));
18502 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
d7ba4cc9 18503 (long (*)(struct bpf_map *map, void *key))NULL));
09772d92 18504 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
d7ba4cc9 18505 (long (*)(struct bpf_map *map, void *key, void *value,
09772d92 18506 u64 flags))NULL));
84430d42 18507 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
d7ba4cc9 18508 (long (*)(struct bpf_map *map, void *value,
84430d42
DB
18509 u64 flags))NULL));
18510 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
d7ba4cc9 18511 (long (*)(struct bpf_map *map, void *value))NULL));
84430d42 18512 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
d7ba4cc9 18513 (long (*)(struct bpf_map *map, void *value))NULL));
e6a4750f 18514 BUILD_BUG_ON(!__same_type(ops->map_redirect,
d7ba4cc9 18515 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
0640c77c 18516 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
d7ba4cc9 18517 (long (*)(struct bpf_map *map,
0640c77c
AI
18518 bpf_callback_t callback_fn,
18519 void *callback_ctx,
18520 u64 flags))NULL));
07343110
FZ
18521 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18522 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
e6a4750f 18523
4a8f87e6 18524patch_map_ops_generic:
09772d92
DB
18525 switch (insn->imm) {
18526 case BPF_FUNC_map_lookup_elem:
3d717fad 18527 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
09772d92
DB
18528 continue;
18529 case BPF_FUNC_map_update_elem:
3d717fad 18530 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
09772d92
DB
18531 continue;
18532 case BPF_FUNC_map_delete_elem:
3d717fad 18533 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
09772d92 18534 continue;
84430d42 18535 case BPF_FUNC_map_push_elem:
3d717fad 18536 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
84430d42
DB
18537 continue;
18538 case BPF_FUNC_map_pop_elem:
3d717fad 18539 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
84430d42
DB
18540 continue;
18541 case BPF_FUNC_map_peek_elem:
3d717fad 18542 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
84430d42 18543 continue;
e6a4750f 18544 case BPF_FUNC_redirect_map:
3d717fad 18545 insn->imm = BPF_CALL_IMM(ops->map_redirect);
e6a4750f 18546 continue;
0640c77c
AI
18547 case BPF_FUNC_for_each_map_elem:
18548 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
e6a4750f 18549 continue;
07343110
FZ
18550 case BPF_FUNC_map_lookup_percpu_elem:
18551 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18552 continue;
09772d92 18553 }
81ed18ab 18554
09772d92 18555 goto patch_call_imm;
81ed18ab
AS
18556 }
18557
e6ac5933 18558 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
18559 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18560 insn->imm == BPF_FUNC_jiffies64) {
18561 struct bpf_insn ld_jiffies_addr[2] = {
18562 BPF_LD_IMM64(BPF_REG_0,
18563 (unsigned long)&jiffies),
18564 };
18565
18566 insn_buf[0] = ld_jiffies_addr[0];
18567 insn_buf[1] = ld_jiffies_addr[1];
18568 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18569 BPF_REG_0, 0);
18570 cnt = 3;
18571
18572 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18573 cnt);
18574 if (!new_prog)
18575 return -ENOMEM;
18576
18577 delta += cnt - 1;
18578 env->prog = prog = new_prog;
18579 insn = new_prog->insnsi + i + delta;
18580 continue;
18581 }
18582
f92c1e18
JO
18583 /* Implement bpf_get_func_arg inline. */
18584 if (prog_type == BPF_PROG_TYPE_TRACING &&
18585 insn->imm == BPF_FUNC_get_func_arg) {
18586 /* Load nr_args from ctx - 8 */
18587 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18588 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18589 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18590 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18591 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18592 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18593 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18594 insn_buf[7] = BPF_JMP_A(1);
18595 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18596 cnt = 9;
18597
18598 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18599 if (!new_prog)
18600 return -ENOMEM;
18601
18602 delta += cnt - 1;
18603 env->prog = prog = new_prog;
18604 insn = new_prog->insnsi + i + delta;
18605 continue;
18606 }
18607
18608 /* Implement bpf_get_func_ret inline. */
18609 if (prog_type == BPF_PROG_TYPE_TRACING &&
18610 insn->imm == BPF_FUNC_get_func_ret) {
18611 if (eatype == BPF_TRACE_FEXIT ||
18612 eatype == BPF_MODIFY_RETURN) {
18613 /* Load nr_args from ctx - 8 */
18614 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18615 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18616 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18617 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18618 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18619 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18620 cnt = 6;
18621 } else {
18622 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18623 cnt = 1;
18624 }
18625
18626 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18627 if (!new_prog)
18628 return -ENOMEM;
18629
18630 delta += cnt - 1;
18631 env->prog = prog = new_prog;
18632 insn = new_prog->insnsi + i + delta;
18633 continue;
18634 }
18635
18636 /* Implement get_func_arg_cnt inline. */
18637 if (prog_type == BPF_PROG_TYPE_TRACING &&
18638 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18639 /* Load nr_args from ctx - 8 */
18640 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18641
18642 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18643 if (!new_prog)
18644 return -ENOMEM;
18645
18646 env->prog = prog = new_prog;
18647 insn = new_prog->insnsi + i + delta;
18648 continue;
18649 }
18650
f705ec76 18651 /* Implement bpf_get_func_ip inline. */
9b99edca
JO
18652 if (prog_type == BPF_PROG_TYPE_TRACING &&
18653 insn->imm == BPF_FUNC_get_func_ip) {
f92c1e18
JO
18654 /* Load IP address from ctx - 16 */
18655 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
9b99edca
JO
18656
18657 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18658 if (!new_prog)
18659 return -ENOMEM;
18660
18661 env->prog = prog = new_prog;
18662 insn = new_prog->insnsi + i + delta;
18663 continue;
18664 }
18665
81ed18ab 18666patch_call_imm:
5e43f899 18667 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
18668 /* all functions that have prototype and verifier allowed
18669 * programs to call them, must be real in-kernel functions
18670 */
18671 if (!fn->func) {
61bd5218
JK
18672 verbose(env,
18673 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
18674 func_id_name(insn->imm), insn->imm);
18675 return -EFAULT;
e245c5c6 18676 }
79741b3b 18677 insn->imm = fn->func - __bpf_call_base;
e245c5c6 18678 }
e245c5c6 18679
d2e4c1e6
DB
18680 /* Since poke tab is now finalized, publish aux to tracker. */
18681 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18682 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18683 if (!map_ptr->ops->map_poke_track ||
18684 !map_ptr->ops->map_poke_untrack ||
18685 !map_ptr->ops->map_poke_run) {
18686 verbose(env, "bpf verifier is misconfigured\n");
18687 return -EINVAL;
18688 }
18689
18690 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18691 if (ret < 0) {
18692 verbose(env, "tracking tail call prog failed\n");
18693 return ret;
18694 }
18695 }
18696
1cf3bfc6 18697 sort_kfunc_descs_by_imm_off(env->prog);
e6ac2450 18698
79741b3b
AS
18699 return 0;
18700}
e245c5c6 18701
1ade2371
EZ
18702static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18703 int position,
18704 s32 stack_base,
18705 u32 callback_subprogno,
18706 u32 *cnt)
18707{
18708 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18709 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18710 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18711 int reg_loop_max = BPF_REG_6;
18712 int reg_loop_cnt = BPF_REG_7;
18713 int reg_loop_ctx = BPF_REG_8;
18714
18715 struct bpf_prog *new_prog;
18716 u32 callback_start;
18717 u32 call_insn_offset;
18718 s32 callback_offset;
18719
18720 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18721 * be careful to modify this code in sync.
18722 */
18723 struct bpf_insn insn_buf[] = {
18724 /* Return error and jump to the end of the patch if
18725 * expected number of iterations is too big.
18726 */
18727 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18728 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18729 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18730 /* spill R6, R7, R8 to use these as loop vars */
18731 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18732 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18733 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18734 /* initialize loop vars */
18735 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18736 BPF_MOV32_IMM(reg_loop_cnt, 0),
18737 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18738 /* loop header,
18739 * if reg_loop_cnt >= reg_loop_max skip the loop body
18740 */
18741 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18742 /* callback call,
18743 * correct callback offset would be set after patching
18744 */
18745 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18746 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18747 BPF_CALL_REL(0),
18748 /* increment loop counter */
18749 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18750 /* jump to loop header if callback returned 0 */
18751 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18752 /* return value of bpf_loop,
18753 * set R0 to the number of iterations
18754 */
18755 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18756 /* restore original values of R6, R7, R8 */
18757 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18758 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18759 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18760 };
18761
18762 *cnt = ARRAY_SIZE(insn_buf);
18763 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18764 if (!new_prog)
18765 return new_prog;
18766
18767 /* callback start is known only after patching */
18768 callback_start = env->subprog_info[callback_subprogno].start;
18769 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18770 call_insn_offset = position + 12;
18771 callback_offset = callback_start - call_insn_offset - 1;
fb4e3b33 18772 new_prog->insnsi[call_insn_offset].imm = callback_offset;
1ade2371
EZ
18773
18774 return new_prog;
18775}
18776
18777static bool is_bpf_loop_call(struct bpf_insn *insn)
18778{
18779 return insn->code == (BPF_JMP | BPF_CALL) &&
18780 insn->src_reg == 0 &&
18781 insn->imm == BPF_FUNC_loop;
18782}
18783
18784/* For all sub-programs in the program (including main) check
18785 * insn_aux_data to see if there are bpf_loop calls that require
18786 * inlining. If such calls are found the calls are replaced with a
18787 * sequence of instructions produced by `inline_bpf_loop` function and
18788 * subprog stack_depth is increased by the size of 3 registers.
18789 * This stack space is used to spill values of the R6, R7, R8. These
18790 * registers are used to store the loop bound, counter and context
18791 * variables.
18792 */
18793static int optimize_bpf_loop(struct bpf_verifier_env *env)
18794{
18795 struct bpf_subprog_info *subprogs = env->subprog_info;
18796 int i, cur_subprog = 0, cnt, delta = 0;
18797 struct bpf_insn *insn = env->prog->insnsi;
18798 int insn_cnt = env->prog->len;
18799 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18800 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18801 u16 stack_depth_extra = 0;
18802
18803 for (i = 0; i < insn_cnt; i++, insn++) {
18804 struct bpf_loop_inline_state *inline_state =
18805 &env->insn_aux_data[i + delta].loop_inline_state;
18806
18807 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18808 struct bpf_prog *new_prog;
18809
18810 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18811 new_prog = inline_bpf_loop(env,
18812 i + delta,
18813 -(stack_depth + stack_depth_extra),
18814 inline_state->callback_subprogno,
18815 &cnt);
18816 if (!new_prog)
18817 return -ENOMEM;
18818
18819 delta += cnt - 1;
18820 env->prog = new_prog;
18821 insn = new_prog->insnsi + i + delta;
18822 }
18823
18824 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18825 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18826 cur_subprog++;
18827 stack_depth = subprogs[cur_subprog].stack_depth;
18828 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18829 stack_depth_extra = 0;
18830 }
18831 }
18832
18833 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18834
18835 return 0;
18836}
18837
58e2af8b 18838static void free_states(struct bpf_verifier_env *env)
f1bca824 18839{
58e2af8b 18840 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
18841 int i;
18842
9f4686c4
AS
18843 sl = env->free_list;
18844 while (sl) {
18845 sln = sl->next;
18846 free_verifier_state(&sl->state, false);
18847 kfree(sl);
18848 sl = sln;
18849 }
51c39bb1 18850 env->free_list = NULL;
9f4686c4 18851
f1bca824
AS
18852 if (!env->explored_states)
18853 return;
18854
dc2a4ebc 18855 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
18856 sl = env->explored_states[i];
18857
a8f500af
AS
18858 while (sl) {
18859 sln = sl->next;
18860 free_verifier_state(&sl->state, false);
18861 kfree(sl);
18862 sl = sln;
18863 }
51c39bb1 18864 env->explored_states[i] = NULL;
f1bca824 18865 }
51c39bb1 18866}
f1bca824 18867
51c39bb1
AS
18868static int do_check_common(struct bpf_verifier_env *env, int subprog)
18869{
6f8a57cc 18870 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
18871 struct bpf_verifier_state *state;
18872 struct bpf_reg_state *regs;
18873 int ret, i;
18874
18875 env->prev_linfo = NULL;
18876 env->pass_cnt++;
18877
18878 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18879 if (!state)
18880 return -ENOMEM;
18881 state->curframe = 0;
18882 state->speculative = false;
18883 state->branches = 1;
18884 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18885 if (!state->frame[0]) {
18886 kfree(state);
18887 return -ENOMEM;
18888 }
18889 env->cur_state = state;
18890 init_func_state(env, state->frame[0],
18891 BPF_MAIN_FUNC /* callsite */,
18892 0 /* frameno */,
18893 subprog);
be2ef816
AN
18894 state->first_insn_idx = env->subprog_info[subprog].start;
18895 state->last_insn_idx = -1;
51c39bb1
AS
18896
18897 regs = state->frame[state->curframe]->regs;
be8704ff 18898 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
18899 ret = btf_prepare_func_args(env, subprog, regs);
18900 if (ret)
18901 goto out;
18902 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18903 if (regs[i].type == PTR_TO_CTX)
18904 mark_reg_known_zero(env, regs, i);
18905 else if (regs[i].type == SCALAR_VALUE)
18906 mark_reg_unknown(env, regs, i);
cf9f2f8d 18907 else if (base_type(regs[i].type) == PTR_TO_MEM) {
e5069b9c
DB
18908 const u32 mem_size = regs[i].mem_size;
18909
18910 mark_reg_known_zero(env, regs, i);
18911 regs[i].mem_size = mem_size;
18912 regs[i].id = ++env->id_gen;
18913 }
51c39bb1
AS
18914 }
18915 } else {
18916 /* 1st arg to a function */
18917 regs[BPF_REG_1].type = PTR_TO_CTX;
18918 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 18919 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
18920 if (ret == -EFAULT)
18921 /* unlikely verifier bug. abort.
18922 * ret == 0 and ret < 0 are sadly acceptable for
18923 * main() function due to backward compatibility.
18924 * Like socket filter program may be written as:
18925 * int bpf_prog(struct pt_regs *ctx)
18926 * and never dereference that ctx in the program.
18927 * 'struct pt_regs' is a type mismatch for socket
18928 * filter that should be using 'struct __sk_buff'.
18929 */
18930 goto out;
18931 }
18932
18933 ret = do_check(env);
18934out:
f59bbfc2
AS
18935 /* check for NULL is necessary, since cur_state can be freed inside
18936 * do_check() under memory pressure.
18937 */
18938 if (env->cur_state) {
18939 free_verifier_state(env->cur_state, true);
18940 env->cur_state = NULL;
18941 }
6f8a57cc
AN
18942 while (!pop_stack(env, NULL, NULL, false));
18943 if (!ret && pop_log)
18944 bpf_vlog_reset(&env->log, 0);
51c39bb1 18945 free_states(env);
51c39bb1
AS
18946 return ret;
18947}
18948
18949/* Verify all global functions in a BPF program one by one based on their BTF.
18950 * All global functions must pass verification. Otherwise the whole program is rejected.
18951 * Consider:
18952 * int bar(int);
18953 * int foo(int f)
18954 * {
18955 * return bar(f);
18956 * }
18957 * int bar(int b)
18958 * {
18959 * ...
18960 * }
18961 * foo() will be verified first for R1=any_scalar_value. During verification it
18962 * will be assumed that bar() already verified successfully and call to bar()
18963 * from foo() will be checked for type match only. Later bar() will be verified
18964 * independently to check that it's safe for R1=any_scalar_value.
18965 */
18966static int do_check_subprogs(struct bpf_verifier_env *env)
18967{
18968 struct bpf_prog_aux *aux = env->prog->aux;
18969 int i, ret;
18970
18971 if (!aux->func_info)
18972 return 0;
18973
18974 for (i = 1; i < env->subprog_cnt; i++) {
18975 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18976 continue;
18977 env->insn_idx = env->subprog_info[i].start;
18978 WARN_ON_ONCE(env->insn_idx == 0);
18979 ret = do_check_common(env, i);
18980 if (ret) {
18981 return ret;
18982 } else if (env->log.level & BPF_LOG_LEVEL) {
18983 verbose(env,
18984 "Func#%d is safe for any args that match its prototype\n",
18985 i);
18986 }
18987 }
18988 return 0;
18989}
18990
18991static int do_check_main(struct bpf_verifier_env *env)
18992{
18993 int ret;
18994
18995 env->insn_idx = 0;
18996 ret = do_check_common(env, 0);
18997 if (!ret)
18998 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18999 return ret;
19000}
19001
19002
06ee7115
AS
19003static void print_verification_stats(struct bpf_verifier_env *env)
19004{
19005 int i;
19006
19007 if (env->log.level & BPF_LOG_STATS) {
19008 verbose(env, "verification time %lld usec\n",
19009 div_u64(env->verification_time, 1000));
19010 verbose(env, "stack depth ");
19011 for (i = 0; i < env->subprog_cnt; i++) {
19012 u32 depth = env->subprog_info[i].stack_depth;
19013
19014 verbose(env, "%d", depth);
19015 if (i + 1 < env->subprog_cnt)
19016 verbose(env, "+");
19017 }
19018 verbose(env, "\n");
19019 }
19020 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19021 "total_states %d peak_states %d mark_read %d\n",
19022 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19023 env->max_states_per_insn, env->total_states,
19024 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
19025}
19026
27ae7997
MKL
19027static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19028{
19029 const struct btf_type *t, *func_proto;
19030 const struct bpf_struct_ops *st_ops;
19031 const struct btf_member *member;
19032 struct bpf_prog *prog = env->prog;
19033 u32 btf_id, member_idx;
19034 const char *mname;
19035
12aa8a94
THJ
19036 if (!prog->gpl_compatible) {
19037 verbose(env, "struct ops programs must have a GPL compatible license\n");
19038 return -EINVAL;
19039 }
19040
27ae7997
MKL
19041 btf_id = prog->aux->attach_btf_id;
19042 st_ops = bpf_struct_ops_find(btf_id);
19043 if (!st_ops) {
19044 verbose(env, "attach_btf_id %u is not a supported struct\n",
19045 btf_id);
19046 return -ENOTSUPP;
19047 }
19048
19049 t = st_ops->type;
19050 member_idx = prog->expected_attach_type;
19051 if (member_idx >= btf_type_vlen(t)) {
19052 verbose(env, "attach to invalid member idx %u of struct %s\n",
19053 member_idx, st_ops->name);
19054 return -EINVAL;
19055 }
19056
19057 member = &btf_type_member(t)[member_idx];
19058 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19059 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19060 NULL);
19061 if (!func_proto) {
19062 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19063 mname, member_idx, st_ops->name);
19064 return -EINVAL;
19065 }
19066
19067 if (st_ops->check_member) {
51a52a29 19068 int err = st_ops->check_member(t, member, prog);
27ae7997
MKL
19069
19070 if (err) {
19071 verbose(env, "attach to unsupported member %s of struct %s\n",
19072 mname, st_ops->name);
19073 return err;
19074 }
19075 }
19076
19077 prog->aux->attach_func_proto = func_proto;
19078 prog->aux->attach_func_name = mname;
19079 env->ops = st_ops->verifier_ops;
19080
19081 return 0;
19082}
6ba43b76
KS
19083#define SECURITY_PREFIX "security_"
19084
f7b12b6f 19085static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 19086{
69191754 19087 if (within_error_injection_list(addr) ||
f7b12b6f 19088 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 19089 return 0;
6ba43b76 19090
6ba43b76
KS
19091 return -EINVAL;
19092}
27ae7997 19093
1e6c62a8
AS
19094/* list of non-sleepable functions that are otherwise on
19095 * ALLOW_ERROR_INJECTION list
19096 */
19097BTF_SET_START(btf_non_sleepable_error_inject)
19098/* Three functions below can be called from sleepable and non-sleepable context.
19099 * Assume non-sleepable from bpf safety point of view.
19100 */
9dd3d069 19101BTF_ID(func, __filemap_add_folio)
1e6c62a8
AS
19102BTF_ID(func, should_fail_alloc_page)
19103BTF_ID(func, should_failslab)
19104BTF_SET_END(btf_non_sleepable_error_inject)
19105
19106static int check_non_sleepable_error_inject(u32 btf_id)
19107{
19108 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19109}
19110
f7b12b6f
THJ
19111int bpf_check_attach_target(struct bpf_verifier_log *log,
19112 const struct bpf_prog *prog,
19113 const struct bpf_prog *tgt_prog,
19114 u32 btf_id,
19115 struct bpf_attach_target_info *tgt_info)
38207291 19116{
be8704ff 19117 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 19118 const char prefix[] = "btf_trace_";
5b92a28a 19119 int ret = 0, subprog = -1, i;
38207291 19120 const struct btf_type *t;
5b92a28a 19121 bool conservative = true;
38207291 19122 const char *tname;
5b92a28a 19123 struct btf *btf;
f7b12b6f 19124 long addr = 0;
31bf1dbc 19125 struct module *mod = NULL;
38207291 19126
f1b9509c 19127 if (!btf_id) {
efc68158 19128 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
19129 return -EINVAL;
19130 }
22dc4a0f 19131 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 19132 if (!btf) {
efc68158 19133 bpf_log(log,
5b92a28a
AS
19134 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19135 return -EINVAL;
19136 }
19137 t = btf_type_by_id(btf, btf_id);
f1b9509c 19138 if (!t) {
efc68158 19139 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
19140 return -EINVAL;
19141 }
5b92a28a 19142 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 19143 if (!tname) {
efc68158 19144 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
19145 return -EINVAL;
19146 }
5b92a28a
AS
19147 if (tgt_prog) {
19148 struct bpf_prog_aux *aux = tgt_prog->aux;
19149
fd7c211d
THJ
19150 if (bpf_prog_is_dev_bound(prog->aux) &&
19151 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19152 bpf_log(log, "Target program bound device mismatch");
3d76a4d3
SF
19153 return -EINVAL;
19154 }
19155
5b92a28a
AS
19156 for (i = 0; i < aux->func_info_cnt; i++)
19157 if (aux->func_info[i].type_id == btf_id) {
19158 subprog = i;
19159 break;
19160 }
19161 if (subprog == -1) {
efc68158 19162 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
19163 return -EINVAL;
19164 }
19165 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
19166 if (prog_extension) {
19167 if (conservative) {
efc68158 19168 bpf_log(log,
be8704ff
AS
19169 "Cannot replace static functions\n");
19170 return -EINVAL;
19171 }
19172 if (!prog->jit_requested) {
efc68158 19173 bpf_log(log,
be8704ff
AS
19174 "Extension programs should be JITed\n");
19175 return -EINVAL;
19176 }
be8704ff
AS
19177 }
19178 if (!tgt_prog->jited) {
efc68158 19179 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
19180 return -EINVAL;
19181 }
19182 if (tgt_prog->type == prog->type) {
19183 /* Cannot fentry/fexit another fentry/fexit program.
19184 * Cannot attach program extension to another extension.
19185 * It's ok to attach fentry/fexit to extension program.
19186 */
efc68158 19187 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
19188 return -EINVAL;
19189 }
19190 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19191 prog_extension &&
19192 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19193 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19194 /* Program extensions can extend all program types
19195 * except fentry/fexit. The reason is the following.
19196 * The fentry/fexit programs are used for performance
19197 * analysis, stats and can be attached to any program
19198 * type except themselves. When extension program is
19199 * replacing XDP function it is necessary to allow
19200 * performance analysis of all functions. Both original
19201 * XDP program and its program extension. Hence
19202 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19203 * allowed. If extending of fentry/fexit was allowed it
19204 * would be possible to create long call chain
19205 * fentry->extension->fentry->extension beyond
19206 * reasonable stack size. Hence extending fentry is not
19207 * allowed.
19208 */
efc68158 19209 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
19210 return -EINVAL;
19211 }
5b92a28a 19212 } else {
be8704ff 19213 if (prog_extension) {
efc68158 19214 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
19215 return -EINVAL;
19216 }
5b92a28a 19217 }
f1b9509c
AS
19218
19219 switch (prog->expected_attach_type) {
19220 case BPF_TRACE_RAW_TP:
5b92a28a 19221 if (tgt_prog) {
efc68158 19222 bpf_log(log,
5b92a28a
AS
19223 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19224 return -EINVAL;
19225 }
38207291 19226 if (!btf_type_is_typedef(t)) {
efc68158 19227 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
19228 btf_id);
19229 return -EINVAL;
19230 }
f1b9509c 19231 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 19232 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
19233 btf_id, tname);
19234 return -EINVAL;
19235 }
19236 tname += sizeof(prefix) - 1;
5b92a28a 19237 t = btf_type_by_id(btf, t->type);
38207291
MKL
19238 if (!btf_type_is_ptr(t))
19239 /* should never happen in valid vmlinux build */
19240 return -EINVAL;
5b92a28a 19241 t = btf_type_by_id(btf, t->type);
38207291
MKL
19242 if (!btf_type_is_func_proto(t))
19243 /* should never happen in valid vmlinux build */
19244 return -EINVAL;
19245
f7b12b6f 19246 break;
15d83c4d
YS
19247 case BPF_TRACE_ITER:
19248 if (!btf_type_is_func(t)) {
efc68158 19249 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
19250 btf_id);
19251 return -EINVAL;
19252 }
19253 t = btf_type_by_id(btf, t->type);
19254 if (!btf_type_is_func_proto(t))
19255 return -EINVAL;
f7b12b6f
THJ
19256 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19257 if (ret)
19258 return ret;
19259 break;
be8704ff
AS
19260 default:
19261 if (!prog_extension)
19262 return -EINVAL;
df561f66 19263 fallthrough;
ae240823 19264 case BPF_MODIFY_RETURN:
9e4e01df 19265 case BPF_LSM_MAC:
69fd337a 19266 case BPF_LSM_CGROUP:
fec56f58
AS
19267 case BPF_TRACE_FENTRY:
19268 case BPF_TRACE_FEXIT:
19269 if (!btf_type_is_func(t)) {
efc68158 19270 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
19271 btf_id);
19272 return -EINVAL;
19273 }
be8704ff 19274 if (prog_extension &&
efc68158 19275 btf_check_type_match(log, prog, btf, t))
be8704ff 19276 return -EINVAL;
5b92a28a 19277 t = btf_type_by_id(btf, t->type);
fec56f58
AS
19278 if (!btf_type_is_func_proto(t))
19279 return -EINVAL;
f7b12b6f 19280
4a1e7c0c
THJ
19281 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19282 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19283 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19284 return -EINVAL;
19285
f7b12b6f 19286 if (tgt_prog && conservative)
5b92a28a 19287 t = NULL;
f7b12b6f
THJ
19288
19289 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 19290 if (ret < 0)
f7b12b6f
THJ
19291 return ret;
19292
5b92a28a 19293 if (tgt_prog) {
e9eeec58
YS
19294 if (subprog == 0)
19295 addr = (long) tgt_prog->bpf_func;
19296 else
19297 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a 19298 } else {
31bf1dbc
VM
19299 if (btf_is_module(btf)) {
19300 mod = btf_try_get_module(btf);
19301 if (mod)
19302 addr = find_kallsyms_symbol_value(mod, tname);
19303 else
19304 addr = 0;
19305 } else {
19306 addr = kallsyms_lookup_name(tname);
19307 }
5b92a28a 19308 if (!addr) {
31bf1dbc 19309 module_put(mod);
efc68158 19310 bpf_log(log,
5b92a28a
AS
19311 "The address of function %s cannot be found\n",
19312 tname);
f7b12b6f 19313 return -ENOENT;
5b92a28a 19314 }
fec56f58 19315 }
18644cec 19316
1e6c62a8
AS
19317 if (prog->aux->sleepable) {
19318 ret = -EINVAL;
19319 switch (prog->type) {
19320 case BPF_PROG_TYPE_TRACING:
5b481aca
BT
19321
19322 /* fentry/fexit/fmod_ret progs can be sleepable if they are
1e6c62a8
AS
19323 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19324 */
19325 if (!check_non_sleepable_error_inject(btf_id) &&
19326 within_error_injection_list(addr))
19327 ret = 0;
5b481aca
BT
19328 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19329 * in the fmodret id set with the KF_SLEEPABLE flag.
19330 */
19331 else {
e924e80e
AG
19332 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19333 prog);
5b481aca
BT
19334
19335 if (flags && (*flags & KF_SLEEPABLE))
19336 ret = 0;
19337 }
1e6c62a8
AS
19338 break;
19339 case BPF_PROG_TYPE_LSM:
19340 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19341 * Only some of them are sleepable.
19342 */
423f1610 19343 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
19344 ret = 0;
19345 break;
19346 default:
19347 break;
19348 }
f7b12b6f 19349 if (ret) {
31bf1dbc 19350 module_put(mod);
f7b12b6f
THJ
19351 bpf_log(log, "%s is not sleepable\n", tname);
19352 return ret;
19353 }
1e6c62a8 19354 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 19355 if (tgt_prog) {
31bf1dbc 19356 module_put(mod);
efc68158 19357 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
19358 return -EINVAL;
19359 }
5b481aca 19360 ret = -EINVAL;
e924e80e 19361 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
5b481aca
BT
19362 !check_attach_modify_return(addr, tname))
19363 ret = 0;
f7b12b6f 19364 if (ret) {
31bf1dbc 19365 module_put(mod);
f7b12b6f
THJ
19366 bpf_log(log, "%s() is not modifiable\n", tname);
19367 return ret;
1af9270e 19368 }
18644cec 19369 }
f7b12b6f
THJ
19370
19371 break;
19372 }
19373 tgt_info->tgt_addr = addr;
19374 tgt_info->tgt_name = tname;
19375 tgt_info->tgt_type = t;
31bf1dbc 19376 tgt_info->tgt_mod = mod;
f7b12b6f
THJ
19377 return 0;
19378}
19379
35e3815f
JO
19380BTF_SET_START(btf_id_deny)
19381BTF_ID_UNUSED
19382#ifdef CONFIG_SMP
19383BTF_ID(func, migrate_disable)
19384BTF_ID(func, migrate_enable)
19385#endif
19386#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19387BTF_ID(func, rcu_read_unlock_strict)
19388#endif
c11bd046
Y
19389#if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19390BTF_ID(func, preempt_count_add)
19391BTF_ID(func, preempt_count_sub)
19392#endif
a0c109dc
YS
19393#ifdef CONFIG_PREEMPT_RCU
19394BTF_ID(func, __rcu_read_lock)
19395BTF_ID(func, __rcu_read_unlock)
19396#endif
35e3815f
JO
19397BTF_SET_END(btf_id_deny)
19398
700e6f85
JO
19399static bool can_be_sleepable(struct bpf_prog *prog)
19400{
19401 if (prog->type == BPF_PROG_TYPE_TRACING) {
19402 switch (prog->expected_attach_type) {
19403 case BPF_TRACE_FENTRY:
19404 case BPF_TRACE_FEXIT:
19405 case BPF_MODIFY_RETURN:
19406 case BPF_TRACE_ITER:
19407 return true;
19408 default:
19409 return false;
19410 }
19411 }
19412 return prog->type == BPF_PROG_TYPE_LSM ||
1e12d3ef
DV
19413 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19414 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
700e6f85
JO
19415}
19416
f7b12b6f
THJ
19417static int check_attach_btf_id(struct bpf_verifier_env *env)
19418{
19419 struct bpf_prog *prog = env->prog;
3aac1ead 19420 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
19421 struct bpf_attach_target_info tgt_info = {};
19422 u32 btf_id = prog->aux->attach_btf_id;
19423 struct bpf_trampoline *tr;
19424 int ret;
19425 u64 key;
19426
79a7f8bd
AS
19427 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19428 if (prog->aux->sleepable)
19429 /* attach_btf_id checked to be zero already */
19430 return 0;
19431 verbose(env, "Syscall programs can only be sleepable\n");
19432 return -EINVAL;
19433 }
19434
700e6f85 19435 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
1e12d3ef 19436 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
f7b12b6f
THJ
19437 return -EINVAL;
19438 }
19439
19440 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19441 return check_struct_ops_btf_id(env);
19442
19443 if (prog->type != BPF_PROG_TYPE_TRACING &&
19444 prog->type != BPF_PROG_TYPE_LSM &&
19445 prog->type != BPF_PROG_TYPE_EXT)
19446 return 0;
19447
19448 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19449 if (ret)
fec56f58 19450 return ret;
f7b12b6f
THJ
19451
19452 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
19453 /* to make freplace equivalent to their targets, they need to
19454 * inherit env->ops and expected_attach_type for the rest of the
19455 * verification
19456 */
f7b12b6f
THJ
19457 env->ops = bpf_verifier_ops[tgt_prog->type];
19458 prog->expected_attach_type = tgt_prog->expected_attach_type;
19459 }
19460
19461 /* store info about the attachment target that will be used later */
19462 prog->aux->attach_func_proto = tgt_info.tgt_type;
19463 prog->aux->attach_func_name = tgt_info.tgt_name;
31bf1dbc 19464 prog->aux->mod = tgt_info.tgt_mod;
f7b12b6f 19465
4a1e7c0c
THJ
19466 if (tgt_prog) {
19467 prog->aux->saved_dst_prog_type = tgt_prog->type;
19468 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19469 }
19470
f7b12b6f
THJ
19471 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19472 prog->aux->attach_btf_trace = true;
19473 return 0;
19474 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19475 if (!bpf_iter_prog_supported(prog))
19476 return -EINVAL;
19477 return 0;
19478 }
19479
19480 if (prog->type == BPF_PROG_TYPE_LSM) {
19481 ret = bpf_lsm_verify_prog(&env->log, prog);
19482 if (ret < 0)
19483 return ret;
35e3815f
JO
19484 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19485 btf_id_set_contains(&btf_id_deny, btf_id)) {
19486 return -EINVAL;
38207291 19487 }
f7b12b6f 19488
22dc4a0f 19489 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
19490 tr = bpf_trampoline_get(key, &tgt_info);
19491 if (!tr)
19492 return -ENOMEM;
19493
3aac1ead 19494 prog->aux->dst_trampoline = tr;
f7b12b6f 19495 return 0;
38207291
MKL
19496}
19497
76654e67
AM
19498struct btf *bpf_get_btf_vmlinux(void)
19499{
19500 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19501 mutex_lock(&bpf_verifier_lock);
19502 if (!btf_vmlinux)
19503 btf_vmlinux = btf_parse_vmlinux();
19504 mutex_unlock(&bpf_verifier_lock);
19505 }
19506 return btf_vmlinux;
19507}
19508
47a71c1f 19509int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
51580e79 19510{
06ee7115 19511 u64 start_time = ktime_get_ns();
58e2af8b 19512 struct bpf_verifier_env *env;
bdcab414
AN
19513 int i, len, ret = -EINVAL, err;
19514 u32 log_true_size;
e2ae4ca2 19515 bool is_priv;
51580e79 19516
eba0c929
AB
19517 /* no program is valid */
19518 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19519 return -EINVAL;
19520
58e2af8b 19521 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
19522 * allocate/free it every time bpf_check() is called
19523 */
58e2af8b 19524 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
19525 if (!env)
19526 return -ENOMEM;
19527
407958a0
AN
19528 env->bt.env = env;
19529
9e4c24e7 19530 len = (*prog)->len;
fad953ce 19531 env->insn_aux_data =
9e4c24e7 19532 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
19533 ret = -ENOMEM;
19534 if (!env->insn_aux_data)
19535 goto err_free_env;
9e4c24e7
JK
19536 for (i = 0; i < len; i++)
19537 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 19538 env->prog = *prog;
00176a34 19539 env->ops = bpf_verifier_ops[env->prog->type];
387544bf 19540 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
2c78ee89 19541 is_priv = bpf_capable();
0246e64d 19542
76654e67 19543 bpf_get_btf_vmlinux();
8580ac94 19544
cbd35700 19545 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
19546 if (!is_priv)
19547 mutex_lock(&bpf_verifier_lock);
cbd35700 19548
bdcab414
AN
19549 /* user could have requested verbose verifier output
19550 * and supplied buffer to store the verification trace
19551 */
19552 ret = bpf_vlog_init(&env->log, attr->log_level,
19553 (char __user *) (unsigned long) attr->log_buf,
19554 attr->log_size);
19555 if (ret)
19556 goto err_unlock;
1ad2f583 19557
0f55f9ed
CL
19558 mark_verifier_state_clean(env);
19559
8580ac94
AS
19560 if (IS_ERR(btf_vmlinux)) {
19561 /* Either gcc or pahole or kernel are broken. */
19562 verbose(env, "in-kernel BTF is malformed\n");
19563 ret = PTR_ERR(btf_vmlinux);
38207291 19564 goto skip_full_check;
8580ac94
AS
19565 }
19566
1ad2f583
DB
19567 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19568 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 19569 env->strict_alignment = true;
e9ee9efc
DM
19570 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19571 env->strict_alignment = false;
cbd35700 19572
2c78ee89 19573 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 19574 env->allow_uninit_stack = bpf_allow_uninit_stack();
2c78ee89
AS
19575 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19576 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19577 env->bpf_capable = bpf_capable();
e2ae4ca2 19578
10d274e8
AS
19579 if (is_priv)
19580 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19581
dc2a4ebc 19582 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 19583 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
19584 GFP_USER);
19585 ret = -ENOMEM;
19586 if (!env->explored_states)
19587 goto skip_full_check;
19588
e6ac2450
MKL
19589 ret = add_subprog_and_kfunc(env);
19590 if (ret < 0)
19591 goto skip_full_check;
19592
d9762e84 19593 ret = check_subprogs(env);
475fb78f
AS
19594 if (ret < 0)
19595 goto skip_full_check;
19596
c454a46b 19597 ret = check_btf_info(env, attr, uattr);
838e9690
YS
19598 if (ret < 0)
19599 goto skip_full_check;
19600
be8704ff
AS
19601 ret = check_attach_btf_id(env);
19602 if (ret)
19603 goto skip_full_check;
19604
4976b718
HL
19605 ret = resolve_pseudo_ldimm64(env);
19606 if (ret < 0)
19607 goto skip_full_check;
19608
9d03ebc7 19609 if (bpf_prog_is_offloaded(env->prog->aux)) {
ceb11679
YZ
19610 ret = bpf_prog_offload_verifier_prep(env->prog);
19611 if (ret)
19612 goto skip_full_check;
19613 }
19614
d9762e84
MKL
19615 ret = check_cfg(env);
19616 if (ret < 0)
19617 goto skip_full_check;
19618
51c39bb1
AS
19619 ret = do_check_subprogs(env);
19620 ret = ret ?: do_check_main(env);
cbd35700 19621
9d03ebc7 19622 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
c941ce9c
QM
19623 ret = bpf_prog_offload_finalize(env);
19624
0246e64d 19625skip_full_check:
51c39bb1 19626 kvfree(env->explored_states);
0246e64d 19627
c131187d 19628 if (ret == 0)
9b38c405 19629 ret = check_max_stack_depth(env);
c131187d 19630
9b38c405 19631 /* instruction rewrites happen after this point */
1ade2371
EZ
19632 if (ret == 0)
19633 ret = optimize_bpf_loop(env);
19634
e2ae4ca2
JK
19635 if (is_priv) {
19636 if (ret == 0)
19637 opt_hard_wire_dead_code_branches(env);
52875a04
JK
19638 if (ret == 0)
19639 ret = opt_remove_dead_code(env);
a1b14abc
JK
19640 if (ret == 0)
19641 ret = opt_remove_nops(env);
52875a04
JK
19642 } else {
19643 if (ret == 0)
19644 sanitize_dead_code(env);
e2ae4ca2
JK
19645 }
19646
9bac3d6d
AS
19647 if (ret == 0)
19648 /* program is valid, convert *(u32*)(ctx + off) accesses */
19649 ret = convert_ctx_accesses(env);
19650
e245c5c6 19651 if (ret == 0)
e6ac5933 19652 ret = do_misc_fixups(env);
e245c5c6 19653
a4b1d3c1
JW
19654 /* do 32-bit optimization after insn patching has done so those patched
19655 * insns could be handled correctly.
19656 */
9d03ebc7 19657 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
d6c2308c
JW
19658 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19659 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19660 : false;
a4b1d3c1
JW
19661 }
19662
1ea47e01
AS
19663 if (ret == 0)
19664 ret = fixup_call_args(env);
19665
06ee7115
AS
19666 env->verification_time = ktime_get_ns() - start_time;
19667 print_verification_stats(env);
aba64c7d 19668 env->prog->aux->verified_insns = env->insn_processed;
06ee7115 19669
bdcab414
AN
19670 /* preserve original error even if log finalization is successful */
19671 err = bpf_vlog_finalize(&env->log, &log_true_size);
19672 if (err)
19673 ret = err;
19674
47a71c1f
AN
19675 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19676 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
bdcab414 19677 &log_true_size, sizeof(log_true_size))) {
47a71c1f
AN
19678 ret = -EFAULT;
19679 goto err_release_maps;
19680 }
cbd35700 19681
541c3bad
AN
19682 if (ret)
19683 goto err_release_maps;
19684
19685 if (env->used_map_cnt) {
0246e64d 19686 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
19687 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19688 sizeof(env->used_maps[0]),
19689 GFP_KERNEL);
0246e64d 19690
9bac3d6d 19691 if (!env->prog->aux->used_maps) {
0246e64d 19692 ret = -ENOMEM;
a2a7d570 19693 goto err_release_maps;
0246e64d
AS
19694 }
19695
9bac3d6d 19696 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 19697 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 19698 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
19699 }
19700 if (env->used_btf_cnt) {
19701 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19702 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19703 sizeof(env->used_btfs[0]),
19704 GFP_KERNEL);
19705 if (!env->prog->aux->used_btfs) {
19706 ret = -ENOMEM;
19707 goto err_release_maps;
19708 }
0246e64d 19709
541c3bad
AN
19710 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19711 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19712 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19713 }
19714 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
19715 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19716 * bpf_ld_imm64 instructions
19717 */
19718 convert_pseudo_ld_imm64(env);
19719 }
cbd35700 19720
541c3bad 19721 adjust_btf_func(env);
ba64e7d8 19722
a2a7d570 19723err_release_maps:
9bac3d6d 19724 if (!env->prog->aux->used_maps)
0246e64d 19725 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 19726 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
19727 */
19728 release_maps(env);
541c3bad
AN
19729 if (!env->prog->aux->used_btfs)
19730 release_btfs(env);
03f87c0b
THJ
19731
19732 /* extension progs temporarily inherit the attach_type of their targets
19733 for verification purposes, so set it back to zero before returning
19734 */
19735 if (env->prog->type == BPF_PROG_TYPE_EXT)
19736 env->prog->expected_attach_type = 0;
19737
9bac3d6d 19738 *prog = env->prog;
3df126f3 19739err_unlock:
45a73c17
AS
19740 if (!is_priv)
19741 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
19742 vfree(env->insn_aux_data);
19743err_free_env:
19744 kfree(env);
51580e79
AS
19745 return ret;
19746}