bpf: Introduce might_sleep field in bpf_func_proto
[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>
51580e79 27
f4ac7e0b
JK
28#include "disasm.h"
29
00176a34 30static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 31#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
32 [_id] = & _name ## _verifier_ops,
33#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 34#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
35#include <linux/bpf_types.h>
36#undef BPF_PROG_TYPE
37#undef BPF_MAP_TYPE
f2e10bff 38#undef BPF_LINK_TYPE
00176a34
JK
39};
40
51580e79
AS
41/* bpf_check() is a static code analyzer that walks eBPF program
42 * instruction by instruction and updates register/stack state.
43 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44 *
45 * The first pass is depth-first-search to check that the program is a DAG.
46 * It rejects the following programs:
47 * - larger than BPF_MAXINSNS insns
48 * - if loop is present (detected via back-edge)
49 * - unreachable insns exist (shouldn't be a forest. program = one function)
50 * - out of bounds or malformed jumps
51 * The second pass is all possible path descent from the 1st insn.
8fb33b60 52 * Since it's analyzing all paths through the program, the length of the
eba38a96 53 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
54 * insn is less then 4K, but there are too many branches that change stack/regs.
55 * Number of 'branches to be analyzed' is limited to 1k
56 *
57 * On entry to each instruction, each register has a type, and the instruction
58 * changes the types of the registers depending on instruction semantics.
59 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60 * copied to R1.
61 *
62 * All registers are 64-bit.
63 * R0 - return register
64 * R1-R5 argument passing registers
65 * R6-R9 callee saved registers
66 * R10 - frame pointer read-only
67 *
68 * At the start of BPF program the register R1 contains a pointer to bpf_context
69 * and has type PTR_TO_CTX.
70 *
71 * Verifier tracks arithmetic operations on pointers in case:
72 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74 * 1st insn copies R10 (which has FRAME_PTR) type into R1
75 * and 2nd arithmetic instruction is pattern matched to recognize
76 * that it wants to construct a pointer to some element within stack.
77 * So after 2nd insn, the register R1 has type PTR_TO_STACK
78 * (and -20 constant is saved for further stack bounds checking).
79 * Meaning that this reg is a pointer to stack plus known immediate constant.
80 *
f1174f77 81 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 82 * means the register has some value, but it's not a valid pointer.
f1174f77 83 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
84 *
85 * When verifier sees load or store instructions the type of base register
c64b7983
JS
86 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87 * four pointer types recognized by check_mem_access() function.
51580e79
AS
88 *
89 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90 * and the range of [ptr, ptr + map's value_size) is accessible.
91 *
92 * registers used to pass values to function calls are checked against
93 * function argument constraints.
94 *
95 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96 * It means that the register type passed to this function must be
97 * PTR_TO_STACK and it will be used inside the function as
98 * 'pointer to map element key'
99 *
100 * For example the argument constraints for bpf_map_lookup_elem():
101 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102 * .arg1_type = ARG_CONST_MAP_PTR,
103 * .arg2_type = ARG_PTR_TO_MAP_KEY,
104 *
105 * ret_type says that this function returns 'pointer to map elem value or null'
106 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107 * 2nd argument should be a pointer to stack, which will be used inside
108 * the helper function as a pointer to map element key.
109 *
110 * On the kernel side the helper function looks like:
111 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112 * {
113 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114 * void *key = (void *) (unsigned long) r2;
115 * void *value;
116 *
117 * here kernel can access 'key' and 'map' pointers safely, knowing that
118 * [key, key + map->key_size) bytes are valid and were initialized on
119 * the stack of eBPF program.
120 * }
121 *
122 * Corresponding eBPF program may look like:
123 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
124 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
126 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127 * here verifier looks at prototype of map_lookup_elem() and sees:
128 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130 *
131 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133 * and were initialized prior to this call.
134 * If it's ok, then verifier allows this BPF_CALL insn and looks at
135 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
8fb33b60 137 * returns either pointer to map value or NULL.
51580e79
AS
138 *
139 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140 * insn, the register holding that pointer in the true branch changes state to
141 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142 * branch. See check_cond_jmp_op().
143 *
144 * After the call R0 is set to return type of the function and registers R1-R5
145 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
146 *
147 * The following reference types represent a potential reference to a kernel
148 * resource which, after first being allocated, must be checked and freed by
149 * the BPF program:
150 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151 *
152 * When the verifier sees a helper call return a reference type, it allocates a
153 * pointer id for the reference and stores it in the current function state.
154 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156 * passes through a NULL-check conditional. For the branch wherein the state is
157 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
158 *
159 * For each helper function that allocates a reference, such as
160 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161 * bpf_sk_release(). When a reference type passes into the release function,
162 * the verifier also releases the reference. If any unchecked or unreleased
163 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
164 */
165
17a52670 166/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 167struct bpf_verifier_stack_elem {
17a52670
AS
168 /* verifer state is 'st'
169 * before processing instruction 'insn_idx'
170 * and after processing instruction 'prev_insn_idx'
171 */
58e2af8b 172 struct bpf_verifier_state st;
17a52670
AS
173 int insn_idx;
174 int prev_insn_idx;
58e2af8b 175 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
176 /* length of verifier log at the time this state was pushed on stack */
177 u32 log_pos;
cbd35700
AS
178};
179
b285fcb7 180#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 181#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 182
d2e4c1e6
DB
183#define BPF_MAP_KEY_POISON (1ULL << 63)
184#define BPF_MAP_KEY_SEEN (1ULL << 62)
185
c93552c4
DB
186#define BPF_MAP_PTR_UNPRIV 1UL
187#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
188 POISON_POINTER_DELTA))
189#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
bc34dee6
JK
191static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193
c93552c4
DB
194static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
197}
198
199static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200{
d2e4c1e6 201 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
202}
203
204static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 const struct bpf_map *map, bool unpriv)
206{
207 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
209 aux->map_ptr_state = (unsigned long)map |
210 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211}
212
213static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214{
215 return aux->map_key_state & BPF_MAP_KEY_POISON;
216}
217
218static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219{
220 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221}
222
223static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224{
225 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226}
227
228static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229{
230 bool poisoned = bpf_map_key_poisoned(aux);
231
232 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 234}
fad73a1a 235
23a2d70c
YS
236static bool bpf_pseudo_call(const struct bpf_insn *insn)
237{
238 return insn->code == (BPF_JMP | BPF_CALL) &&
239 insn->src_reg == BPF_PSEUDO_CALL;
240}
241
e6ac2450
MKL
242static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243{
244 return insn->code == (BPF_JMP | BPF_CALL) &&
245 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246}
247
33ff9823
DB
248struct bpf_call_arg_meta {
249 struct bpf_map *map_ptr;
435faee1 250 bool raw_mode;
36bbef52 251 bool pkt_access;
8f14852e 252 u8 release_regno;
435faee1
DB
253 int regno;
254 int access_size;
457f4436 255 int mem_size;
10060503 256 u64 msize_max_value;
1b986589 257 int ref_obj_id;
3e8ce298 258 int map_uid;
d83525ca 259 int func_id;
22dc4a0f 260 struct btf *btf;
eaa6bcb7 261 u32 btf_id;
22dc4a0f 262 struct btf *ret_btf;
eaa6bcb7 263 u32 ret_btf_id;
69c087ba 264 u32 subprogno;
aa3496ac 265 struct btf_field *kptr_field;
97e03f52 266 u8 uninit_dynptr_regno;
33ff9823
DB
267};
268
8580ac94
AS
269struct btf *btf_vmlinux;
270
cbd35700
AS
271static DEFINE_MUTEX(bpf_verifier_lock);
272
d9762e84
MKL
273static const struct bpf_line_info *
274find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275{
276 const struct bpf_line_info *linfo;
277 const struct bpf_prog *prog;
278 u32 i, nr_linfo;
279
280 prog = env->prog;
281 nr_linfo = prog->aux->nr_linfo;
282
283 if (!nr_linfo || insn_off >= prog->len)
284 return NULL;
285
286 linfo = prog->aux->linfo;
287 for (i = 1; i < nr_linfo; i++)
288 if (insn_off < linfo[i].insn_off)
289 break;
290
291 return &linfo[i - 1];
292}
293
77d2e05a
MKL
294void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 va_list args)
cbd35700 296{
a2a7d570 297 unsigned int n;
cbd35700 298
a2a7d570 299 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
300
301 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 "verifier log line truncated - local buffer too short\n");
303
8580ac94 304 if (log->level == BPF_LOG_KERNEL) {
436d404c
HT
305 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
8580ac94
AS
308 return;
309 }
436d404c
HT
310
311 n = min(log->len_total - log->len_used - 1, n);
312 log->kbuf[n] = '\0';
a2a7d570
JK
313 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 log->len_used += n;
315 else
316 log->ubuf = NULL;
cbd35700 317}
abe08840 318
6f8a57cc
AN
319static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320{
321 char zero = 0;
322
323 if (!bpf_verifier_log_needed(log))
324 return;
325
326 log->len_used = new_pos;
327 if (put_user(zero, log->ubuf + new_pos))
328 log->ubuf = NULL;
329}
330
abe08840
JO
331/* log_level controls verbosity level of eBPF verifier.
332 * bpf_verifier_log_write() is used to dump the verification trace to the log,
333 * so the user can figure out what's wrong with the program
430e68d1 334 */
abe08840
JO
335__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 const char *fmt, ...)
337{
338 va_list args;
339
77d2e05a
MKL
340 if (!bpf_verifier_log_needed(&env->log))
341 return;
342
abe08840 343 va_start(args, fmt);
77d2e05a 344 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
345 va_end(args);
346}
347EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
349__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350{
77d2e05a 351 struct bpf_verifier_env *env = private_data;
abe08840
JO
352 va_list args;
353
77d2e05a
MKL
354 if (!bpf_verifier_log_needed(&env->log))
355 return;
356
abe08840 357 va_start(args, fmt);
77d2e05a 358 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
359 va_end(args);
360}
cbd35700 361
9e15db66
AS
362__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 const char *fmt, ...)
364{
365 va_list args;
366
367 if (!bpf_verifier_log_needed(log))
368 return;
369
370 va_start(args, fmt);
371 bpf_verifier_vlog(log, fmt, args);
372 va_end(args);
373}
84c6ac41 374EXPORT_SYMBOL_GPL(bpf_log);
9e15db66 375
d9762e84
MKL
376static const char *ltrim(const char *s)
377{
378 while (isspace(*s))
379 s++;
380
381 return s;
382}
383
384__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 u32 insn_off,
386 const char *prefix_fmt, ...)
387{
388 const struct bpf_line_info *linfo;
389
390 if (!bpf_verifier_log_needed(&env->log))
391 return;
392
393 linfo = find_linfo(env, insn_off);
394 if (!linfo || linfo == env->prev_linfo)
395 return;
396
397 if (prefix_fmt) {
398 va_list args;
399
400 va_start(args, prefix_fmt);
401 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 va_end(args);
403 }
404
405 verbose(env, "%s\n",
406 ltrim(btf_name_by_offset(env->prog->aux->btf,
407 linfo->line_off)));
408
409 env->prev_linfo = linfo;
410}
411
bc2591d6
YS
412static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 struct bpf_reg_state *reg,
414 struct tnum *range, const char *ctx,
415 const char *reg_name)
416{
417 char tn_buf[48];
418
419 verbose(env, "At %s the register %s ", ctx, reg_name);
420 if (!tnum_is_unknown(reg->var_off)) {
421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 verbose(env, "has value %s", tn_buf);
423 } else {
424 verbose(env, "has unknown scalar value");
425 }
426 tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 verbose(env, " should have been in %s\n", tn_buf);
428}
429
de8f3a83
DB
430static bool type_is_pkt_pointer(enum bpf_reg_type type)
431{
0c9a7a7e 432 type = base_type(type);
de8f3a83
DB
433 return type == PTR_TO_PACKET ||
434 type == PTR_TO_PACKET_META;
435}
436
46f8bc92
MKL
437static bool type_is_sk_pointer(enum bpf_reg_type type)
438{
439 return type == PTR_TO_SOCKET ||
655a51e5 440 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
443}
444
cac616db
JF
445static bool reg_type_not_null(enum bpf_reg_type type)
446{
447 return type == PTR_TO_SOCKET ||
448 type == PTR_TO_TCP_SOCK ||
449 type == PTR_TO_MAP_VALUE ||
69c087ba 450 type == PTR_TO_MAP_KEY ||
01c66c48 451 type == PTR_TO_SOCK_COMMON;
cac616db
JF
452}
453
4e814da0
KKD
454static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
455{
456 struct btf_record *rec = NULL;
457 struct btf_struct_meta *meta;
458
459 if (reg->type == PTR_TO_MAP_VALUE) {
460 rec = reg->map_ptr->record;
461 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
462 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
463 if (meta)
464 rec = meta->record;
465 }
466 return rec;
467}
468
d83525ca
AS
469static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
470{
4e814da0 471 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
cba368c1
MKL
472}
473
20b2aff4
HL
474static bool type_is_rdonly_mem(u32 type)
475{
476 return type & MEM_RDONLY;
cba368c1
MKL
477}
478
48946bd6 479static bool type_may_be_null(u32 type)
fd1b0d60 480{
48946bd6 481 return type & PTR_MAYBE_NULL;
fd1b0d60
LB
482}
483
64d85290
JS
484static bool is_acquire_function(enum bpf_func_id func_id,
485 const struct bpf_map *map)
486{
487 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
488
489 if (func_id == BPF_FUNC_sk_lookup_tcp ||
490 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436 491 func_id == BPF_FUNC_skc_lookup_tcp ||
c0a5a21c
KKD
492 func_id == BPF_FUNC_ringbuf_reserve ||
493 func_id == BPF_FUNC_kptr_xchg)
64d85290
JS
494 return true;
495
496 if (func_id == BPF_FUNC_map_lookup_elem &&
497 (map_type == BPF_MAP_TYPE_SOCKMAP ||
498 map_type == BPF_MAP_TYPE_SOCKHASH))
499 return true;
500
501 return false;
46f8bc92
MKL
502}
503
1b986589
MKL
504static bool is_ptr_cast_function(enum bpf_func_id func_id)
505{
506 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
507 func_id == BPF_FUNC_sk_fullsock ||
508 func_id == BPF_FUNC_skc_to_tcp_sock ||
509 func_id == BPF_FUNC_skc_to_tcp6_sock ||
510 func_id == BPF_FUNC_skc_to_udp6_sock ||
3bc253c2 511 func_id == BPF_FUNC_skc_to_mptcp_sock ||
1df8f55a
MKL
512 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
513 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
514}
515
88374342 516static bool is_dynptr_ref_function(enum bpf_func_id func_id)
b2d8ef19
DM
517{
518 return func_id == BPF_FUNC_dynptr_data;
519}
520
be2ef816
AN
521static bool is_callback_calling_function(enum bpf_func_id func_id)
522{
523 return func_id == BPF_FUNC_for_each_map_elem ||
524 func_id == BPF_FUNC_timer_set_callback ||
525 func_id == BPF_FUNC_find_vma ||
526 func_id == BPF_FUNC_loop ||
527 func_id == BPF_FUNC_user_ringbuf_drain;
528}
529
b2d8ef19
DM
530static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
531 const struct bpf_map *map)
532{
533 int ref_obj_uses = 0;
534
535 if (is_ptr_cast_function(func_id))
536 ref_obj_uses++;
537 if (is_acquire_function(func_id, map))
538 ref_obj_uses++;
88374342 539 if (is_dynptr_ref_function(func_id))
b2d8ef19
DM
540 ref_obj_uses++;
541
542 return ref_obj_uses > 1;
543}
544
39491867
BJ
545static bool is_cmpxchg_insn(const struct bpf_insn *insn)
546{
547 return BPF_CLASS(insn->code) == BPF_STX &&
548 BPF_MODE(insn->code) == BPF_ATOMIC &&
549 insn->imm == BPF_CMPXCHG;
550}
551
c25b2ae1
HL
552/* string representation of 'enum bpf_reg_type'
553 *
554 * Note that reg_type_str() can not appear more than once in a single verbose()
555 * statement.
556 */
557static const char *reg_type_str(struct bpf_verifier_env *env,
558 enum bpf_reg_type type)
559{
ef66c547 560 char postfix[16] = {0}, prefix[64] = {0};
c25b2ae1
HL
561 static const char * const str[] = {
562 [NOT_INIT] = "?",
7df5072c 563 [SCALAR_VALUE] = "scalar",
c25b2ae1
HL
564 [PTR_TO_CTX] = "ctx",
565 [CONST_PTR_TO_MAP] = "map_ptr",
566 [PTR_TO_MAP_VALUE] = "map_value",
567 [PTR_TO_STACK] = "fp",
568 [PTR_TO_PACKET] = "pkt",
569 [PTR_TO_PACKET_META] = "pkt_meta",
570 [PTR_TO_PACKET_END] = "pkt_end",
571 [PTR_TO_FLOW_KEYS] = "flow_keys",
572 [PTR_TO_SOCKET] = "sock",
573 [PTR_TO_SOCK_COMMON] = "sock_common",
574 [PTR_TO_TCP_SOCK] = "tcp_sock",
575 [PTR_TO_TP_BUFFER] = "tp_buffer",
576 [PTR_TO_XDP_SOCK] = "xdp_sock",
577 [PTR_TO_BTF_ID] = "ptr_",
c25b2ae1 578 [PTR_TO_MEM] = "mem",
20b2aff4 579 [PTR_TO_BUF] = "buf",
c25b2ae1
HL
580 [PTR_TO_FUNC] = "func",
581 [PTR_TO_MAP_KEY] = "map_key",
20571567 582 [PTR_TO_DYNPTR] = "dynptr_ptr",
c25b2ae1
HL
583 };
584
585 if (type & PTR_MAYBE_NULL) {
5844101a 586 if (base_type(type) == PTR_TO_BTF_ID)
c25b2ae1
HL
587 strncpy(postfix, "or_null_", 16);
588 else
589 strncpy(postfix, "_or_null", 16);
590 }
591
3f00c523 592 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s",
ef66c547
DV
593 type & MEM_RDONLY ? "rdonly_" : "",
594 type & MEM_RINGBUF ? "ringbuf_" : "",
595 type & MEM_USER ? "user_" : "",
596 type & MEM_PERCPU ? "percpu_" : "",
3f00c523
DV
597 type & PTR_UNTRUSTED ? "untrusted_" : "",
598 type & PTR_TRUSTED ? "trusted_" : ""
ef66c547 599 );
20b2aff4
HL
600
601 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
602 prefix, str[base_type(type)], postfix);
c25b2ae1
HL
603 return env->type_str_buf;
604}
17a52670 605
8efea21d
EC
606static char slot_type_char[] = {
607 [STACK_INVALID] = '?',
608 [STACK_SPILL] = 'r',
609 [STACK_MISC] = 'm',
610 [STACK_ZERO] = '0',
97e03f52 611 [STACK_DYNPTR] = 'd',
8efea21d
EC
612};
613
4e92024a
AS
614static void print_liveness(struct bpf_verifier_env *env,
615 enum bpf_reg_liveness live)
616{
9242b5f5 617 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
618 verbose(env, "_");
619 if (live & REG_LIVE_READ)
620 verbose(env, "r");
621 if (live & REG_LIVE_WRITTEN)
622 verbose(env, "w");
9242b5f5
AS
623 if (live & REG_LIVE_DONE)
624 verbose(env, "D");
4e92024a
AS
625}
626
97e03f52
JK
627static int get_spi(s32 off)
628{
629 return (-off - 1) / BPF_REG_SIZE;
630}
631
632static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
633{
634 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
635
636 /* We need to check that slots between [spi - nr_slots + 1, spi] are
637 * within [0, allocated_stack).
638 *
639 * Please note that the spi grows downwards. For example, a dynptr
640 * takes the size of two stack slots; the first slot will be at
641 * spi and the second slot will be at spi - 1.
642 */
643 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
644}
645
f4d7e40a
AS
646static struct bpf_func_state *func(struct bpf_verifier_env *env,
647 const struct bpf_reg_state *reg)
648{
649 struct bpf_verifier_state *cur = env->cur_state;
650
651 return cur->frame[reg->frameno];
652}
653
22dc4a0f 654static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 655{
22dc4a0f 656 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
657}
658
0f55f9ed
CL
659static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
660{
661 env->scratched_regs |= 1U << regno;
662}
663
664static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
665{
343e5375 666 env->scratched_stack_slots |= 1ULL << spi;
0f55f9ed
CL
667}
668
669static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
670{
671 return (env->scratched_regs >> regno) & 1;
672}
673
674static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
675{
676 return (env->scratched_stack_slots >> regno) & 1;
677}
678
679static bool verifier_state_scratched(const struct bpf_verifier_env *env)
680{
681 return env->scratched_regs || env->scratched_stack_slots;
682}
683
684static void mark_verifier_state_clean(struct bpf_verifier_env *env)
685{
686 env->scratched_regs = 0U;
343e5375 687 env->scratched_stack_slots = 0ULL;
0f55f9ed
CL
688}
689
690/* Used for printing the entire verifier state. */
691static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
692{
693 env->scratched_regs = ~0U;
343e5375 694 env->scratched_stack_slots = ~0ULL;
0f55f9ed
CL
695}
696
97e03f52
JK
697static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
698{
699 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
700 case DYNPTR_TYPE_LOCAL:
701 return BPF_DYNPTR_TYPE_LOCAL;
bc34dee6
JK
702 case DYNPTR_TYPE_RINGBUF:
703 return BPF_DYNPTR_TYPE_RINGBUF;
97e03f52
JK
704 default:
705 return BPF_DYNPTR_TYPE_INVALID;
706 }
707}
708
bc34dee6
JK
709static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
710{
711 return type == BPF_DYNPTR_TYPE_RINGBUF;
712}
713
97e03f52
JK
714static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
715 enum bpf_arg_type arg_type, int insn_idx)
716{
717 struct bpf_func_state *state = func(env, reg);
718 enum bpf_dynptr_type type;
bc34dee6 719 int spi, i, id;
97e03f52
JK
720
721 spi = get_spi(reg->off);
722
723 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
724 return -EINVAL;
725
726 for (i = 0; i < BPF_REG_SIZE; i++) {
727 state->stack[spi].slot_type[i] = STACK_DYNPTR;
728 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
729 }
730
731 type = arg_to_dynptr_type(arg_type);
732 if (type == BPF_DYNPTR_TYPE_INVALID)
733 return -EINVAL;
734
735 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
736 state->stack[spi].spilled_ptr.dynptr.type = type;
737 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
738
bc34dee6
JK
739 if (dynptr_type_refcounted(type)) {
740 /* The id is used to track proper releasing */
741 id = acquire_reference_state(env, insn_idx);
742 if (id < 0)
743 return id;
744
745 state->stack[spi].spilled_ptr.id = id;
746 state->stack[spi - 1].spilled_ptr.id = id;
747 }
748
97e03f52
JK
749 return 0;
750}
751
752static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
753{
754 struct bpf_func_state *state = func(env, reg);
755 int spi, i;
756
757 spi = get_spi(reg->off);
758
759 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
760 return -EINVAL;
761
762 for (i = 0; i < BPF_REG_SIZE; i++) {
763 state->stack[spi].slot_type[i] = STACK_INVALID;
764 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
765 }
766
bc34dee6
JK
767 /* Invalidate any slices associated with this dynptr */
768 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
769 release_reference(env, state->stack[spi].spilled_ptr.id);
770 state->stack[spi].spilled_ptr.id = 0;
771 state->stack[spi - 1].spilled_ptr.id = 0;
772 }
773
97e03f52
JK
774 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
775 state->stack[spi].spilled_ptr.dynptr.type = 0;
776 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
777
778 return 0;
779}
780
781static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
782{
783 struct bpf_func_state *state = func(env, reg);
784 int spi = get_spi(reg->off);
785 int i;
786
787 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
788 return true;
789
790 for (i = 0; i < BPF_REG_SIZE; i++) {
791 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
792 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
793 return false;
794 }
795
796 return true;
797}
798
b8d31762
RS
799bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
800 struct bpf_reg_state *reg)
97e03f52
JK
801{
802 struct bpf_func_state *state = func(env, reg);
803 int spi = get_spi(reg->off);
804 int i;
805
806 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
807 !state->stack[spi].spilled_ptr.dynptr.first_slot)
808 return false;
809
810 for (i = 0; i < BPF_REG_SIZE; i++) {
811 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
812 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
813 return false;
814 }
815
e9e315b4
RS
816 return true;
817}
818
b8d31762
RS
819bool is_dynptr_type_expected(struct bpf_verifier_env *env,
820 struct bpf_reg_state *reg,
821 enum bpf_arg_type arg_type)
e9e315b4
RS
822{
823 struct bpf_func_state *state = func(env, reg);
824 enum bpf_dynptr_type dynptr_type;
825 int spi = get_spi(reg->off);
826
97e03f52
JK
827 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
828 if (arg_type == ARG_PTR_TO_DYNPTR)
829 return true;
830
e9e315b4
RS
831 dynptr_type = arg_to_dynptr_type(arg_type);
832
833 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
97e03f52
JK
834}
835
27113c59
MKL
836/* The reg state of a pointer or a bounded scalar was saved when
837 * it was spilled to the stack.
838 */
839static bool is_spilled_reg(const struct bpf_stack_state *stack)
840{
841 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
842}
843
354e8f19
MKL
844static void scrub_spilled_slot(u8 *stype)
845{
846 if (*stype != STACK_INVALID)
847 *stype = STACK_MISC;
848}
849
61bd5218 850static void print_verifier_state(struct bpf_verifier_env *env,
0f55f9ed
CL
851 const struct bpf_func_state *state,
852 bool print_all)
17a52670 853{
f4d7e40a 854 const struct bpf_reg_state *reg;
17a52670
AS
855 enum bpf_reg_type t;
856 int i;
857
f4d7e40a
AS
858 if (state->frameno)
859 verbose(env, " frame%d:", state->frameno);
17a52670 860 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
861 reg = &state->regs[i];
862 t = reg->type;
17a52670
AS
863 if (t == NOT_INIT)
864 continue;
0f55f9ed
CL
865 if (!print_all && !reg_scratched(env, i))
866 continue;
4e92024a
AS
867 verbose(env, " R%d", i);
868 print_liveness(env, reg->live);
7df5072c 869 verbose(env, "=");
b5dc0163
AS
870 if (t == SCALAR_VALUE && reg->precise)
871 verbose(env, "P");
f1174f77
EC
872 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
873 tnum_is_const(reg->var_off)) {
874 /* reg->off should be 0 for SCALAR_VALUE */
7df5072c 875 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
61bd5218 876 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 877 } else {
7df5072c
ML
878 const char *sep = "";
879
880 verbose(env, "%s", reg_type_str(env, t));
5844101a 881 if (base_type(t) == PTR_TO_BTF_ID)
22dc4a0f 882 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
7df5072c
ML
883 verbose(env, "(");
884/*
885 * _a stands for append, was shortened to avoid multiline statements below.
886 * This macro is used to output a comma separated list of attributes.
887 */
888#define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
889
890 if (reg->id)
891 verbose_a("id=%d", reg->id);
a28ace78 892 if (reg->ref_obj_id)
7df5072c 893 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
f1174f77 894 if (t != SCALAR_VALUE)
7df5072c 895 verbose_a("off=%d", reg->off);
de8f3a83 896 if (type_is_pkt_pointer(t))
7df5072c 897 verbose_a("r=%d", reg->range);
c25b2ae1
HL
898 else if (base_type(t) == CONST_PTR_TO_MAP ||
899 base_type(t) == PTR_TO_MAP_KEY ||
900 base_type(t) == PTR_TO_MAP_VALUE)
7df5072c
ML
901 verbose_a("ks=%d,vs=%d",
902 reg->map_ptr->key_size,
903 reg->map_ptr->value_size);
7d1238f2
EC
904 if (tnum_is_const(reg->var_off)) {
905 /* Typically an immediate SCALAR_VALUE, but
906 * could be a pointer whose offset is too big
907 * for reg->off
908 */
7df5072c 909 verbose_a("imm=%llx", reg->var_off.value);
7d1238f2
EC
910 } else {
911 if (reg->smin_value != reg->umin_value &&
912 reg->smin_value != S64_MIN)
7df5072c 913 verbose_a("smin=%lld", (long long)reg->smin_value);
7d1238f2
EC
914 if (reg->smax_value != reg->umax_value &&
915 reg->smax_value != S64_MAX)
7df5072c 916 verbose_a("smax=%lld", (long long)reg->smax_value);
7d1238f2 917 if (reg->umin_value != 0)
7df5072c 918 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
7d1238f2 919 if (reg->umax_value != U64_MAX)
7df5072c 920 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
7d1238f2
EC
921 if (!tnum_is_unknown(reg->var_off)) {
922 char tn_buf[48];
f1174f77 923
7d1238f2 924 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7df5072c 925 verbose_a("var_off=%s", tn_buf);
7d1238f2 926 }
3f50f132
JF
927 if (reg->s32_min_value != reg->smin_value &&
928 reg->s32_min_value != S32_MIN)
7df5072c 929 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
3f50f132
JF
930 if (reg->s32_max_value != reg->smax_value &&
931 reg->s32_max_value != S32_MAX)
7df5072c 932 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
3f50f132
JF
933 if (reg->u32_min_value != reg->umin_value &&
934 reg->u32_min_value != U32_MIN)
7df5072c 935 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
3f50f132
JF
936 if (reg->u32_max_value != reg->umax_value &&
937 reg->u32_max_value != U32_MAX)
7df5072c 938 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
f1174f77 939 }
7df5072c
ML
940#undef verbose_a
941
61bd5218 942 verbose(env, ")");
f1174f77 943 }
17a52670 944 }
638f5b90 945 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
946 char types_buf[BPF_REG_SIZE + 1];
947 bool valid = false;
948 int j;
949
950 for (j = 0; j < BPF_REG_SIZE; j++) {
951 if (state->stack[i].slot_type[j] != STACK_INVALID)
952 valid = true;
953 types_buf[j] = slot_type_char[
954 state->stack[i].slot_type[j]];
955 }
956 types_buf[BPF_REG_SIZE] = 0;
957 if (!valid)
958 continue;
0f55f9ed
CL
959 if (!print_all && !stack_slot_scratched(env, i))
960 continue;
8efea21d
EC
961 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
962 print_liveness(env, state->stack[i].spilled_ptr.live);
27113c59 963 if (is_spilled_reg(&state->stack[i])) {
b5dc0163
AS
964 reg = &state->stack[i].spilled_ptr;
965 t = reg->type;
7df5072c 966 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
b5dc0163
AS
967 if (t == SCALAR_VALUE && reg->precise)
968 verbose(env, "P");
969 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
970 verbose(env, "%lld", reg->var_off.value + reg->off);
971 } else {
8efea21d 972 verbose(env, "=%s", types_buf);
b5dc0163 973 }
17a52670 974 }
fd978bf7
JS
975 if (state->acquired_refs && state->refs[0].id) {
976 verbose(env, " refs=%d", state->refs[0].id);
977 for (i = 1; i < state->acquired_refs; i++)
978 if (state->refs[i].id)
979 verbose(env, ",%d", state->refs[i].id);
980 }
bfc6bb74
AS
981 if (state->in_callback_fn)
982 verbose(env, " cb");
983 if (state->in_async_callback_fn)
984 verbose(env, " async_cb");
61bd5218 985 verbose(env, "\n");
0f55f9ed 986 mark_verifier_state_clean(env);
17a52670
AS
987}
988
2e576648
CL
989static inline u32 vlog_alignment(u32 pos)
990{
991 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
992 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
993}
994
995static void print_insn_state(struct bpf_verifier_env *env,
996 const struct bpf_func_state *state)
997{
998 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
999 /* remove new line character */
1000 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
1001 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
1002 } else {
1003 verbose(env, "%d:", env->insn_idx);
1004 }
1005 print_verifier_state(env, state, false);
17a52670
AS
1006}
1007
c69431aa
LB
1008/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1009 * small to hold src. This is different from krealloc since we don't want to preserve
1010 * the contents of dst.
1011 *
1012 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1013 * not be allocated.
638f5b90 1014 */
c69431aa 1015static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 1016{
c69431aa
LB
1017 size_t bytes;
1018
1019 if (ZERO_OR_NULL_PTR(src))
1020 goto out;
1021
1022 if (unlikely(check_mul_overflow(n, size, &bytes)))
1023 return NULL;
1024
ceb35b66 1025 if (ksize(dst) < ksize(src)) {
c69431aa 1026 kfree(dst);
ceb35b66 1027 dst = kmalloc_track_caller(kmalloc_size_roundup(bytes), flags);
c69431aa
LB
1028 if (!dst)
1029 return NULL;
1030 }
1031
1032 memcpy(dst, src, bytes);
1033out:
1034 return dst ? dst : ZERO_SIZE_PTR;
1035}
1036
1037/* resize an array from old_n items to new_n items. the array is reallocated if it's too
1038 * small to hold new_n items. new items are zeroed out if the array grows.
1039 *
1040 * Contrary to krealloc_array, does not free arr if new_n is zero.
1041 */
1042static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1043{
ceb35b66 1044 size_t alloc_size;
42378a9c
KC
1045 void *new_arr;
1046
c69431aa
LB
1047 if (!new_n || old_n == new_n)
1048 goto out;
1049
ceb35b66
KC
1050 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1051 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
42378a9c
KC
1052 if (!new_arr) {
1053 kfree(arr);
c69431aa 1054 return NULL;
42378a9c
KC
1055 }
1056 arr = new_arr;
c69431aa
LB
1057
1058 if (new_n > old_n)
1059 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1060
1061out:
1062 return arr ? arr : ZERO_SIZE_PTR;
1063}
1064
1065static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1066{
1067 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1068 sizeof(struct bpf_reference_state), GFP_KERNEL);
1069 if (!dst->refs)
1070 return -ENOMEM;
1071
1072 dst->acquired_refs = src->acquired_refs;
1073 return 0;
1074}
1075
1076static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1077{
1078 size_t n = src->allocated_stack / BPF_REG_SIZE;
1079
1080 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1081 GFP_KERNEL);
1082 if (!dst->stack)
1083 return -ENOMEM;
1084
1085 dst->allocated_stack = src->allocated_stack;
1086 return 0;
1087}
1088
1089static int resize_reference_state(struct bpf_func_state *state, size_t n)
1090{
1091 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1092 sizeof(struct bpf_reference_state));
1093 if (!state->refs)
1094 return -ENOMEM;
1095
1096 state->acquired_refs = n;
1097 return 0;
1098}
1099
1100static int grow_stack_state(struct bpf_func_state *state, int size)
1101{
1102 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1103
1104 if (old_n >= n)
1105 return 0;
1106
1107 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1108 if (!state->stack)
1109 return -ENOMEM;
1110
1111 state->allocated_stack = size;
1112 return 0;
fd978bf7
JS
1113}
1114
1115/* Acquire a pointer id from the env and update the state->refs to include
1116 * this new pointer reference.
1117 * On success, returns a valid pointer id to associate with the register
1118 * On failure, returns a negative errno.
638f5b90 1119 */
fd978bf7 1120static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 1121{
fd978bf7
JS
1122 struct bpf_func_state *state = cur_func(env);
1123 int new_ofs = state->acquired_refs;
1124 int id, err;
1125
c69431aa 1126 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
1127 if (err)
1128 return err;
1129 id = ++env->id_gen;
1130 state->refs[new_ofs].id = id;
1131 state->refs[new_ofs].insn_idx = insn_idx;
9d9d00ac 1132 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
638f5b90 1133
fd978bf7
JS
1134 return id;
1135}
1136
1137/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 1138static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
1139{
1140 int i, last_idx;
1141
fd978bf7
JS
1142 last_idx = state->acquired_refs - 1;
1143 for (i = 0; i < state->acquired_refs; i++) {
1144 if (state->refs[i].id == ptr_id) {
9d9d00ac
KKD
1145 /* Cannot release caller references in callbacks */
1146 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1147 return -EINVAL;
fd978bf7
JS
1148 if (last_idx && i != last_idx)
1149 memcpy(&state->refs[i], &state->refs[last_idx],
1150 sizeof(*state->refs));
1151 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1152 state->acquired_refs--;
638f5b90 1153 return 0;
638f5b90 1154 }
638f5b90 1155 }
46f8bc92 1156 return -EINVAL;
fd978bf7
JS
1157}
1158
f4d7e40a
AS
1159static void free_func_state(struct bpf_func_state *state)
1160{
5896351e
AS
1161 if (!state)
1162 return;
fd978bf7 1163 kfree(state->refs);
f4d7e40a
AS
1164 kfree(state->stack);
1165 kfree(state);
1166}
1167
b5dc0163
AS
1168static void clear_jmp_history(struct bpf_verifier_state *state)
1169{
1170 kfree(state->jmp_history);
1171 state->jmp_history = NULL;
1172 state->jmp_history_cnt = 0;
1173}
1174
1969db47
AS
1175static void free_verifier_state(struct bpf_verifier_state *state,
1176 bool free_self)
638f5b90 1177{
f4d7e40a
AS
1178 int i;
1179
1180 for (i = 0; i <= state->curframe; i++) {
1181 free_func_state(state->frame[i]);
1182 state->frame[i] = NULL;
1183 }
b5dc0163 1184 clear_jmp_history(state);
1969db47
AS
1185 if (free_self)
1186 kfree(state);
638f5b90
AS
1187}
1188
1189/* copy verifier state from src to dst growing dst stack space
1190 * when necessary to accommodate larger src stack
1191 */
f4d7e40a
AS
1192static int copy_func_state(struct bpf_func_state *dst,
1193 const struct bpf_func_state *src)
638f5b90
AS
1194{
1195 int err;
1196
fd978bf7
JS
1197 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1198 err = copy_reference_state(dst, src);
638f5b90
AS
1199 if (err)
1200 return err;
638f5b90
AS
1201 return copy_stack_state(dst, src);
1202}
1203
f4d7e40a
AS
1204static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1205 const struct bpf_verifier_state *src)
1206{
1207 struct bpf_func_state *dst;
1208 int i, err;
1209
06ab6a50
LB
1210 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1211 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1212 GFP_USER);
1213 if (!dst_state->jmp_history)
1214 return -ENOMEM;
b5dc0163
AS
1215 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1216
f4d7e40a
AS
1217 /* if dst has more stack frames then src frame, free them */
1218 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1219 free_func_state(dst_state->frame[i]);
1220 dst_state->frame[i] = NULL;
1221 }
979d63d5 1222 dst_state->speculative = src->speculative;
f4d7e40a 1223 dst_state->curframe = src->curframe;
d0d78c1d
KKD
1224 dst_state->active_lock.ptr = src->active_lock.ptr;
1225 dst_state->active_lock.id = src->active_lock.id;
2589726d
AS
1226 dst_state->branches = src->branches;
1227 dst_state->parent = src->parent;
b5dc0163
AS
1228 dst_state->first_insn_idx = src->first_insn_idx;
1229 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
1230 for (i = 0; i <= src->curframe; i++) {
1231 dst = dst_state->frame[i];
1232 if (!dst) {
1233 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1234 if (!dst)
1235 return -ENOMEM;
1236 dst_state->frame[i] = dst;
1237 }
1238 err = copy_func_state(dst, src->frame[i]);
1239 if (err)
1240 return err;
1241 }
1242 return 0;
1243}
1244
2589726d
AS
1245static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1246{
1247 while (st) {
1248 u32 br = --st->branches;
1249
1250 /* WARN_ON(br > 1) technically makes sense here,
1251 * but see comment in push_stack(), hence:
1252 */
1253 WARN_ONCE((int)br < 0,
1254 "BUG update_branch_counts:branches_to_explore=%d\n",
1255 br);
1256 if (br)
1257 break;
1258 st = st->parent;
1259 }
1260}
1261
638f5b90 1262static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 1263 int *insn_idx, bool pop_log)
638f5b90
AS
1264{
1265 struct bpf_verifier_state *cur = env->cur_state;
1266 struct bpf_verifier_stack_elem *elem, *head = env->head;
1267 int err;
17a52670
AS
1268
1269 if (env->head == NULL)
638f5b90 1270 return -ENOENT;
17a52670 1271
638f5b90
AS
1272 if (cur) {
1273 err = copy_verifier_state(cur, &head->st);
1274 if (err)
1275 return err;
1276 }
6f8a57cc
AN
1277 if (pop_log)
1278 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
1279 if (insn_idx)
1280 *insn_idx = head->insn_idx;
17a52670 1281 if (prev_insn_idx)
638f5b90
AS
1282 *prev_insn_idx = head->prev_insn_idx;
1283 elem = head->next;
1969db47 1284 free_verifier_state(&head->st, false);
638f5b90 1285 kfree(head);
17a52670
AS
1286 env->head = elem;
1287 env->stack_size--;
638f5b90 1288 return 0;
17a52670
AS
1289}
1290
58e2af8b 1291static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1292 int insn_idx, int prev_insn_idx,
1293 bool speculative)
17a52670 1294{
638f5b90 1295 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1296 struct bpf_verifier_stack_elem *elem;
638f5b90 1297 int err;
17a52670 1298
638f5b90 1299 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1300 if (!elem)
1301 goto err;
1302
17a52670
AS
1303 elem->insn_idx = insn_idx;
1304 elem->prev_insn_idx = prev_insn_idx;
1305 elem->next = env->head;
6f8a57cc 1306 elem->log_pos = env->log.len_used;
17a52670
AS
1307 env->head = elem;
1308 env->stack_size++;
1969db47
AS
1309 err = copy_verifier_state(&elem->st, cur);
1310 if (err)
1311 goto err;
979d63d5 1312 elem->st.speculative |= speculative;
b285fcb7
AS
1313 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1314 verbose(env, "The sequence of %d jumps is too complex.\n",
1315 env->stack_size);
17a52670
AS
1316 goto err;
1317 }
2589726d
AS
1318 if (elem->st.parent) {
1319 ++elem->st.parent->branches;
1320 /* WARN_ON(branches > 2) technically makes sense here,
1321 * but
1322 * 1. speculative states will bump 'branches' for non-branch
1323 * instructions
1324 * 2. is_state_visited() heuristics may decide not to create
1325 * a new state for a sequence of branches and all such current
1326 * and cloned states will be pointing to a single parent state
1327 * which might have large 'branches' count.
1328 */
1329 }
17a52670
AS
1330 return &elem->st;
1331err:
5896351e
AS
1332 free_verifier_state(env->cur_state, true);
1333 env->cur_state = NULL;
17a52670 1334 /* pop all elements and return */
6f8a57cc 1335 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1336 return NULL;
1337}
1338
1339#define CALLER_SAVED_REGS 6
1340static const int caller_saved[CALLER_SAVED_REGS] = {
1341 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1342};
1343
f54c7898
DB
1344static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1345 struct bpf_reg_state *reg);
f1174f77 1346
e688c3db
AS
1347/* This helper doesn't clear reg->id */
1348static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1349{
b03c9f9f
EC
1350 reg->var_off = tnum_const(imm);
1351 reg->smin_value = (s64)imm;
1352 reg->smax_value = (s64)imm;
1353 reg->umin_value = imm;
1354 reg->umax_value = imm;
3f50f132
JF
1355
1356 reg->s32_min_value = (s32)imm;
1357 reg->s32_max_value = (s32)imm;
1358 reg->u32_min_value = (u32)imm;
1359 reg->u32_max_value = (u32)imm;
1360}
1361
e688c3db
AS
1362/* Mark the unknown part of a register (variable offset or scalar value) as
1363 * known to have the value @imm.
1364 */
1365static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1366{
1367 /* Clear id, off, and union(map_ptr, range) */
1368 memset(((u8 *)reg) + sizeof(reg->type), 0,
1369 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1370 ___mark_reg_known(reg, imm);
1371}
1372
3f50f132
JF
1373static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1374{
1375 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1376 reg->s32_min_value = (s32)imm;
1377 reg->s32_max_value = (s32)imm;
1378 reg->u32_min_value = (u32)imm;
1379 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1380}
1381
f1174f77
EC
1382/* Mark the 'variable offset' part of a register as zero. This should be
1383 * used only on registers holding a pointer type.
1384 */
1385static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1386{
b03c9f9f 1387 __mark_reg_known(reg, 0);
f1174f77 1388}
a9789ef9 1389
cc2b14d5
AS
1390static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1391{
1392 __mark_reg_known(reg, 0);
cc2b14d5
AS
1393 reg->type = SCALAR_VALUE;
1394}
1395
61bd5218
JK
1396static void mark_reg_known_zero(struct bpf_verifier_env *env,
1397 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1398{
1399 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1400 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1401 /* Something bad happened, let's kill all regs */
1402 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1403 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1404 return;
1405 }
1406 __mark_reg_known_zero(regs + regno);
1407}
1408
4ddb7416
DB
1409static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1410{
c25b2ae1 1411 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
4ddb7416
DB
1412 const struct bpf_map *map = reg->map_ptr;
1413
1414 if (map->inner_map_meta) {
1415 reg->type = CONST_PTR_TO_MAP;
1416 reg->map_ptr = map->inner_map_meta;
3e8ce298
AS
1417 /* transfer reg's id which is unique for every map_lookup_elem
1418 * as UID of the inner map.
1419 */
db559117 1420 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
34d11a44 1421 reg->map_uid = reg->id;
4ddb7416
DB
1422 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1423 reg->type = PTR_TO_XDP_SOCK;
1424 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1425 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1426 reg->type = PTR_TO_SOCKET;
1427 } else {
1428 reg->type = PTR_TO_MAP_VALUE;
1429 }
c25b2ae1 1430 return;
4ddb7416 1431 }
c25b2ae1
HL
1432
1433 reg->type &= ~PTR_MAYBE_NULL;
4ddb7416
DB
1434}
1435
de8f3a83
DB
1436static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1437{
1438 return type_is_pkt_pointer(reg->type);
1439}
1440
1441static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1442{
1443 return reg_is_pkt_pointer(reg) ||
1444 reg->type == PTR_TO_PACKET_END;
1445}
1446
1447/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1448static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1449 enum bpf_reg_type which)
1450{
1451 /* The register can already have a range from prior markings.
1452 * This is fine as long as it hasn't been advanced from its
1453 * origin.
1454 */
1455 return reg->type == which &&
1456 reg->id == 0 &&
1457 reg->off == 0 &&
1458 tnum_equals_const(reg->var_off, 0);
1459}
1460
3f50f132
JF
1461/* Reset the min/max bounds of a register */
1462static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1463{
1464 reg->smin_value = S64_MIN;
1465 reg->smax_value = S64_MAX;
1466 reg->umin_value = 0;
1467 reg->umax_value = U64_MAX;
1468
1469 reg->s32_min_value = S32_MIN;
1470 reg->s32_max_value = S32_MAX;
1471 reg->u32_min_value = 0;
1472 reg->u32_max_value = U32_MAX;
1473}
1474
1475static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1476{
1477 reg->smin_value = S64_MIN;
1478 reg->smax_value = S64_MAX;
1479 reg->umin_value = 0;
1480 reg->umax_value = U64_MAX;
1481}
1482
1483static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1484{
1485 reg->s32_min_value = S32_MIN;
1486 reg->s32_max_value = S32_MAX;
1487 reg->u32_min_value = 0;
1488 reg->u32_max_value = U32_MAX;
1489}
1490
1491static void __update_reg32_bounds(struct bpf_reg_state *reg)
1492{
1493 struct tnum var32_off = tnum_subreg(reg->var_off);
1494
1495 /* min signed is max(sign bit) | min(other bits) */
1496 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1497 var32_off.value | (var32_off.mask & S32_MIN));
1498 /* max signed is min(sign bit) | max(other bits) */
1499 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1500 var32_off.value | (var32_off.mask & S32_MAX));
1501 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1502 reg->u32_max_value = min(reg->u32_max_value,
1503 (u32)(var32_off.value | var32_off.mask));
1504}
1505
1506static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1507{
1508 /* min signed is max(sign bit) | min(other bits) */
1509 reg->smin_value = max_t(s64, reg->smin_value,
1510 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1511 /* max signed is min(sign bit) | max(other bits) */
1512 reg->smax_value = min_t(s64, reg->smax_value,
1513 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1514 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1515 reg->umax_value = min(reg->umax_value,
1516 reg->var_off.value | reg->var_off.mask);
1517}
1518
3f50f132
JF
1519static void __update_reg_bounds(struct bpf_reg_state *reg)
1520{
1521 __update_reg32_bounds(reg);
1522 __update_reg64_bounds(reg);
1523}
1524
b03c9f9f 1525/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1526static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1527{
1528 /* Learn sign from signed bounds.
1529 * If we cannot cross the sign boundary, then signed and unsigned bounds
1530 * are the same, so combine. This works even in the negative case, e.g.
1531 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1532 */
1533 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1534 reg->s32_min_value = reg->u32_min_value =
1535 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1536 reg->s32_max_value = reg->u32_max_value =
1537 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1538 return;
1539 }
1540 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1541 * boundary, so we must be careful.
1542 */
1543 if ((s32)reg->u32_max_value >= 0) {
1544 /* Positive. We can't learn anything from the smin, but smax
1545 * is positive, hence safe.
1546 */
1547 reg->s32_min_value = reg->u32_min_value;
1548 reg->s32_max_value = reg->u32_max_value =
1549 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1550 } else if ((s32)reg->u32_min_value < 0) {
1551 /* Negative. We can't learn anything from the smax, but smin
1552 * is negative, hence safe.
1553 */
1554 reg->s32_min_value = reg->u32_min_value =
1555 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1556 reg->s32_max_value = reg->u32_max_value;
1557 }
1558}
1559
1560static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1561{
1562 /* Learn sign from signed bounds.
1563 * If we cannot cross the sign boundary, then signed and unsigned bounds
1564 * are the same, so combine. This works even in the negative case, e.g.
1565 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1566 */
1567 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1568 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1569 reg->umin_value);
1570 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1571 reg->umax_value);
1572 return;
1573 }
1574 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1575 * boundary, so we must be careful.
1576 */
1577 if ((s64)reg->umax_value >= 0) {
1578 /* Positive. We can't learn anything from the smin, but smax
1579 * is positive, hence safe.
1580 */
1581 reg->smin_value = reg->umin_value;
1582 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1583 reg->umax_value);
1584 } else if ((s64)reg->umin_value < 0) {
1585 /* Negative. We can't learn anything from the smax, but smin
1586 * is negative, hence safe.
1587 */
1588 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1589 reg->umin_value);
1590 reg->smax_value = reg->umax_value;
1591 }
1592}
1593
3f50f132
JF
1594static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1595{
1596 __reg32_deduce_bounds(reg);
1597 __reg64_deduce_bounds(reg);
1598}
1599
b03c9f9f
EC
1600/* Attempts to improve var_off based on unsigned min/max information */
1601static void __reg_bound_offset(struct bpf_reg_state *reg)
1602{
3f50f132
JF
1603 struct tnum var64_off = tnum_intersect(reg->var_off,
1604 tnum_range(reg->umin_value,
1605 reg->umax_value));
1606 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1607 tnum_range(reg->u32_min_value,
1608 reg->u32_max_value));
1609
1610 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1611}
1612
3844d153
DB
1613static void reg_bounds_sync(struct bpf_reg_state *reg)
1614{
1615 /* We might have learned new bounds from the var_off. */
1616 __update_reg_bounds(reg);
1617 /* We might have learned something about the sign bit. */
1618 __reg_deduce_bounds(reg);
1619 /* We might have learned some bits from the bounds. */
1620 __reg_bound_offset(reg);
1621 /* Intersecting with the old var_off might have improved our bounds
1622 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1623 * then new var_off is (0; 0x7f...fc) which improves our umax.
1624 */
1625 __update_reg_bounds(reg);
1626}
1627
e572ff80
DB
1628static bool __reg32_bound_s64(s32 a)
1629{
1630 return a >= 0 && a <= S32_MAX;
1631}
1632
3f50f132 1633static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1634{
3f50f132
JF
1635 reg->umin_value = reg->u32_min_value;
1636 reg->umax_value = reg->u32_max_value;
e572ff80
DB
1637
1638 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1639 * be positive otherwise set to worse case bounds and refine later
1640 * from tnum.
3f50f132 1641 */
e572ff80
DB
1642 if (__reg32_bound_s64(reg->s32_min_value) &&
1643 __reg32_bound_s64(reg->s32_max_value)) {
3a71dc36 1644 reg->smin_value = reg->s32_min_value;
e572ff80
DB
1645 reg->smax_value = reg->s32_max_value;
1646 } else {
3a71dc36 1647 reg->smin_value = 0;
e572ff80
DB
1648 reg->smax_value = U32_MAX;
1649 }
3f50f132
JF
1650}
1651
1652static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1653{
1654 /* special case when 64-bit register has upper 32-bit register
1655 * zeroed. Typically happens after zext or <<32, >>32 sequence
1656 * allowing us to use 32-bit bounds directly,
1657 */
1658 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1659 __reg_assign_32_into_64(reg);
1660 } else {
1661 /* Otherwise the best we can do is push lower 32bit known and
1662 * unknown bits into register (var_off set from jmp logic)
1663 * then learn as much as possible from the 64-bit tnum
1664 * known and unknown bits. The previous smin/smax bounds are
1665 * invalid here because of jmp32 compare so mark them unknown
1666 * so they do not impact tnum bounds calculation.
1667 */
1668 __mark_reg64_unbounded(reg);
3f50f132 1669 }
3844d153 1670 reg_bounds_sync(reg);
3f50f132
JF
1671}
1672
1673static bool __reg64_bound_s32(s64 a)
1674{
388e2c0b 1675 return a >= S32_MIN && a <= S32_MAX;
3f50f132
JF
1676}
1677
1678static bool __reg64_bound_u32(u64 a)
1679{
b9979db8 1680 return a >= U32_MIN && a <= U32_MAX;
3f50f132
JF
1681}
1682
1683static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1684{
1685 __mark_reg32_unbounded(reg);
b0270958 1686 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1687 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1688 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1689 }
10bf4e83 1690 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 1691 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 1692 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 1693 }
3844d153 1694 reg_bounds_sync(reg);
b03c9f9f
EC
1695}
1696
f1174f77 1697/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1698static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1699 struct bpf_reg_state *reg)
f1174f77 1700{
a9c676bc
AS
1701 /*
1702 * Clear type, id, off, and union(map_ptr, range) and
1703 * padding between 'type' and union
1704 */
1705 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1706 reg->type = SCALAR_VALUE;
f1174f77 1707 reg->var_off = tnum_unknown;
f4d7e40a 1708 reg->frameno = 0;
be2ef816 1709 reg->precise = !env->bpf_capable;
b03c9f9f 1710 __mark_reg_unbounded(reg);
f1174f77
EC
1711}
1712
61bd5218
JK
1713static void mark_reg_unknown(struct bpf_verifier_env *env,
1714 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1715{
1716 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1717 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1718 /* Something bad happened, let's kill all regs except FP */
1719 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1720 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1721 return;
1722 }
f54c7898 1723 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1724}
1725
f54c7898
DB
1726static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1727 struct bpf_reg_state *reg)
f1174f77 1728{
f54c7898 1729 __mark_reg_unknown(env, reg);
f1174f77
EC
1730 reg->type = NOT_INIT;
1731}
1732
61bd5218
JK
1733static void mark_reg_not_init(struct bpf_verifier_env *env,
1734 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1735{
1736 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1737 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1738 /* Something bad happened, let's kill all regs except FP */
1739 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1740 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1741 return;
1742 }
f54c7898 1743 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1744}
1745
41c48f3a
AI
1746static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1747 struct bpf_reg_state *regs, u32 regno,
22dc4a0f 1748 enum bpf_reg_type reg_type,
c6f1bfe8
YS
1749 struct btf *btf, u32 btf_id,
1750 enum bpf_type_flag flag)
41c48f3a
AI
1751{
1752 if (reg_type == SCALAR_VALUE) {
1753 mark_reg_unknown(env, regs, regno);
1754 return;
1755 }
1756 mark_reg_known_zero(env, regs, regno);
c6f1bfe8 1757 regs[regno].type = PTR_TO_BTF_ID | flag;
22dc4a0f 1758 regs[regno].btf = btf;
41c48f3a
AI
1759 regs[regno].btf_id = btf_id;
1760}
1761
5327ed3d 1762#define DEF_NOT_SUBREG (0)
61bd5218 1763static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1764 struct bpf_func_state *state)
17a52670 1765{
f4d7e40a 1766 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1767 int i;
1768
dc503a8a 1769 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1770 mark_reg_not_init(env, regs, i);
dc503a8a 1771 regs[i].live = REG_LIVE_NONE;
679c782d 1772 regs[i].parent = NULL;
5327ed3d 1773 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1774 }
17a52670
AS
1775
1776 /* frame pointer */
f1174f77 1777 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1778 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1779 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1780}
1781
f4d7e40a
AS
1782#define BPF_MAIN_FUNC (-1)
1783static void init_func_state(struct bpf_verifier_env *env,
1784 struct bpf_func_state *state,
1785 int callsite, int frameno, int subprogno)
1786{
1787 state->callsite = callsite;
1788 state->frameno = frameno;
1789 state->subprogno = subprogno;
1bfe26fb 1790 state->callback_ret_range = tnum_range(0, 0);
f4d7e40a 1791 init_reg_state(env, state);
0f55f9ed 1792 mark_verifier_state_scratched(env);
f4d7e40a
AS
1793}
1794
bfc6bb74
AS
1795/* Similar to push_stack(), but for async callbacks */
1796static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1797 int insn_idx, int prev_insn_idx,
1798 int subprog)
1799{
1800 struct bpf_verifier_stack_elem *elem;
1801 struct bpf_func_state *frame;
1802
1803 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1804 if (!elem)
1805 goto err;
1806
1807 elem->insn_idx = insn_idx;
1808 elem->prev_insn_idx = prev_insn_idx;
1809 elem->next = env->head;
1810 elem->log_pos = env->log.len_used;
1811 env->head = elem;
1812 env->stack_size++;
1813 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1814 verbose(env,
1815 "The sequence of %d jumps is too complex for async cb.\n",
1816 env->stack_size);
1817 goto err;
1818 }
1819 /* Unlike push_stack() do not copy_verifier_state().
1820 * The caller state doesn't matter.
1821 * This is async callback. It starts in a fresh stack.
1822 * Initialize it similar to do_check_common().
1823 */
1824 elem->st.branches = 1;
1825 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1826 if (!frame)
1827 goto err;
1828 init_func_state(env, frame,
1829 BPF_MAIN_FUNC /* callsite */,
1830 0 /* frameno within this callchain */,
1831 subprog /* subprog number within this prog */);
1832 elem->st.frame[0] = frame;
1833 return &elem->st;
1834err:
1835 free_verifier_state(env->cur_state, true);
1836 env->cur_state = NULL;
1837 /* pop all elements and return */
1838 while (!pop_stack(env, NULL, NULL, false));
1839 return NULL;
1840}
1841
1842
17a52670
AS
1843enum reg_arg_type {
1844 SRC_OP, /* register is used as source operand */
1845 DST_OP, /* register is used as destination operand */
1846 DST_OP_NO_MARK /* same as above, check only, don't mark */
1847};
1848
cc8b0b92
AS
1849static int cmp_subprogs(const void *a, const void *b)
1850{
9c8105bd
JW
1851 return ((struct bpf_subprog_info *)a)->start -
1852 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1853}
1854
1855static int find_subprog(struct bpf_verifier_env *env, int off)
1856{
9c8105bd 1857 struct bpf_subprog_info *p;
cc8b0b92 1858
9c8105bd
JW
1859 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1860 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1861 if (!p)
1862 return -ENOENT;
9c8105bd 1863 return p - env->subprog_info;
cc8b0b92
AS
1864
1865}
1866
1867static int add_subprog(struct bpf_verifier_env *env, int off)
1868{
1869 int insn_cnt = env->prog->len;
1870 int ret;
1871
1872 if (off >= insn_cnt || off < 0) {
1873 verbose(env, "call to invalid destination\n");
1874 return -EINVAL;
1875 }
1876 ret = find_subprog(env, off);
1877 if (ret >= 0)
282a0f46 1878 return ret;
4cb3d99c 1879 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1880 verbose(env, "too many subprograms\n");
1881 return -E2BIG;
1882 }
e6ac2450 1883 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
1884 env->subprog_info[env->subprog_cnt++].start = off;
1885 sort(env->subprog_info, env->subprog_cnt,
1886 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1887 return env->subprog_cnt - 1;
cc8b0b92
AS
1888}
1889
2357672c
KKD
1890#define MAX_KFUNC_DESCS 256
1891#define MAX_KFUNC_BTFS 256
1892
e6ac2450
MKL
1893struct bpf_kfunc_desc {
1894 struct btf_func_model func_model;
1895 u32 func_id;
1896 s32 imm;
2357672c
KKD
1897 u16 offset;
1898};
1899
1900struct bpf_kfunc_btf {
1901 struct btf *btf;
1902 struct module *module;
1903 u16 offset;
e6ac2450
MKL
1904};
1905
e6ac2450
MKL
1906struct bpf_kfunc_desc_tab {
1907 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1908 u32 nr_descs;
1909};
1910
2357672c
KKD
1911struct bpf_kfunc_btf_tab {
1912 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1913 u32 nr_descs;
1914};
1915
1916static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
e6ac2450
MKL
1917{
1918 const struct bpf_kfunc_desc *d0 = a;
1919 const struct bpf_kfunc_desc *d1 = b;
1920
1921 /* func_id is not greater than BTF_MAX_TYPE */
2357672c
KKD
1922 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1923}
1924
1925static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1926{
1927 const struct bpf_kfunc_btf *d0 = a;
1928 const struct bpf_kfunc_btf *d1 = b;
1929
1930 return d0->offset - d1->offset;
e6ac2450
MKL
1931}
1932
1933static const struct bpf_kfunc_desc *
2357672c 1934find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
e6ac2450
MKL
1935{
1936 struct bpf_kfunc_desc desc = {
1937 .func_id = func_id,
2357672c 1938 .offset = offset,
e6ac2450
MKL
1939 };
1940 struct bpf_kfunc_desc_tab *tab;
1941
1942 tab = prog->aux->kfunc_tab;
1943 return bsearch(&desc, tab->descs, tab->nr_descs,
2357672c
KKD
1944 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1945}
1946
1947static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
b202d844 1948 s16 offset)
2357672c
KKD
1949{
1950 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1951 struct bpf_kfunc_btf_tab *tab;
1952 struct bpf_kfunc_btf *b;
1953 struct module *mod;
1954 struct btf *btf;
1955 int btf_fd;
1956
1957 tab = env->prog->aux->kfunc_btf_tab;
1958 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1959 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1960 if (!b) {
1961 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1962 verbose(env, "too many different module BTFs\n");
1963 return ERR_PTR(-E2BIG);
1964 }
1965
1966 if (bpfptr_is_null(env->fd_array)) {
1967 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1968 return ERR_PTR(-EPROTO);
1969 }
1970
1971 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1972 offset * sizeof(btf_fd),
1973 sizeof(btf_fd)))
1974 return ERR_PTR(-EFAULT);
1975
1976 btf = btf_get_by_fd(btf_fd);
588cd7ef
KKD
1977 if (IS_ERR(btf)) {
1978 verbose(env, "invalid module BTF fd specified\n");
2357672c 1979 return btf;
588cd7ef 1980 }
2357672c
KKD
1981
1982 if (!btf_is_module(btf)) {
1983 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1984 btf_put(btf);
1985 return ERR_PTR(-EINVAL);
1986 }
1987
1988 mod = btf_try_get_module(btf);
1989 if (!mod) {
1990 btf_put(btf);
1991 return ERR_PTR(-ENXIO);
1992 }
1993
1994 b = &tab->descs[tab->nr_descs++];
1995 b->btf = btf;
1996 b->module = mod;
1997 b->offset = offset;
1998
1999 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2000 kfunc_btf_cmp_by_off, NULL);
2001 }
2357672c 2002 return b->btf;
e6ac2450
MKL
2003}
2004
2357672c
KKD
2005void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2006{
2007 if (!tab)
2008 return;
2009
2010 while (tab->nr_descs--) {
2011 module_put(tab->descs[tab->nr_descs].module);
2012 btf_put(tab->descs[tab->nr_descs].btf);
2013 }
2014 kfree(tab);
2015}
2016
43bf0878 2017static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2357672c 2018{
2357672c
KKD
2019 if (offset) {
2020 if (offset < 0) {
2021 /* In the future, this can be allowed to increase limit
2022 * of fd index into fd_array, interpreted as u16.
2023 */
2024 verbose(env, "negative offset disallowed for kernel module function call\n");
2025 return ERR_PTR(-EINVAL);
2026 }
2027
b202d844 2028 return __find_kfunc_desc_btf(env, offset);
2357672c
KKD
2029 }
2030 return btf_vmlinux ?: ERR_PTR(-ENOENT);
e6ac2450
MKL
2031}
2032
2357672c 2033static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
e6ac2450
MKL
2034{
2035 const struct btf_type *func, *func_proto;
2357672c 2036 struct bpf_kfunc_btf_tab *btf_tab;
e6ac2450
MKL
2037 struct bpf_kfunc_desc_tab *tab;
2038 struct bpf_prog_aux *prog_aux;
2039 struct bpf_kfunc_desc *desc;
2040 const char *func_name;
2357672c 2041 struct btf *desc_btf;
8cbf062a 2042 unsigned long call_imm;
e6ac2450
MKL
2043 unsigned long addr;
2044 int err;
2045
2046 prog_aux = env->prog->aux;
2047 tab = prog_aux->kfunc_tab;
2357672c 2048 btf_tab = prog_aux->kfunc_btf_tab;
e6ac2450
MKL
2049 if (!tab) {
2050 if (!btf_vmlinux) {
2051 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2052 return -ENOTSUPP;
2053 }
2054
2055 if (!env->prog->jit_requested) {
2056 verbose(env, "JIT is required for calling kernel function\n");
2057 return -ENOTSUPP;
2058 }
2059
2060 if (!bpf_jit_supports_kfunc_call()) {
2061 verbose(env, "JIT does not support calling kernel function\n");
2062 return -ENOTSUPP;
2063 }
2064
2065 if (!env->prog->gpl_compatible) {
2066 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2067 return -EINVAL;
2068 }
2069
2070 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2071 if (!tab)
2072 return -ENOMEM;
2073 prog_aux->kfunc_tab = tab;
2074 }
2075
a5d82727
KKD
2076 /* func_id == 0 is always invalid, but instead of returning an error, be
2077 * conservative and wait until the code elimination pass before returning
2078 * error, so that invalid calls that get pruned out can be in BPF programs
2079 * loaded from userspace. It is also required that offset be untouched
2080 * for such calls.
2081 */
2082 if (!func_id && !offset)
2083 return 0;
2084
2357672c
KKD
2085 if (!btf_tab && offset) {
2086 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2087 if (!btf_tab)
2088 return -ENOMEM;
2089 prog_aux->kfunc_btf_tab = btf_tab;
2090 }
2091
43bf0878 2092 desc_btf = find_kfunc_desc_btf(env, offset);
2357672c
KKD
2093 if (IS_ERR(desc_btf)) {
2094 verbose(env, "failed to find BTF for kernel function\n");
2095 return PTR_ERR(desc_btf);
2096 }
2097
2098 if (find_kfunc_desc(env->prog, func_id, offset))
e6ac2450
MKL
2099 return 0;
2100
2101 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2102 verbose(env, "too many different kernel function calls\n");
2103 return -E2BIG;
2104 }
2105
2357672c 2106 func = btf_type_by_id(desc_btf, func_id);
e6ac2450
MKL
2107 if (!func || !btf_type_is_func(func)) {
2108 verbose(env, "kernel btf_id %u is not a function\n",
2109 func_id);
2110 return -EINVAL;
2111 }
2357672c 2112 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450
MKL
2113 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2114 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2115 func_id);
2116 return -EINVAL;
2117 }
2118
2357672c 2119 func_name = btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
2120 addr = kallsyms_lookup_name(func_name);
2121 if (!addr) {
2122 verbose(env, "cannot find address for kernel function %s\n",
2123 func_name);
2124 return -EINVAL;
2125 }
2126
8cbf062a
HT
2127 call_imm = BPF_CALL_IMM(addr);
2128 /* Check whether or not the relative offset overflows desc->imm */
2129 if ((unsigned long)(s32)call_imm != call_imm) {
2130 verbose(env, "address of kernel function %s is out of range\n",
2131 func_name);
2132 return -EINVAL;
2133 }
2134
e6ac2450
MKL
2135 desc = &tab->descs[tab->nr_descs++];
2136 desc->func_id = func_id;
8cbf062a 2137 desc->imm = call_imm;
2357672c
KKD
2138 desc->offset = offset;
2139 err = btf_distill_func_proto(&env->log, desc_btf,
e6ac2450
MKL
2140 func_proto, func_name,
2141 &desc->func_model);
2142 if (!err)
2143 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2357672c 2144 kfunc_desc_cmp_by_id_off, NULL);
e6ac2450
MKL
2145 return err;
2146}
2147
2148static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2149{
2150 const struct bpf_kfunc_desc *d0 = a;
2151 const struct bpf_kfunc_desc *d1 = b;
2152
2153 if (d0->imm > d1->imm)
2154 return 1;
2155 else if (d0->imm < d1->imm)
2156 return -1;
2157 return 0;
2158}
2159
2160static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2161{
2162 struct bpf_kfunc_desc_tab *tab;
2163
2164 tab = prog->aux->kfunc_tab;
2165 if (!tab)
2166 return;
2167
2168 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2169 kfunc_desc_cmp_by_imm, NULL);
2170}
2171
2172bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2173{
2174 return !!prog->aux->kfunc_tab;
2175}
2176
2177const struct btf_func_model *
2178bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2179 const struct bpf_insn *insn)
2180{
2181 const struct bpf_kfunc_desc desc = {
2182 .imm = insn->imm,
2183 };
2184 const struct bpf_kfunc_desc *res;
2185 struct bpf_kfunc_desc_tab *tab;
2186
2187 tab = prog->aux->kfunc_tab;
2188 res = bsearch(&desc, tab->descs, tab->nr_descs,
2189 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2190
2191 return res ? &res->func_model : NULL;
2192}
2193
2194static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 2195{
9c8105bd 2196 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 2197 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 2198 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 2199
f910cefa
JW
2200 /* Add entry function. */
2201 ret = add_subprog(env, 0);
e6ac2450 2202 if (ret)
f910cefa
JW
2203 return ret;
2204
e6ac2450
MKL
2205 for (i = 0; i < insn_cnt; i++, insn++) {
2206 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2207 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 2208 continue;
e6ac2450 2209
2c78ee89 2210 if (!env->bpf_capable) {
e6ac2450 2211 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
2212 return -EPERM;
2213 }
e6ac2450 2214
3990ed4c 2215 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
e6ac2450 2216 ret = add_subprog(env, i + insn->imm + 1);
3990ed4c 2217 else
2357672c 2218 ret = add_kfunc_call(env, insn->imm, insn->off);
e6ac2450 2219
cc8b0b92
AS
2220 if (ret < 0)
2221 return ret;
2222 }
2223
4cb3d99c
JW
2224 /* Add a fake 'exit' subprog which could simplify subprog iteration
2225 * logic. 'subprog_cnt' should not be increased.
2226 */
2227 subprog[env->subprog_cnt].start = insn_cnt;
2228
06ee7115 2229 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 2230 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 2231 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 2232
e6ac2450
MKL
2233 return 0;
2234}
2235
2236static int check_subprogs(struct bpf_verifier_env *env)
2237{
2238 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2239 struct bpf_subprog_info *subprog = env->subprog_info;
2240 struct bpf_insn *insn = env->prog->insnsi;
2241 int insn_cnt = env->prog->len;
2242
cc8b0b92 2243 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
2244 subprog_start = subprog[cur_subprog].start;
2245 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2246 for (i = 0; i < insn_cnt; i++) {
2247 u8 code = insn[i].code;
2248
7f6e4312
MF
2249 if (code == (BPF_JMP | BPF_CALL) &&
2250 insn[i].imm == BPF_FUNC_tail_call &&
2251 insn[i].src_reg != BPF_PSEUDO_CALL)
2252 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
2253 if (BPF_CLASS(code) == BPF_LD &&
2254 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2255 subprog[cur_subprog].has_ld_abs = true;
092ed096 2256 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
2257 goto next;
2258 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2259 goto next;
2260 off = i + insn[i].off + 1;
2261 if (off < subprog_start || off >= subprog_end) {
2262 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2263 return -EINVAL;
2264 }
2265next:
2266 if (i == subprog_end - 1) {
2267 /* to avoid fall-through from one subprog into another
2268 * the last insn of the subprog should be either exit
2269 * or unconditional jump back
2270 */
2271 if (code != (BPF_JMP | BPF_EXIT) &&
2272 code != (BPF_JMP | BPF_JA)) {
2273 verbose(env, "last insn is not an exit or jmp\n");
2274 return -EINVAL;
2275 }
2276 subprog_start = subprog_end;
4cb3d99c
JW
2277 cur_subprog++;
2278 if (cur_subprog < env->subprog_cnt)
9c8105bd 2279 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
2280 }
2281 }
2282 return 0;
2283}
2284
679c782d
EC
2285/* Parentage chain of this register (or stack slot) should take care of all
2286 * issues like callee-saved registers, stack slot allocation time, etc.
2287 */
f4d7e40a 2288static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 2289 const struct bpf_reg_state *state,
5327ed3d 2290 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
2291{
2292 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 2293 int cnt = 0;
dc503a8a
EC
2294
2295 while (parent) {
2296 /* if read wasn't screened by an earlier write ... */
679c782d 2297 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 2298 break;
9242b5f5
AS
2299 if (parent->live & REG_LIVE_DONE) {
2300 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
c25b2ae1 2301 reg_type_str(env, parent->type),
9242b5f5
AS
2302 parent->var_off.value, parent->off);
2303 return -EFAULT;
2304 }
5327ed3d
JW
2305 /* The first condition is more likely to be true than the
2306 * second, checked it first.
2307 */
2308 if ((parent->live & REG_LIVE_READ) == flag ||
2309 parent->live & REG_LIVE_READ64)
25af32da
AS
2310 /* The parentage chain never changes and
2311 * this parent was already marked as LIVE_READ.
2312 * There is no need to keep walking the chain again and
2313 * keep re-marking all parents as LIVE_READ.
2314 * This case happens when the same register is read
2315 * multiple times without writes into it in-between.
5327ed3d
JW
2316 * Also, if parent has the stronger REG_LIVE_READ64 set,
2317 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
2318 */
2319 break;
dc503a8a 2320 /* ... then we depend on parent's value */
5327ed3d
JW
2321 parent->live |= flag;
2322 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2323 if (flag == REG_LIVE_READ64)
2324 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
2325 state = parent;
2326 parent = state->parent;
f4d7e40a 2327 writes = true;
06ee7115 2328 cnt++;
dc503a8a 2329 }
06ee7115
AS
2330
2331 if (env->longest_mark_read_walk < cnt)
2332 env->longest_mark_read_walk = cnt;
f4d7e40a 2333 return 0;
dc503a8a
EC
2334}
2335
5327ed3d
JW
2336/* This function is supposed to be used by the following 32-bit optimization
2337 * code only. It returns TRUE if the source or destination register operates
2338 * on 64-bit, otherwise return FALSE.
2339 */
2340static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2341 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2342{
2343 u8 code, class, op;
2344
2345 code = insn->code;
2346 class = BPF_CLASS(code);
2347 op = BPF_OP(code);
2348 if (class == BPF_JMP) {
2349 /* BPF_EXIT for "main" will reach here. Return TRUE
2350 * conservatively.
2351 */
2352 if (op == BPF_EXIT)
2353 return true;
2354 if (op == BPF_CALL) {
2355 /* BPF to BPF call will reach here because of marking
2356 * caller saved clobber with DST_OP_NO_MARK for which we
2357 * don't care the register def because they are anyway
2358 * marked as NOT_INIT already.
2359 */
2360 if (insn->src_reg == BPF_PSEUDO_CALL)
2361 return false;
2362 /* Helper call will reach here because of arg type
2363 * check, conservatively return TRUE.
2364 */
2365 if (t == SRC_OP)
2366 return true;
2367
2368 return false;
2369 }
2370 }
2371
2372 if (class == BPF_ALU64 || class == BPF_JMP ||
2373 /* BPF_END always use BPF_ALU class. */
2374 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2375 return true;
2376
2377 if (class == BPF_ALU || class == BPF_JMP32)
2378 return false;
2379
2380 if (class == BPF_LDX) {
2381 if (t != SRC_OP)
2382 return BPF_SIZE(code) == BPF_DW;
2383 /* LDX source must be ptr. */
2384 return true;
2385 }
2386
2387 if (class == BPF_STX) {
83a28819
IL
2388 /* BPF_STX (including atomic variants) has multiple source
2389 * operands, one of which is a ptr. Check whether the caller is
2390 * asking about it.
2391 */
2392 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
2393 return true;
2394 return BPF_SIZE(code) == BPF_DW;
2395 }
2396
2397 if (class == BPF_LD) {
2398 u8 mode = BPF_MODE(code);
2399
2400 /* LD_IMM64 */
2401 if (mode == BPF_IMM)
2402 return true;
2403
2404 /* Both LD_IND and LD_ABS return 32-bit data. */
2405 if (t != SRC_OP)
2406 return false;
2407
2408 /* Implicit ctx ptr. */
2409 if (regno == BPF_REG_6)
2410 return true;
2411
2412 /* Explicit source could be any width. */
2413 return true;
2414 }
2415
2416 if (class == BPF_ST)
2417 /* The only source register for BPF_ST is a ptr. */
2418 return true;
2419
2420 /* Conservatively return true at default. */
2421 return true;
2422}
2423
83a28819
IL
2424/* Return the regno defined by the insn, or -1. */
2425static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 2426{
83a28819
IL
2427 switch (BPF_CLASS(insn->code)) {
2428 case BPF_JMP:
2429 case BPF_JMP32:
2430 case BPF_ST:
2431 return -1;
2432 case BPF_STX:
2433 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2434 (insn->imm & BPF_FETCH)) {
2435 if (insn->imm == BPF_CMPXCHG)
2436 return BPF_REG_0;
2437 else
2438 return insn->src_reg;
2439 } else {
2440 return -1;
2441 }
2442 default:
2443 return insn->dst_reg;
2444 }
b325fbca
JW
2445}
2446
2447/* Return TRUE if INSN has defined any 32-bit value explicitly. */
2448static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2449{
83a28819
IL
2450 int dst_reg = insn_def_regno(insn);
2451
2452 if (dst_reg == -1)
b325fbca
JW
2453 return false;
2454
83a28819 2455 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
2456}
2457
5327ed3d
JW
2458static void mark_insn_zext(struct bpf_verifier_env *env,
2459 struct bpf_reg_state *reg)
2460{
2461 s32 def_idx = reg->subreg_def;
2462
2463 if (def_idx == DEF_NOT_SUBREG)
2464 return;
2465
2466 env->insn_aux_data[def_idx - 1].zext_dst = true;
2467 /* The dst will be zero extended, so won't be sub-register anymore. */
2468 reg->subreg_def = DEF_NOT_SUBREG;
2469}
2470
dc503a8a 2471static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
2472 enum reg_arg_type t)
2473{
f4d7e40a
AS
2474 struct bpf_verifier_state *vstate = env->cur_state;
2475 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 2476 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 2477 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 2478 bool rw64;
dc503a8a 2479
17a52670 2480 if (regno >= MAX_BPF_REG) {
61bd5218 2481 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
2482 return -EINVAL;
2483 }
2484
0f55f9ed
CL
2485 mark_reg_scratched(env, regno);
2486
c342dc10 2487 reg = &regs[regno];
5327ed3d 2488 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
2489 if (t == SRC_OP) {
2490 /* check whether register used as source operand can be read */
c342dc10 2491 if (reg->type == NOT_INIT) {
61bd5218 2492 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
2493 return -EACCES;
2494 }
679c782d 2495 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
2496 if (regno == BPF_REG_FP)
2497 return 0;
2498
5327ed3d
JW
2499 if (rw64)
2500 mark_insn_zext(env, reg);
2501
2502 return mark_reg_read(env, reg, reg->parent,
2503 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
2504 } else {
2505 /* check whether register used as dest operand can be written to */
2506 if (regno == BPF_REG_FP) {
61bd5218 2507 verbose(env, "frame pointer is read only\n");
17a52670
AS
2508 return -EACCES;
2509 }
c342dc10 2510 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 2511 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 2512 if (t == DST_OP)
61bd5218 2513 mark_reg_unknown(env, regs, regno);
17a52670
AS
2514 }
2515 return 0;
2516}
2517
b5dc0163
AS
2518/* for any branch, call, exit record the history of jmps in the given state */
2519static int push_jmp_history(struct bpf_verifier_env *env,
2520 struct bpf_verifier_state *cur)
2521{
2522 u32 cnt = cur->jmp_history_cnt;
2523 struct bpf_idx_pair *p;
ceb35b66 2524 size_t alloc_size;
b5dc0163
AS
2525
2526 cnt++;
ceb35b66
KC
2527 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2528 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
b5dc0163
AS
2529 if (!p)
2530 return -ENOMEM;
2531 p[cnt - 1].idx = env->insn_idx;
2532 p[cnt - 1].prev_idx = env->prev_insn_idx;
2533 cur->jmp_history = p;
2534 cur->jmp_history_cnt = cnt;
2535 return 0;
2536}
2537
2538/* Backtrack one insn at a time. If idx is not at the top of recorded
2539 * history then previous instruction came from straight line execution.
2540 */
2541static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2542 u32 *history)
2543{
2544 u32 cnt = *history;
2545
2546 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2547 i = st->jmp_history[cnt - 1].prev_idx;
2548 (*history)--;
2549 } else {
2550 i--;
2551 }
2552 return i;
2553}
2554
e6ac2450
MKL
2555static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2556{
2557 const struct btf_type *func;
2357672c 2558 struct btf *desc_btf;
e6ac2450
MKL
2559
2560 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2561 return NULL;
2562
43bf0878 2563 desc_btf = find_kfunc_desc_btf(data, insn->off);
2357672c
KKD
2564 if (IS_ERR(desc_btf))
2565 return "<error>";
2566
2567 func = btf_type_by_id(desc_btf, insn->imm);
2568 return btf_name_by_offset(desc_btf, func->name_off);
e6ac2450
MKL
2569}
2570
b5dc0163
AS
2571/* For given verifier state backtrack_insn() is called from the last insn to
2572 * the first insn. Its purpose is to compute a bitmask of registers and
2573 * stack slots that needs precision in the parent verifier state.
2574 */
2575static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2576 u32 *reg_mask, u64 *stack_mask)
2577{
2578 const struct bpf_insn_cbs cbs = {
e6ac2450 2579 .cb_call = disasm_kfunc_name,
b5dc0163
AS
2580 .cb_print = verbose,
2581 .private_data = env,
2582 };
2583 struct bpf_insn *insn = env->prog->insnsi + idx;
2584 u8 class = BPF_CLASS(insn->code);
2585 u8 opcode = BPF_OP(insn->code);
2586 u8 mode = BPF_MODE(insn->code);
2587 u32 dreg = 1u << insn->dst_reg;
2588 u32 sreg = 1u << insn->src_reg;
2589 u32 spi;
2590
2591 if (insn->code == 0)
2592 return 0;
496f3324 2593 if (env->log.level & BPF_LOG_LEVEL2) {
b5dc0163
AS
2594 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2595 verbose(env, "%d: ", idx);
2596 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2597 }
2598
2599 if (class == BPF_ALU || class == BPF_ALU64) {
2600 if (!(*reg_mask & dreg))
2601 return 0;
2602 if (opcode == BPF_MOV) {
2603 if (BPF_SRC(insn->code) == BPF_X) {
2604 /* dreg = sreg
2605 * dreg needs precision after this insn
2606 * sreg needs precision before this insn
2607 */
2608 *reg_mask &= ~dreg;
2609 *reg_mask |= sreg;
2610 } else {
2611 /* dreg = K
2612 * dreg needs precision after this insn.
2613 * Corresponding register is already marked
2614 * as precise=true in this verifier state.
2615 * No further markings in parent are necessary
2616 */
2617 *reg_mask &= ~dreg;
2618 }
2619 } else {
2620 if (BPF_SRC(insn->code) == BPF_X) {
2621 /* dreg += sreg
2622 * both dreg and sreg need precision
2623 * before this insn
2624 */
2625 *reg_mask |= sreg;
2626 } /* else dreg += K
2627 * dreg still needs precision before this insn
2628 */
2629 }
2630 } else if (class == BPF_LDX) {
2631 if (!(*reg_mask & dreg))
2632 return 0;
2633 *reg_mask &= ~dreg;
2634
2635 /* scalars can only be spilled into stack w/o losing precision.
2636 * Load from any other memory can be zero extended.
2637 * The desire to keep that precision is already indicated
2638 * by 'precise' mark in corresponding register of this state.
2639 * No further tracking necessary.
2640 */
2641 if (insn->src_reg != BPF_REG_FP)
2642 return 0;
b5dc0163
AS
2643
2644 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2645 * that [fp - off] slot contains scalar that needs to be
2646 * tracked with precision
2647 */
2648 spi = (-insn->off - 1) / BPF_REG_SIZE;
2649 if (spi >= 64) {
2650 verbose(env, "BUG spi %d\n", spi);
2651 WARN_ONCE(1, "verifier backtracking bug");
2652 return -EFAULT;
2653 }
2654 *stack_mask |= 1ull << spi;
b3b50f05 2655 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2656 if (*reg_mask & dreg)
b3b50f05 2657 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2658 * to access memory. It means backtracking
2659 * encountered a case of pointer subtraction.
2660 */
2661 return -ENOTSUPP;
2662 /* scalars can only be spilled into stack */
2663 if (insn->dst_reg != BPF_REG_FP)
2664 return 0;
b5dc0163
AS
2665 spi = (-insn->off - 1) / BPF_REG_SIZE;
2666 if (spi >= 64) {
2667 verbose(env, "BUG spi %d\n", spi);
2668 WARN_ONCE(1, "verifier backtracking bug");
2669 return -EFAULT;
2670 }
2671 if (!(*stack_mask & (1ull << spi)))
2672 return 0;
2673 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2674 if (class == BPF_STX)
2675 *reg_mask |= sreg;
b5dc0163
AS
2676 } else if (class == BPF_JMP || class == BPF_JMP32) {
2677 if (opcode == BPF_CALL) {
2678 if (insn->src_reg == BPF_PSEUDO_CALL)
2679 return -ENOTSUPP;
be2ef816
AN
2680 /* BPF helpers that invoke callback subprogs are
2681 * equivalent to BPF_PSEUDO_CALL above
2682 */
2683 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2684 return -ENOTSUPP;
b5dc0163
AS
2685 /* regular helper call sets R0 */
2686 *reg_mask &= ~1;
2687 if (*reg_mask & 0x3f) {
2688 /* if backtracing was looking for registers R1-R5
2689 * they should have been found already.
2690 */
2691 verbose(env, "BUG regs %x\n", *reg_mask);
2692 WARN_ONCE(1, "verifier backtracking bug");
2693 return -EFAULT;
2694 }
2695 } else if (opcode == BPF_EXIT) {
2696 return -ENOTSUPP;
2697 }
2698 } else if (class == BPF_LD) {
2699 if (!(*reg_mask & dreg))
2700 return 0;
2701 *reg_mask &= ~dreg;
2702 /* It's ld_imm64 or ld_abs or ld_ind.
2703 * For ld_imm64 no further tracking of precision
2704 * into parent is necessary
2705 */
2706 if (mode == BPF_IND || mode == BPF_ABS)
2707 /* to be analyzed */
2708 return -ENOTSUPP;
b5dc0163
AS
2709 }
2710 return 0;
2711}
2712
2713/* the scalar precision tracking algorithm:
2714 * . at the start all registers have precise=false.
2715 * . scalar ranges are tracked as normal through alu and jmp insns.
2716 * . once precise value of the scalar register is used in:
2717 * . ptr + scalar alu
2718 * . if (scalar cond K|scalar)
2719 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2720 * backtrack through the verifier states and mark all registers and
2721 * stack slots with spilled constants that these scalar regisers
2722 * should be precise.
2723 * . during state pruning two registers (or spilled stack slots)
2724 * are equivalent if both are not precise.
2725 *
2726 * Note the verifier cannot simply walk register parentage chain,
2727 * since many different registers and stack slots could have been
2728 * used to compute single precise scalar.
2729 *
2730 * The approach of starting with precise=true for all registers and then
2731 * backtrack to mark a register as not precise when the verifier detects
2732 * that program doesn't care about specific value (e.g., when helper
2733 * takes register as ARG_ANYTHING parameter) is not safe.
2734 *
2735 * It's ok to walk single parentage chain of the verifier states.
2736 * It's possible that this backtracking will go all the way till 1st insn.
2737 * All other branches will be explored for needing precision later.
2738 *
2739 * The backtracking needs to deal with cases like:
2740 * 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)
2741 * r9 -= r8
2742 * r5 = r9
2743 * if r5 > 0x79f goto pc+7
2744 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2745 * r5 += 1
2746 * ...
2747 * call bpf_perf_event_output#25
2748 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2749 *
2750 * and this case:
2751 * r6 = 1
2752 * call foo // uses callee's r6 inside to compute r0
2753 * r0 += r6
2754 * if r0 == 0 goto
2755 *
2756 * to track above reg_mask/stack_mask needs to be independent for each frame.
2757 *
2758 * Also if parent's curframe > frame where backtracking started,
2759 * the verifier need to mark registers in both frames, otherwise callees
2760 * may incorrectly prune callers. This is similar to
2761 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2762 *
2763 * For now backtracking falls back into conservative marking.
2764 */
2765static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2766 struct bpf_verifier_state *st)
2767{
2768 struct bpf_func_state *func;
2769 struct bpf_reg_state *reg;
2770 int i, j;
2771
2772 /* big hammer: mark all scalars precise in this path.
2773 * pop_stack may still get !precise scalars.
f63181b6
AN
2774 * We also skip current state and go straight to first parent state,
2775 * because precision markings in current non-checkpointed state are
2776 * not needed. See why in the comment in __mark_chain_precision below.
b5dc0163 2777 */
f63181b6 2778 for (st = st->parent; st; st = st->parent) {
b5dc0163
AS
2779 for (i = 0; i <= st->curframe; i++) {
2780 func = st->frame[i];
2781 for (j = 0; j < BPF_REG_FP; j++) {
2782 reg = &func->regs[j];
2783 if (reg->type != SCALAR_VALUE)
2784 continue;
2785 reg->precise = true;
2786 }
2787 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
27113c59 2788 if (!is_spilled_reg(&func->stack[j]))
b5dc0163
AS
2789 continue;
2790 reg = &func->stack[j].spilled_ptr;
2791 if (reg->type != SCALAR_VALUE)
2792 continue;
2793 reg->precise = true;
2794 }
2795 }
f63181b6 2796 }
b5dc0163
AS
2797}
2798
7a830b53
AN
2799static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2800{
2801 struct bpf_func_state *func;
2802 struct bpf_reg_state *reg;
2803 int i, j;
2804
2805 for (i = 0; i <= st->curframe; i++) {
2806 func = st->frame[i];
2807 for (j = 0; j < BPF_REG_FP; j++) {
2808 reg = &func->regs[j];
2809 if (reg->type != SCALAR_VALUE)
2810 continue;
2811 reg->precise = false;
2812 }
2813 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2814 if (!is_spilled_reg(&func->stack[j]))
2815 continue;
2816 reg = &func->stack[j].spilled_ptr;
2817 if (reg->type != SCALAR_VALUE)
2818 continue;
2819 reg->precise = false;
2820 }
2821 }
2822}
2823
f63181b6
AN
2824/*
2825 * __mark_chain_precision() backtracks BPF program instruction sequence and
2826 * chain of verifier states making sure that register *regno* (if regno >= 0)
2827 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2828 * SCALARS, as well as any other registers and slots that contribute to
2829 * a tracked state of given registers/stack slots, depending on specific BPF
2830 * assembly instructions (see backtrack_insns() for exact instruction handling
2831 * logic). This backtracking relies on recorded jmp_history and is able to
2832 * traverse entire chain of parent states. This process ends only when all the
2833 * necessary registers/slots and their transitive dependencies are marked as
2834 * precise.
2835 *
2836 * One important and subtle aspect is that precise marks *do not matter* in
2837 * the currently verified state (current state). It is important to understand
2838 * why this is the case.
2839 *
2840 * First, note that current state is the state that is not yet "checkpointed",
2841 * i.e., it is not yet put into env->explored_states, and it has no children
2842 * states as well. It's ephemeral, and can end up either a) being discarded if
2843 * compatible explored state is found at some point or BPF_EXIT instruction is
2844 * reached or b) checkpointed and put into env->explored_states, branching out
2845 * into one or more children states.
2846 *
2847 * In the former case, precise markings in current state are completely
2848 * ignored by state comparison code (see regsafe() for details). Only
2849 * checkpointed ("old") state precise markings are important, and if old
2850 * state's register/slot is precise, regsafe() assumes current state's
2851 * register/slot as precise and checks value ranges exactly and precisely. If
2852 * states turn out to be compatible, current state's necessary precise
2853 * markings and any required parent states' precise markings are enforced
2854 * after the fact with propagate_precision() logic, after the fact. But it's
2855 * important to realize that in this case, even after marking current state
2856 * registers/slots as precise, we immediately discard current state. So what
2857 * actually matters is any of the precise markings propagated into current
2858 * state's parent states, which are always checkpointed (due to b) case above).
2859 * As such, for scenario a) it doesn't matter if current state has precise
2860 * markings set or not.
2861 *
2862 * Now, for the scenario b), checkpointing and forking into child(ren)
2863 * state(s). Note that before current state gets to checkpointing step, any
2864 * processed instruction always assumes precise SCALAR register/slot
2865 * knowledge: if precise value or range is useful to prune jump branch, BPF
2866 * verifier takes this opportunity enthusiastically. Similarly, when
2867 * register's value is used to calculate offset or memory address, exact
2868 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2869 * what we mentioned above about state comparison ignoring precise markings
2870 * during state comparison, BPF verifier ignores and also assumes precise
2871 * markings *at will* during instruction verification process. But as verifier
2872 * assumes precision, it also propagates any precision dependencies across
2873 * parent states, which are not yet finalized, so can be further restricted
2874 * based on new knowledge gained from restrictions enforced by their children
2875 * states. This is so that once those parent states are finalized, i.e., when
2876 * they have no more active children state, state comparison logic in
2877 * is_state_visited() would enforce strict and precise SCALAR ranges, if
2878 * required for correctness.
2879 *
2880 * To build a bit more intuition, note also that once a state is checkpointed,
2881 * the path we took to get to that state is not important. This is crucial
2882 * property for state pruning. When state is checkpointed and finalized at
2883 * some instruction index, it can be correctly and safely used to "short
2884 * circuit" any *compatible* state that reaches exactly the same instruction
2885 * index. I.e., if we jumped to that instruction from a completely different
2886 * code path than original finalized state was derived from, it doesn't
2887 * matter, current state can be discarded because from that instruction
2888 * forward having a compatible state will ensure we will safely reach the
2889 * exit. States describe preconditions for further exploration, but completely
2890 * forget the history of how we got here.
2891 *
2892 * This also means that even if we needed precise SCALAR range to get to
2893 * finalized state, but from that point forward *that same* SCALAR register is
2894 * never used in a precise context (i.e., it's precise value is not needed for
2895 * correctness), it's correct and safe to mark such register as "imprecise"
2896 * (i.e., precise marking set to false). This is what we rely on when we do
2897 * not set precise marking in current state. If no child state requires
2898 * precision for any given SCALAR register, it's safe to dictate that it can
2899 * be imprecise. If any child state does require this register to be precise,
2900 * we'll mark it precise later retroactively during precise markings
2901 * propagation from child state to parent states.
7a830b53
AN
2902 *
2903 * Skipping precise marking setting in current state is a mild version of
2904 * relying on the above observation. But we can utilize this property even
2905 * more aggressively by proactively forgetting any precise marking in the
2906 * current state (which we inherited from the parent state), right before we
2907 * checkpoint it and branch off into new child state. This is done by
2908 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2909 * finalized states which help in short circuiting more future states.
f63181b6 2910 */
529409ea 2911static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
a3ce685d 2912 int spi)
b5dc0163
AS
2913{
2914 struct bpf_verifier_state *st = env->cur_state;
2915 int first_idx = st->first_insn_idx;
2916 int last_idx = env->insn_idx;
2917 struct bpf_func_state *func;
2918 struct bpf_reg_state *reg;
a3ce685d
AS
2919 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2920 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2921 bool skip_first = true;
a3ce685d 2922 bool new_marks = false;
b5dc0163
AS
2923 int i, err;
2924
2c78ee89 2925 if (!env->bpf_capable)
b5dc0163
AS
2926 return 0;
2927
f63181b6
AN
2928 /* Do sanity checks against current state of register and/or stack
2929 * slot, but don't set precise flag in current state, as precision
2930 * tracking in the current state is unnecessary.
2931 */
529409ea 2932 func = st->frame[frame];
a3ce685d
AS
2933 if (regno >= 0) {
2934 reg = &func->regs[regno];
2935 if (reg->type != SCALAR_VALUE) {
2936 WARN_ONCE(1, "backtracing misuse");
2937 return -EFAULT;
2938 }
f63181b6 2939 new_marks = true;
b5dc0163 2940 }
b5dc0163 2941
a3ce685d 2942 while (spi >= 0) {
27113c59 2943 if (!is_spilled_reg(&func->stack[spi])) {
a3ce685d
AS
2944 stack_mask = 0;
2945 break;
2946 }
2947 reg = &func->stack[spi].spilled_ptr;
2948 if (reg->type != SCALAR_VALUE) {
2949 stack_mask = 0;
2950 break;
2951 }
f63181b6 2952 new_marks = true;
a3ce685d
AS
2953 break;
2954 }
2955
2956 if (!new_marks)
2957 return 0;
2958 if (!reg_mask && !stack_mask)
2959 return 0;
be2ef816 2960
b5dc0163
AS
2961 for (;;) {
2962 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2963 u32 history = st->jmp_history_cnt;
2964
496f3324 2965 if (env->log.level & BPF_LOG_LEVEL2)
b5dc0163 2966 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
be2ef816
AN
2967
2968 if (last_idx < 0) {
2969 /* we are at the entry into subprog, which
2970 * is expected for global funcs, but only if
2971 * requested precise registers are R1-R5
2972 * (which are global func's input arguments)
2973 */
2974 if (st->curframe == 0 &&
2975 st->frame[0]->subprogno > 0 &&
2976 st->frame[0]->callsite == BPF_MAIN_FUNC &&
2977 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2978 bitmap_from_u64(mask, reg_mask);
2979 for_each_set_bit(i, mask, 32) {
2980 reg = &st->frame[0]->regs[i];
2981 if (reg->type != SCALAR_VALUE) {
2982 reg_mask &= ~(1u << i);
2983 continue;
2984 }
2985 reg->precise = true;
2986 }
2987 return 0;
2988 }
2989
2990 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2991 st->frame[0]->subprogno, reg_mask, stack_mask);
2992 WARN_ONCE(1, "verifier backtracking bug");
2993 return -EFAULT;
2994 }
2995
b5dc0163
AS
2996 for (i = last_idx;;) {
2997 if (skip_first) {
2998 err = 0;
2999 skip_first = false;
3000 } else {
3001 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3002 }
3003 if (err == -ENOTSUPP) {
3004 mark_all_scalars_precise(env, st);
3005 return 0;
3006 } else if (err) {
3007 return err;
3008 }
3009 if (!reg_mask && !stack_mask)
3010 /* Found assignment(s) into tracked register in this state.
3011 * Since this state is already marked, just return.
3012 * Nothing to be tracked further in the parent state.
3013 */
3014 return 0;
3015 if (i == first_idx)
3016 break;
3017 i = get_prev_insn_idx(st, i, &history);
3018 if (i >= env->prog->len) {
3019 /* This can happen if backtracking reached insn 0
3020 * and there are still reg_mask or stack_mask
3021 * to backtrack.
3022 * It means the backtracking missed the spot where
3023 * particular register was initialized with a constant.
3024 */
3025 verbose(env, "BUG backtracking idx %d\n", i);
3026 WARN_ONCE(1, "verifier backtracking bug");
3027 return -EFAULT;
3028 }
3029 }
3030 st = st->parent;
3031 if (!st)
3032 break;
3033
a3ce685d 3034 new_marks = false;
529409ea 3035 func = st->frame[frame];
b5dc0163
AS
3036 bitmap_from_u64(mask, reg_mask);
3037 for_each_set_bit(i, mask, 32) {
3038 reg = &func->regs[i];
a3ce685d
AS
3039 if (reg->type != SCALAR_VALUE) {
3040 reg_mask &= ~(1u << i);
b5dc0163 3041 continue;
a3ce685d 3042 }
b5dc0163
AS
3043 if (!reg->precise)
3044 new_marks = true;
3045 reg->precise = true;
3046 }
3047
3048 bitmap_from_u64(mask, stack_mask);
3049 for_each_set_bit(i, mask, 64) {
3050 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
3051 /* the sequence of instructions:
3052 * 2: (bf) r3 = r10
3053 * 3: (7b) *(u64 *)(r3 -8) = r0
3054 * 4: (79) r4 = *(u64 *)(r10 -8)
3055 * doesn't contain jmps. It's backtracked
3056 * as a single block.
3057 * During backtracking insn 3 is not recognized as
3058 * stack access, so at the end of backtracking
3059 * stack slot fp-8 is still marked in stack_mask.
3060 * However the parent state may not have accessed
3061 * fp-8 and it's "unallocated" stack space.
3062 * In such case fallback to conservative.
b5dc0163 3063 */
2339cd6c
AS
3064 mark_all_scalars_precise(env, st);
3065 return 0;
b5dc0163
AS
3066 }
3067
27113c59 3068 if (!is_spilled_reg(&func->stack[i])) {
a3ce685d 3069 stack_mask &= ~(1ull << i);
b5dc0163 3070 continue;
a3ce685d 3071 }
b5dc0163 3072 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
3073 if (reg->type != SCALAR_VALUE) {
3074 stack_mask &= ~(1ull << i);
b5dc0163 3075 continue;
a3ce685d 3076 }
b5dc0163
AS
3077 if (!reg->precise)
3078 new_marks = true;
3079 reg->precise = true;
3080 }
496f3324 3081 if (env->log.level & BPF_LOG_LEVEL2) {
2e576648 3082 verbose(env, "parent %s regs=%x stack=%llx marks:",
b5dc0163
AS
3083 new_marks ? "didn't have" : "already had",
3084 reg_mask, stack_mask);
2e576648 3085 print_verifier_state(env, func, true);
b5dc0163
AS
3086 }
3087
a3ce685d
AS
3088 if (!reg_mask && !stack_mask)
3089 break;
b5dc0163
AS
3090 if (!new_marks)
3091 break;
3092
3093 last_idx = st->last_insn_idx;
3094 first_idx = st->first_insn_idx;
3095 }
3096 return 0;
3097}
3098
eb1f7f71 3099int mark_chain_precision(struct bpf_verifier_env *env, int regno)
a3ce685d 3100{
529409ea 3101 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
a3ce685d
AS
3102}
3103
529409ea 3104static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
a3ce685d 3105{
529409ea 3106 return __mark_chain_precision(env, frame, regno, -1);
a3ce685d
AS
3107}
3108
529409ea 3109static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
a3ce685d 3110{
529409ea 3111 return __mark_chain_precision(env, frame, -1, spi);
a3ce685d 3112}
b5dc0163 3113
1be7f75d
AS
3114static bool is_spillable_regtype(enum bpf_reg_type type)
3115{
c25b2ae1 3116 switch (base_type(type)) {
1be7f75d 3117 case PTR_TO_MAP_VALUE:
1be7f75d
AS
3118 case PTR_TO_STACK:
3119 case PTR_TO_CTX:
969bf05e 3120 case PTR_TO_PACKET:
de8f3a83 3121 case PTR_TO_PACKET_META:
969bf05e 3122 case PTR_TO_PACKET_END:
d58e468b 3123 case PTR_TO_FLOW_KEYS:
1be7f75d 3124 case CONST_PTR_TO_MAP:
c64b7983 3125 case PTR_TO_SOCKET:
46f8bc92 3126 case PTR_TO_SOCK_COMMON:
655a51e5 3127 case PTR_TO_TCP_SOCK:
fada7fdc 3128 case PTR_TO_XDP_SOCK:
65726b5b 3129 case PTR_TO_BTF_ID:
20b2aff4 3130 case PTR_TO_BUF:
744ea4e3 3131 case PTR_TO_MEM:
69c087ba
YS
3132 case PTR_TO_FUNC:
3133 case PTR_TO_MAP_KEY:
1be7f75d
AS
3134 return true;
3135 default:
3136 return false;
3137 }
3138}
3139
cc2b14d5
AS
3140/* Does this register contain a constant zero? */
3141static bool register_is_null(struct bpf_reg_state *reg)
3142{
3143 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3144}
3145
f7cf25b2
AS
3146static bool register_is_const(struct bpf_reg_state *reg)
3147{
3148 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3149}
3150
5689d49b
YS
3151static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3152{
3153 return tnum_is_unknown(reg->var_off) &&
3154 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3155 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3156 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3157 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3158}
3159
3160static bool register_is_bounded(struct bpf_reg_state *reg)
3161{
3162 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3163}
3164
6e7e63cb
JH
3165static bool __is_pointer_value(bool allow_ptr_leaks,
3166 const struct bpf_reg_state *reg)
3167{
3168 if (allow_ptr_leaks)
3169 return false;
3170
3171 return reg->type != SCALAR_VALUE;
3172}
3173
f7cf25b2 3174static void save_register_state(struct bpf_func_state *state,
354e8f19
MKL
3175 int spi, struct bpf_reg_state *reg,
3176 int size)
f7cf25b2
AS
3177{
3178 int i;
3179
3180 state->stack[spi].spilled_ptr = *reg;
354e8f19
MKL
3181 if (size == BPF_REG_SIZE)
3182 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
f7cf25b2 3183
354e8f19
MKL
3184 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3185 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
f7cf25b2 3186
354e8f19
MKL
3187 /* size < 8 bytes spill */
3188 for (; i; i--)
3189 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
f7cf25b2
AS
3190}
3191
01f810ac 3192/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
3193 * stack boundary and alignment are checked in check_mem_access()
3194 */
01f810ac
AM
3195static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3196 /* stack frame we're writing to */
3197 struct bpf_func_state *state,
3198 int off, int size, int value_regno,
3199 int insn_idx)
17a52670 3200{
f4d7e40a 3201 struct bpf_func_state *cur; /* state of the current function */
638f5b90 3202 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 3203 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 3204 struct bpf_reg_state *reg = NULL;
638f5b90 3205
c69431aa 3206 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
3207 if (err)
3208 return err;
9c399760
AS
3209 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3210 * so it's aligned access and [off, off + size) are within stack limits
3211 */
638f5b90
AS
3212 if (!env->allow_ptr_leaks &&
3213 state->stack[spi].slot_type[0] == STACK_SPILL &&
3214 size != BPF_REG_SIZE) {
3215 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3216 return -EACCES;
3217 }
17a52670 3218
f4d7e40a 3219 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
3220 if (value_regno >= 0)
3221 reg = &cur->regs[value_regno];
2039f26f
DB
3222 if (!env->bypass_spec_v4) {
3223 bool sanitize = reg && is_spillable_regtype(reg->type);
3224
3225 for (i = 0; i < size; i++) {
3226 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3227 sanitize = true;
3228 break;
3229 }
3230 }
3231
3232 if (sanitize)
3233 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3234 }
17a52670 3235
0f55f9ed 3236 mark_stack_slot_scratched(env, spi);
354e8f19 3237 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2c78ee89 3238 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
3239 if (dst_reg != BPF_REG_FP) {
3240 /* The backtracking logic can only recognize explicit
3241 * stack slot address like [fp - 8]. Other spill of
8fb33b60 3242 * scalar via different register has to be conservative.
b5dc0163
AS
3243 * Backtrack from here and mark all registers as precise
3244 * that contributed into 'reg' being a constant.
3245 */
3246 err = mark_chain_precision(env, value_regno);
3247 if (err)
3248 return err;
3249 }
354e8f19 3250 save_register_state(state, spi, reg, size);
f7cf25b2 3251 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 3252 /* register containing pointer is being spilled into stack */
9c399760 3253 if (size != BPF_REG_SIZE) {
f7cf25b2 3254 verbose_linfo(env, insn_idx, "; ");
61bd5218 3255 verbose(env, "invalid size of register spill\n");
17a52670
AS
3256 return -EACCES;
3257 }
f7cf25b2 3258 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
3259 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3260 return -EINVAL;
3261 }
354e8f19 3262 save_register_state(state, spi, reg, size);
9c399760 3263 } else {
cc2b14d5
AS
3264 u8 type = STACK_MISC;
3265
679c782d
EC
3266 /* regular write of data into stack destroys any spilled ptr */
3267 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d 3268 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
27113c59 3269 if (is_spilled_reg(&state->stack[spi]))
0bae2d4d 3270 for (i = 0; i < BPF_REG_SIZE; i++)
354e8f19 3271 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
9c399760 3272
cc2b14d5
AS
3273 /* only mark the slot as written if all 8 bytes were written
3274 * otherwise read propagation may incorrectly stop too soon
3275 * when stack slots are partially written.
3276 * This heuristic means that read propagation will be
3277 * conservative, since it will add reg_live_read marks
3278 * to stack slots all the way to first state when programs
3279 * writes+reads less than 8 bytes
3280 */
3281 if (size == BPF_REG_SIZE)
3282 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3283
3284 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
3285 if (reg && register_is_null(reg)) {
3286 /* backtracking doesn't work for STACK_ZERO yet. */
3287 err = mark_chain_precision(env, value_regno);
3288 if (err)
3289 return err;
cc2b14d5 3290 type = STACK_ZERO;
b5dc0163 3291 }
cc2b14d5 3292
0bae2d4d 3293 /* Mark slots affected by this stack write. */
9c399760 3294 for (i = 0; i < size; i++)
638f5b90 3295 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 3296 type;
17a52670
AS
3297 }
3298 return 0;
3299}
3300
01f810ac
AM
3301/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3302 * known to contain a variable offset.
3303 * This function checks whether the write is permitted and conservatively
3304 * tracks the effects of the write, considering that each stack slot in the
3305 * dynamic range is potentially written to.
3306 *
3307 * 'off' includes 'regno->off'.
3308 * 'value_regno' can be -1, meaning that an unknown value is being written to
3309 * the stack.
3310 *
3311 * Spilled pointers in range are not marked as written because we don't know
3312 * what's going to be actually written. This means that read propagation for
3313 * future reads cannot be terminated by this write.
3314 *
3315 * For privileged programs, uninitialized stack slots are considered
3316 * initialized by this write (even though we don't know exactly what offsets
3317 * are going to be written to). The idea is that we don't want the verifier to
3318 * reject future reads that access slots written to through variable offsets.
3319 */
3320static int check_stack_write_var_off(struct bpf_verifier_env *env,
3321 /* func where register points to */
3322 struct bpf_func_state *state,
3323 int ptr_regno, int off, int size,
3324 int value_regno, int insn_idx)
3325{
3326 struct bpf_func_state *cur; /* state of the current function */
3327 int min_off, max_off;
3328 int i, err;
3329 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3330 bool writing_zero = false;
3331 /* set if the fact that we're writing a zero is used to let any
3332 * stack slots remain STACK_ZERO
3333 */
3334 bool zero_used = false;
3335
3336 cur = env->cur_state->frame[env->cur_state->curframe];
3337 ptr_reg = &cur->regs[ptr_regno];
3338 min_off = ptr_reg->smin_value + off;
3339 max_off = ptr_reg->smax_value + off + size;
3340 if (value_regno >= 0)
3341 value_reg = &cur->regs[value_regno];
3342 if (value_reg && register_is_null(value_reg))
3343 writing_zero = true;
3344
c69431aa 3345 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
3346 if (err)
3347 return err;
3348
3349
3350 /* Variable offset writes destroy any spilled pointers in range. */
3351 for (i = min_off; i < max_off; i++) {
3352 u8 new_type, *stype;
3353 int slot, spi;
3354
3355 slot = -i - 1;
3356 spi = slot / BPF_REG_SIZE;
3357 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
0f55f9ed 3358 mark_stack_slot_scratched(env, spi);
01f810ac 3359
f5e477a8
KKD
3360 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3361 /* Reject the write if range we may write to has not
3362 * been initialized beforehand. If we didn't reject
3363 * here, the ptr status would be erased below (even
3364 * though not all slots are actually overwritten),
3365 * possibly opening the door to leaks.
3366 *
3367 * We do however catch STACK_INVALID case below, and
3368 * only allow reading possibly uninitialized memory
3369 * later for CAP_PERFMON, as the write may not happen to
3370 * that slot.
01f810ac
AM
3371 */
3372 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3373 insn_idx, i);
3374 return -EINVAL;
3375 }
3376
3377 /* Erase all spilled pointers. */
3378 state->stack[spi].spilled_ptr.type = NOT_INIT;
3379
3380 /* Update the slot type. */
3381 new_type = STACK_MISC;
3382 if (writing_zero && *stype == STACK_ZERO) {
3383 new_type = STACK_ZERO;
3384 zero_used = true;
3385 }
3386 /* If the slot is STACK_INVALID, we check whether it's OK to
3387 * pretend that it will be initialized by this write. The slot
3388 * might not actually be written to, and so if we mark it as
3389 * initialized future reads might leak uninitialized memory.
3390 * For privileged programs, we will accept such reads to slots
3391 * that may or may not be written because, if we're reject
3392 * them, the error would be too confusing.
3393 */
3394 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3395 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3396 insn_idx, i);
3397 return -EINVAL;
3398 }
3399 *stype = new_type;
3400 }
3401 if (zero_used) {
3402 /* backtracking doesn't work for STACK_ZERO yet. */
3403 err = mark_chain_precision(env, value_regno);
3404 if (err)
3405 return err;
3406 }
3407 return 0;
3408}
3409
3410/* When register 'dst_regno' is assigned some values from stack[min_off,
3411 * max_off), we set the register's type according to the types of the
3412 * respective stack slots. If all the stack values are known to be zeros, then
3413 * so is the destination reg. Otherwise, the register is considered to be
3414 * SCALAR. This function does not deal with register filling; the caller must
3415 * ensure that all spilled registers in the stack range have been marked as
3416 * read.
3417 */
3418static void mark_reg_stack_read(struct bpf_verifier_env *env,
3419 /* func where src register points to */
3420 struct bpf_func_state *ptr_state,
3421 int min_off, int max_off, int dst_regno)
3422{
3423 struct bpf_verifier_state *vstate = env->cur_state;
3424 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3425 int i, slot, spi;
3426 u8 *stype;
3427 int zeros = 0;
3428
3429 for (i = min_off; i < max_off; i++) {
3430 slot = -i - 1;
3431 spi = slot / BPF_REG_SIZE;
3432 stype = ptr_state->stack[spi].slot_type;
3433 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3434 break;
3435 zeros++;
3436 }
3437 if (zeros == max_off - min_off) {
3438 /* any access_size read into register is zero extended,
3439 * so the whole register == const_zero
3440 */
3441 __mark_reg_const_zero(&state->regs[dst_regno]);
3442 /* backtracking doesn't support STACK_ZERO yet,
3443 * so mark it precise here, so that later
3444 * backtracking can stop here.
3445 * Backtracking may not need this if this register
3446 * doesn't participate in pointer adjustment.
3447 * Forward propagation of precise flag is not
3448 * necessary either. This mark is only to stop
3449 * backtracking. Any register that contributed
3450 * to const 0 was marked precise before spill.
3451 */
3452 state->regs[dst_regno].precise = true;
3453 } else {
3454 /* have read misc data from the stack */
3455 mark_reg_unknown(env, state->regs, dst_regno);
3456 }
3457 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3458}
3459
3460/* Read the stack at 'off' and put the results into the register indicated by
3461 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3462 * spilled reg.
3463 *
3464 * 'dst_regno' can be -1, meaning that the read value is not going to a
3465 * register.
3466 *
3467 * The access is assumed to be within the current stack bounds.
3468 */
3469static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3470 /* func where src register points to */
3471 struct bpf_func_state *reg_state,
3472 int off, int size, int dst_regno)
17a52670 3473{
f4d7e40a
AS
3474 struct bpf_verifier_state *vstate = env->cur_state;
3475 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 3476 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 3477 struct bpf_reg_state *reg;
354e8f19 3478 u8 *stype, type;
17a52670 3479
f4d7e40a 3480 stype = reg_state->stack[spi].slot_type;
f7cf25b2 3481 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 3482
27113c59 3483 if (is_spilled_reg(&reg_state->stack[spi])) {
f30d4968
MKL
3484 u8 spill_size = 1;
3485
3486 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3487 spill_size++;
354e8f19 3488
f30d4968 3489 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
f7cf25b2
AS
3490 if (reg->type != SCALAR_VALUE) {
3491 verbose_linfo(env, env->insn_idx, "; ");
3492 verbose(env, "invalid size of register fill\n");
3493 return -EACCES;
3494 }
354e8f19
MKL
3495
3496 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3497 if (dst_regno < 0)
3498 return 0;
3499
f30d4968 3500 if (!(off % BPF_REG_SIZE) && size == spill_size) {
354e8f19
MKL
3501 /* The earlier check_reg_arg() has decided the
3502 * subreg_def for this insn. Save it first.
3503 */
3504 s32 subreg_def = state->regs[dst_regno].subreg_def;
3505
3506 state->regs[dst_regno] = *reg;
3507 state->regs[dst_regno].subreg_def = subreg_def;
3508 } else {
3509 for (i = 0; i < size; i++) {
3510 type = stype[(slot - i) % BPF_REG_SIZE];
3511 if (type == STACK_SPILL)
3512 continue;
3513 if (type == STACK_MISC)
3514 continue;
3515 verbose(env, "invalid read from stack off %d+%d size %d\n",
3516 off, i, size);
3517 return -EACCES;
3518 }
01f810ac 3519 mark_reg_unknown(env, state->regs, dst_regno);
f7cf25b2 3520 }
354e8f19 3521 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2 3522 return 0;
17a52670 3523 }
17a52670 3524
01f810ac 3525 if (dst_regno >= 0) {
17a52670 3526 /* restore register state from stack */
01f810ac 3527 state->regs[dst_regno] = *reg;
2f18f62e
AS
3528 /* mark reg as written since spilled pointer state likely
3529 * has its liveness marks cleared by is_state_visited()
3530 * which resets stack/reg liveness for state transitions
3531 */
01f810ac 3532 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 3533 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 3534 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
3535 * it is acceptable to use this value as a SCALAR_VALUE
3536 * (e.g. for XADD).
3537 * We must not allow unprivileged callers to do that
3538 * with spilled pointers.
3539 */
3540 verbose(env, "leaking pointer from stack off %d\n",
3541 off);
3542 return -EACCES;
dc503a8a 3543 }
f7cf25b2 3544 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670
AS
3545 } else {
3546 for (i = 0; i < size; i++) {
01f810ac
AM
3547 type = stype[(slot - i) % BPF_REG_SIZE];
3548 if (type == STACK_MISC)
cc2b14d5 3549 continue;
01f810ac 3550 if (type == STACK_ZERO)
cc2b14d5 3551 continue;
cc2b14d5
AS
3552 verbose(env, "invalid read from stack off %d+%d size %d\n",
3553 off, i, size);
3554 return -EACCES;
3555 }
f7cf25b2 3556 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
3557 if (dst_regno >= 0)
3558 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 3559 }
f7cf25b2 3560 return 0;
17a52670
AS
3561}
3562
61df10c7 3563enum bpf_access_src {
01f810ac
AM
3564 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3565 ACCESS_HELPER = 2, /* the access is performed by a helper */
3566};
3567
3568static int check_stack_range_initialized(struct bpf_verifier_env *env,
3569 int regno, int off, int access_size,
3570 bool zero_size_allowed,
61df10c7 3571 enum bpf_access_src type,
01f810ac
AM
3572 struct bpf_call_arg_meta *meta);
3573
3574static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3575{
3576 return cur_regs(env) + regno;
3577}
3578
3579/* Read the stack at 'ptr_regno + off' and put the result into the register
3580 * 'dst_regno'.
3581 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3582 * but not its variable offset.
3583 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3584 *
3585 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3586 * filling registers (i.e. reads of spilled register cannot be detected when
3587 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3588 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3589 * offset; for a fixed offset check_stack_read_fixed_off should be used
3590 * instead.
3591 */
3592static int check_stack_read_var_off(struct bpf_verifier_env *env,
3593 int ptr_regno, int off, int size, int dst_regno)
e4298d25 3594{
01f810ac
AM
3595 /* The state of the source register. */
3596 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3597 struct bpf_func_state *ptr_state = func(env, reg);
3598 int err;
3599 int min_off, max_off;
3600
3601 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 3602 */
01f810ac
AM
3603 err = check_stack_range_initialized(env, ptr_regno, off, size,
3604 false, ACCESS_DIRECT, NULL);
3605 if (err)
3606 return err;
3607
3608 min_off = reg->smin_value + off;
3609 max_off = reg->smax_value + off;
3610 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3611 return 0;
3612}
3613
3614/* check_stack_read dispatches to check_stack_read_fixed_off or
3615 * check_stack_read_var_off.
3616 *
3617 * The caller must ensure that the offset falls within the allocated stack
3618 * bounds.
3619 *
3620 * 'dst_regno' is a register which will receive the value from the stack. It
3621 * can be -1, meaning that the read value is not going to a register.
3622 */
3623static int check_stack_read(struct bpf_verifier_env *env,
3624 int ptr_regno, int off, int size,
3625 int dst_regno)
3626{
3627 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3628 struct bpf_func_state *state = func(env, reg);
3629 int err;
3630 /* Some accesses are only permitted with a static offset. */
3631 bool var_off = !tnum_is_const(reg->var_off);
3632
3633 /* The offset is required to be static when reads don't go to a
3634 * register, in order to not leak pointers (see
3635 * check_stack_read_fixed_off).
3636 */
3637 if (dst_regno < 0 && var_off) {
e4298d25
DB
3638 char tn_buf[48];
3639
3640 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 3641 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
3642 tn_buf, off, size);
3643 return -EACCES;
3644 }
01f810ac
AM
3645 /* Variable offset is prohibited for unprivileged mode for simplicity
3646 * since it requires corresponding support in Spectre masking for stack
3647 * ALU. See also retrieve_ptr_limit().
3648 */
3649 if (!env->bypass_spec_v1 && var_off) {
3650 char tn_buf[48];
e4298d25 3651
01f810ac
AM
3652 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3653 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3654 ptr_regno, tn_buf);
e4298d25
DB
3655 return -EACCES;
3656 }
3657
01f810ac
AM
3658 if (!var_off) {
3659 off += reg->var_off.value;
3660 err = check_stack_read_fixed_off(env, state, off, size,
3661 dst_regno);
3662 } else {
3663 /* Variable offset stack reads need more conservative handling
3664 * than fixed offset ones. Note that dst_regno >= 0 on this
3665 * branch.
3666 */
3667 err = check_stack_read_var_off(env, ptr_regno, off, size,
3668 dst_regno);
3669 }
3670 return err;
3671}
3672
3673
3674/* check_stack_write dispatches to check_stack_write_fixed_off or
3675 * check_stack_write_var_off.
3676 *
3677 * 'ptr_regno' is the register used as a pointer into the stack.
3678 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3679 * 'value_regno' is the register whose value we're writing to the stack. It can
3680 * be -1, meaning that we're not writing from a register.
3681 *
3682 * The caller must ensure that the offset falls within the maximum stack size.
3683 */
3684static int check_stack_write(struct bpf_verifier_env *env,
3685 int ptr_regno, int off, int size,
3686 int value_regno, int insn_idx)
3687{
3688 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3689 struct bpf_func_state *state = func(env, reg);
3690 int err;
3691
3692 if (tnum_is_const(reg->var_off)) {
3693 off += reg->var_off.value;
3694 err = check_stack_write_fixed_off(env, state, off, size,
3695 value_regno, insn_idx);
3696 } else {
3697 /* Variable offset stack reads need more conservative handling
3698 * than fixed offset ones.
3699 */
3700 err = check_stack_write_var_off(env, state,
3701 ptr_regno, off, size,
3702 value_regno, insn_idx);
3703 }
3704 return err;
e4298d25
DB
3705}
3706
591fe988
DB
3707static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3708 int off, int size, enum bpf_access_type type)
3709{
3710 struct bpf_reg_state *regs = cur_regs(env);
3711 struct bpf_map *map = regs[regno].map_ptr;
3712 u32 cap = bpf_map_flags_to_cap(map);
3713
3714 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3715 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3716 map->value_size, off, size);
3717 return -EACCES;
3718 }
3719
3720 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3721 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3722 map->value_size, off, size);
3723 return -EACCES;
3724 }
3725
3726 return 0;
3727}
3728
457f4436
AN
3729/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3730static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3731 int off, int size, u32 mem_size,
3732 bool zero_size_allowed)
17a52670 3733{
457f4436
AN
3734 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3735 struct bpf_reg_state *reg;
3736
3737 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3738 return 0;
17a52670 3739
457f4436
AN
3740 reg = &cur_regs(env)[regno];
3741 switch (reg->type) {
69c087ba
YS
3742 case PTR_TO_MAP_KEY:
3743 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3744 mem_size, off, size);
3745 break;
457f4436 3746 case PTR_TO_MAP_VALUE:
61bd5218 3747 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
3748 mem_size, off, size);
3749 break;
3750 case PTR_TO_PACKET:
3751 case PTR_TO_PACKET_META:
3752 case PTR_TO_PACKET_END:
3753 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3754 off, size, regno, reg->id, off, mem_size);
3755 break;
3756 case PTR_TO_MEM:
3757 default:
3758 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3759 mem_size, off, size);
17a52670 3760 }
457f4436
AN
3761
3762 return -EACCES;
17a52670
AS
3763}
3764
457f4436
AN
3765/* check read/write into a memory region with possible variable offset */
3766static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3767 int off, int size, u32 mem_size,
3768 bool zero_size_allowed)
dbcfe5f7 3769{
f4d7e40a
AS
3770 struct bpf_verifier_state *vstate = env->cur_state;
3771 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
3772 struct bpf_reg_state *reg = &state->regs[regno];
3773 int err;
3774
457f4436 3775 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
3776 * need to try adding each of min_value and max_value to off
3777 * to make sure our theoretical access will be safe.
2e576648
CL
3778 *
3779 * The minimum value is only important with signed
dbcfe5f7
GB
3780 * comparisons where we can't assume the floor of a
3781 * value is 0. If we are using signed variables for our
3782 * index'es we need to make sure that whatever we use
3783 * will have a set floor within our range.
3784 */
b7137c4e
DB
3785 if (reg->smin_value < 0 &&
3786 (reg->smin_value == S64_MIN ||
3787 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3788 reg->smin_value + off < 0)) {
61bd5218 3789 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
3790 regno);
3791 return -EACCES;
3792 }
457f4436
AN
3793 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3794 mem_size, zero_size_allowed);
dbcfe5f7 3795 if (err) {
457f4436 3796 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3797 regno);
dbcfe5f7
GB
3798 return err;
3799 }
3800
b03c9f9f
EC
3801 /* If we haven't set a max value then we need to bail since we can't be
3802 * sure we won't do bad things.
3803 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3804 */
b03c9f9f 3805 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3806 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3807 regno);
3808 return -EACCES;
3809 }
457f4436
AN
3810 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3811 mem_size, zero_size_allowed);
3812 if (err) {
3813 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3814 regno);
457f4436
AN
3815 return err;
3816 }
3817
3818 return 0;
3819}
d83525ca 3820
e9147b44
KKD
3821static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3822 const struct bpf_reg_state *reg, int regno,
3823 bool fixed_off_ok)
3824{
3825 /* Access to this pointer-typed register or passing it to a helper
3826 * is only allowed in its original, unmodified form.
3827 */
3828
3829 if (reg->off < 0) {
3830 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3831 reg_type_str(env, reg->type), regno, reg->off);
3832 return -EACCES;
3833 }
3834
3835 if (!fixed_off_ok && reg->off) {
3836 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3837 reg_type_str(env, reg->type), regno, reg->off);
3838 return -EACCES;
3839 }
3840
3841 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3842 char tn_buf[48];
3843
3844 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3845 verbose(env, "variable %s access var_off=%s disallowed\n",
3846 reg_type_str(env, reg->type), tn_buf);
3847 return -EACCES;
3848 }
3849
3850 return 0;
3851}
3852
3853int check_ptr_off_reg(struct bpf_verifier_env *env,
3854 const struct bpf_reg_state *reg, int regno)
3855{
3856 return __check_ptr_off_reg(env, reg, regno, false);
3857}
3858
61df10c7 3859static int map_kptr_match_type(struct bpf_verifier_env *env,
aa3496ac 3860 struct btf_field *kptr_field,
61df10c7
KKD
3861 struct bpf_reg_state *reg, u32 regno)
3862{
aa3496ac 3863 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
3f00c523 3864 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED;
61df10c7
KKD
3865 const char *reg_name = "";
3866
6efe152d 3867 /* Only unreferenced case accepts untrusted pointers */
aa3496ac 3868 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
3869 perm_flags |= PTR_UNTRUSTED;
3870
3871 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
61df10c7
KKD
3872 goto bad_type;
3873
3874 if (!btf_is_kernel(reg->btf)) {
3875 verbose(env, "R%d must point to kernel BTF\n", regno);
3876 return -EINVAL;
3877 }
3878 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3879 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3880
c0a5a21c
KKD
3881 /* For ref_ptr case, release function check should ensure we get one
3882 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3883 * normal store of unreferenced kptr, we must ensure var_off is zero.
3884 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3885 * reg->off and reg->ref_obj_id are not needed here.
3886 */
61df10c7
KKD
3887 if (__check_ptr_off_reg(env, reg, regno, true))
3888 return -EACCES;
3889
3890 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3891 * we also need to take into account the reg->off.
3892 *
3893 * We want to support cases like:
3894 *
3895 * struct foo {
3896 * struct bar br;
3897 * struct baz bz;
3898 * };
3899 *
3900 * struct foo *v;
3901 * v = func(); // PTR_TO_BTF_ID
3902 * val->foo = v; // reg->off is zero, btf and btf_id match type
3903 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3904 * // first member type of struct after comparison fails
3905 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3906 * // to match type
3907 *
3908 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
2ab3b380
KKD
3909 * is zero. We must also ensure that btf_struct_ids_match does not walk
3910 * the struct to match type against first member of struct, i.e. reject
3911 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3912 * strict mode to true for type match.
61df10c7
KKD
3913 */
3914 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
aa3496ac
KKD
3915 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
3916 kptr_field->type == BPF_KPTR_REF))
61df10c7
KKD
3917 goto bad_type;
3918 return 0;
3919bad_type:
3920 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3921 reg_type_str(env, reg->type), reg_name);
6efe152d 3922 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
aa3496ac 3923 if (kptr_field->type == BPF_KPTR_UNREF)
6efe152d
KKD
3924 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3925 targ_name);
3926 else
3927 verbose(env, "\n");
61df10c7
KKD
3928 return -EINVAL;
3929}
3930
3931static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3932 int value_regno, int insn_idx,
aa3496ac 3933 struct btf_field *kptr_field)
61df10c7
KKD
3934{
3935 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3936 int class = BPF_CLASS(insn->code);
3937 struct bpf_reg_state *val_reg;
3938
3939 /* Things we already checked for in check_map_access and caller:
3940 * - Reject cases where variable offset may touch kptr
3941 * - size of access (must be BPF_DW)
3942 * - tnum_is_const(reg->var_off)
aa3496ac 3943 * - kptr_field->offset == off + reg->var_off.value
61df10c7
KKD
3944 */
3945 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3946 if (BPF_MODE(insn->code) != BPF_MEM) {
3947 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3948 return -EACCES;
3949 }
3950
6efe152d
KKD
3951 /* We only allow loading referenced kptr, since it will be marked as
3952 * untrusted, similar to unreferenced kptr.
3953 */
aa3496ac 3954 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
6efe152d 3955 verbose(env, "store to referenced kptr disallowed\n");
c0a5a21c
KKD
3956 return -EACCES;
3957 }
3958
61df10c7
KKD
3959 if (class == BPF_LDX) {
3960 val_reg = reg_state(env, value_regno);
3961 /* We can simply mark the value_regno receiving the pointer
3962 * value from map as PTR_TO_BTF_ID, with the correct type.
3963 */
aa3496ac
KKD
3964 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
3965 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
61df10c7
KKD
3966 /* For mark_ptr_or_null_reg */
3967 val_reg->id = ++env->id_gen;
3968 } else if (class == BPF_STX) {
3969 val_reg = reg_state(env, value_regno);
3970 if (!register_is_null(val_reg) &&
aa3496ac 3971 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
61df10c7
KKD
3972 return -EACCES;
3973 } else if (class == BPF_ST) {
3974 if (insn->imm) {
3975 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
aa3496ac 3976 kptr_field->offset);
61df10c7
KKD
3977 return -EACCES;
3978 }
3979 } else {
3980 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3981 return -EACCES;
3982 }
3983 return 0;
3984}
3985
457f4436
AN
3986/* check read/write into a map element with possible variable offset */
3987static int check_map_access(struct bpf_verifier_env *env, u32 regno,
61df10c7
KKD
3988 int off, int size, bool zero_size_allowed,
3989 enum bpf_access_src src)
457f4436
AN
3990{
3991 struct bpf_verifier_state *vstate = env->cur_state;
3992 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3993 struct bpf_reg_state *reg = &state->regs[regno];
3994 struct bpf_map *map = reg->map_ptr;
aa3496ac
KKD
3995 struct btf_record *rec;
3996 int err, i;
457f4436
AN
3997
3998 err = check_mem_region_access(env, regno, off, size, map->value_size,
3999 zero_size_allowed);
4000 if (err)
4001 return err;
4002
aa3496ac
KKD
4003 if (IS_ERR_OR_NULL(map->record))
4004 return 0;
4005 rec = map->record;
4006 for (i = 0; i < rec->cnt; i++) {
4007 struct btf_field *field = &rec->fields[i];
4008 u32 p = field->offset;
d83525ca 4009
db559117
KKD
4010 /* If any part of a field can be touched by load/store, reject
4011 * this program. To check that [x1, x2) overlaps with [y1, y2),
d83525ca
AS
4012 * it is sufficient to check x1 < y2 && y1 < x2.
4013 */
aa3496ac
KKD
4014 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4015 p < reg->umax_value + off + size) {
4016 switch (field->type) {
4017 case BPF_KPTR_UNREF:
4018 case BPF_KPTR_REF:
61df10c7
KKD
4019 if (src != ACCESS_DIRECT) {
4020 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4021 return -EACCES;
4022 }
4023 if (!tnum_is_const(reg->var_off)) {
4024 verbose(env, "kptr access cannot have variable offset\n");
4025 return -EACCES;
4026 }
4027 if (p != off + reg->var_off.value) {
4028 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4029 p, off + reg->var_off.value);
4030 return -EACCES;
4031 }
4032 if (size != bpf_size_to_bytes(BPF_DW)) {
4033 verbose(env, "kptr access size must be BPF_DW\n");
4034 return -EACCES;
4035 }
4036 break;
aa3496ac 4037 default:
db559117
KKD
4038 verbose(env, "%s cannot be accessed directly by load/store\n",
4039 btf_field_type_name(field->type));
aa3496ac 4040 return -EACCES;
61df10c7
KKD
4041 }
4042 }
4043 }
aa3496ac 4044 return 0;
dbcfe5f7
GB
4045}
4046
969bf05e
AS
4047#define MAX_PACKET_OFF 0xffff
4048
58e2af8b 4049static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
4050 const struct bpf_call_arg_meta *meta,
4051 enum bpf_access_type t)
4acf6c0b 4052{
7e40781c
UP
4053 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4054
4055 switch (prog_type) {
5d66fa7d 4056 /* Program types only with direct read access go here! */
3a0af8fd
TG
4057 case BPF_PROG_TYPE_LWT_IN:
4058 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 4059 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 4060 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 4061 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 4062 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
4063 if (t == BPF_WRITE)
4064 return false;
8731745e 4065 fallthrough;
5d66fa7d
DB
4066
4067 /* Program types with direct read + write access go here! */
36bbef52
DB
4068 case BPF_PROG_TYPE_SCHED_CLS:
4069 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 4070 case BPF_PROG_TYPE_XDP:
3a0af8fd 4071 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 4072 case BPF_PROG_TYPE_SK_SKB:
4f738adb 4073 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
4074 if (meta)
4075 return meta->pkt_access;
4076
4077 env->seen_direct_write = true;
4acf6c0b 4078 return true;
0d01da6a
SF
4079
4080 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4081 if (t == BPF_WRITE)
4082 env->seen_direct_write = true;
4083
4084 return true;
4085
4acf6c0b
BB
4086 default:
4087 return false;
4088 }
4089}
4090
f1174f77 4091static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 4092 int size, bool zero_size_allowed)
f1174f77 4093{
638f5b90 4094 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
4095 struct bpf_reg_state *reg = &regs[regno];
4096 int err;
4097
4098 /* We may have added a variable offset to the packet pointer; but any
4099 * reg->range we have comes after that. We are only checking the fixed
4100 * offset.
4101 */
4102
4103 /* We don't allow negative numbers, because we aren't tracking enough
4104 * detail to prove they're safe.
4105 */
b03c9f9f 4106 if (reg->smin_value < 0) {
61bd5218 4107 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
4108 regno);
4109 return -EACCES;
4110 }
6d94e741
AS
4111
4112 err = reg->range < 0 ? -EINVAL :
4113 __check_mem_access(env, regno, off, size, reg->range,
457f4436 4114 zero_size_allowed);
f1174f77 4115 if (err) {
61bd5218 4116 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
4117 return err;
4118 }
e647815a 4119
457f4436 4120 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
4121 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4122 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 4123 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
4124 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4125 */
4126 env->prog->aux->max_pkt_offset =
4127 max_t(u32, env->prog->aux->max_pkt_offset,
4128 off + reg->umax_value + size - 1);
4129
f1174f77
EC
4130 return err;
4131}
4132
4133/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 4134static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 4135 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 4136 struct btf **btf, u32 *btf_id)
17a52670 4137{
f96da094
DB
4138 struct bpf_insn_access_aux info = {
4139 .reg_type = *reg_type,
9e15db66 4140 .log = &env->log,
f96da094 4141 };
31fd8581 4142
4f9218aa 4143 if (env->ops->is_valid_access &&
5e43f899 4144 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
4145 /* A non zero info.ctx_field_size indicates that this field is a
4146 * candidate for later verifier transformation to load the whole
4147 * field and then apply a mask when accessed with a narrower
4148 * access than actual ctx access size. A zero info.ctx_field_size
4149 * will only allow for whole field access and rejects any other
4150 * type of narrower access.
31fd8581 4151 */
23994631 4152 *reg_type = info.reg_type;
31fd8581 4153
c25b2ae1 4154 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 4155 *btf = info.btf;
9e15db66 4156 *btf_id = info.btf_id;
22dc4a0f 4157 } else {
9e15db66 4158 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 4159 }
32bbe007
AS
4160 /* remember the offset of last byte accessed in ctx */
4161 if (env->prog->aux->max_ctx_offset < off + size)
4162 env->prog->aux->max_ctx_offset = off + size;
17a52670 4163 return 0;
32bbe007 4164 }
17a52670 4165
61bd5218 4166 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
4167 return -EACCES;
4168}
4169
d58e468b
PP
4170static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4171 int size)
4172{
4173 if (size < 0 || off < 0 ||
4174 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4175 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4176 off, size);
4177 return -EACCES;
4178 }
4179 return 0;
4180}
4181
5f456649
MKL
4182static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4183 u32 regno, int off, int size,
4184 enum bpf_access_type t)
c64b7983
JS
4185{
4186 struct bpf_reg_state *regs = cur_regs(env);
4187 struct bpf_reg_state *reg = &regs[regno];
5f456649 4188 struct bpf_insn_access_aux info = {};
46f8bc92 4189 bool valid;
c64b7983
JS
4190
4191 if (reg->smin_value < 0) {
4192 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4193 regno);
4194 return -EACCES;
4195 }
4196
46f8bc92
MKL
4197 switch (reg->type) {
4198 case PTR_TO_SOCK_COMMON:
4199 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4200 break;
4201 case PTR_TO_SOCKET:
4202 valid = bpf_sock_is_valid_access(off, size, t, &info);
4203 break;
655a51e5
MKL
4204 case PTR_TO_TCP_SOCK:
4205 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4206 break;
fada7fdc
JL
4207 case PTR_TO_XDP_SOCK:
4208 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4209 break;
46f8bc92
MKL
4210 default:
4211 valid = false;
c64b7983
JS
4212 }
4213
5f456649 4214
46f8bc92
MKL
4215 if (valid) {
4216 env->insn_aux_data[insn_idx].ctx_field_size =
4217 info.ctx_field_size;
4218 return 0;
4219 }
4220
4221 verbose(env, "R%d invalid %s access off=%d size=%d\n",
c25b2ae1 4222 regno, reg_type_str(env, reg->type), off, size);
46f8bc92
MKL
4223
4224 return -EACCES;
c64b7983
JS
4225}
4226
4cabc5b1
DB
4227static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4228{
2a159c6f 4229 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
4230}
4231
f37a8cb8
DB
4232static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4233{
2a159c6f 4234 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 4235
46f8bc92
MKL
4236 return reg->type == PTR_TO_CTX;
4237}
4238
4239static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4240{
4241 const struct bpf_reg_state *reg = reg_state(env, regno);
4242
4243 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
4244}
4245
ca369602
DB
4246static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4247{
2a159c6f 4248 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
4249
4250 return type_is_pkt_pointer(reg->type);
4251}
4252
4b5defde
DB
4253static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4254{
4255 const struct bpf_reg_state *reg = reg_state(env, regno);
4256
4257 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4258 return reg->type == PTR_TO_FLOW_KEYS;
4259}
4260
61bd5218
JK
4261static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4262 const struct bpf_reg_state *reg,
d1174416 4263 int off, int size, bool strict)
969bf05e 4264{
f1174f77 4265 struct tnum reg_off;
e07b98d9 4266 int ip_align;
d1174416
DM
4267
4268 /* Byte size accesses are always allowed. */
4269 if (!strict || size == 1)
4270 return 0;
4271
e4eda884
DM
4272 /* For platforms that do not have a Kconfig enabling
4273 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4274 * NET_IP_ALIGN is universally set to '2'. And on platforms
4275 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4276 * to this code only in strict mode where we want to emulate
4277 * the NET_IP_ALIGN==2 checking. Therefore use an
4278 * unconditional IP align value of '2'.
e07b98d9 4279 */
e4eda884 4280 ip_align = 2;
f1174f77
EC
4281
4282 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4283 if (!tnum_is_aligned(reg_off, size)) {
4284 char tn_buf[48];
4285
4286 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
4287 verbose(env,
4288 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 4289 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
4290 return -EACCES;
4291 }
79adffcd 4292
969bf05e
AS
4293 return 0;
4294}
4295
61bd5218
JK
4296static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4297 const struct bpf_reg_state *reg,
f1174f77
EC
4298 const char *pointer_desc,
4299 int off, int size, bool strict)
79adffcd 4300{
f1174f77
EC
4301 struct tnum reg_off;
4302
4303 /* Byte size accesses are always allowed. */
4304 if (!strict || size == 1)
4305 return 0;
4306
4307 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4308 if (!tnum_is_aligned(reg_off, size)) {
4309 char tn_buf[48];
4310
4311 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 4312 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 4313 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
4314 return -EACCES;
4315 }
4316
969bf05e
AS
4317 return 0;
4318}
4319
e07b98d9 4320static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
4321 const struct bpf_reg_state *reg, int off,
4322 int size, bool strict_alignment_once)
79adffcd 4323{
ca369602 4324 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 4325 const char *pointer_desc = "";
d1174416 4326
79adffcd
DB
4327 switch (reg->type) {
4328 case PTR_TO_PACKET:
de8f3a83
DB
4329 case PTR_TO_PACKET_META:
4330 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4331 * right in front, treat it the very same way.
4332 */
61bd5218 4333 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
4334 case PTR_TO_FLOW_KEYS:
4335 pointer_desc = "flow keys ";
4336 break;
69c087ba
YS
4337 case PTR_TO_MAP_KEY:
4338 pointer_desc = "key ";
4339 break;
f1174f77
EC
4340 case PTR_TO_MAP_VALUE:
4341 pointer_desc = "value ";
4342 break;
4343 case PTR_TO_CTX:
4344 pointer_desc = "context ";
4345 break;
4346 case PTR_TO_STACK:
4347 pointer_desc = "stack ";
01f810ac
AM
4348 /* The stack spill tracking logic in check_stack_write_fixed_off()
4349 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
4350 * aligned.
4351 */
4352 strict = true;
f1174f77 4353 break;
c64b7983
JS
4354 case PTR_TO_SOCKET:
4355 pointer_desc = "sock ";
4356 break;
46f8bc92
MKL
4357 case PTR_TO_SOCK_COMMON:
4358 pointer_desc = "sock_common ";
4359 break;
655a51e5
MKL
4360 case PTR_TO_TCP_SOCK:
4361 pointer_desc = "tcp_sock ";
4362 break;
fada7fdc
JL
4363 case PTR_TO_XDP_SOCK:
4364 pointer_desc = "xdp_sock ";
4365 break;
79adffcd 4366 default:
f1174f77 4367 break;
79adffcd 4368 }
61bd5218
JK
4369 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4370 strict);
79adffcd
DB
4371}
4372
f4d7e40a
AS
4373static int update_stack_depth(struct bpf_verifier_env *env,
4374 const struct bpf_func_state *func,
4375 int off)
4376{
9c8105bd 4377 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
4378
4379 if (stack >= -off)
4380 return 0;
4381
4382 /* update known max for given subprogram */
9c8105bd 4383 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
4384 return 0;
4385}
f4d7e40a 4386
70a87ffe
AS
4387/* starting from main bpf function walk all instructions of the function
4388 * and recursively walk all callees that given function can call.
4389 * Ignore jump and exit insns.
4390 * Since recursion is prevented by check_cfg() this algorithm
4391 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4392 */
4393static int check_max_stack_depth(struct bpf_verifier_env *env)
4394{
9c8105bd
JW
4395 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4396 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 4397 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 4398 bool tail_call_reachable = false;
70a87ffe
AS
4399 int ret_insn[MAX_CALL_FRAMES];
4400 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 4401 int j;
f4d7e40a 4402
70a87ffe 4403process_func:
7f6e4312
MF
4404 /* protect against potential stack overflow that might happen when
4405 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4406 * depth for such case down to 256 so that the worst case scenario
4407 * would result in 8k stack size (32 which is tailcall limit * 256 =
4408 * 8k).
4409 *
4410 * To get the idea what might happen, see an example:
4411 * func1 -> sub rsp, 128
4412 * subfunc1 -> sub rsp, 256
4413 * tailcall1 -> add rsp, 256
4414 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4415 * subfunc2 -> sub rsp, 64
4416 * subfunc22 -> sub rsp, 128
4417 * tailcall2 -> add rsp, 128
4418 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4419 *
4420 * tailcall will unwind the current stack frame but it will not get rid
4421 * of caller's stack as shown on the example above.
4422 */
4423 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4424 verbose(env,
4425 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4426 depth);
4427 return -EACCES;
4428 }
70a87ffe
AS
4429 /* round up to 32-bytes, since this is granularity
4430 * of interpreter stack size
4431 */
9c8105bd 4432 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 4433 if (depth > MAX_BPF_STACK) {
f4d7e40a 4434 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 4435 frame + 1, depth);
f4d7e40a
AS
4436 return -EACCES;
4437 }
70a87ffe 4438continue_func:
4cb3d99c 4439 subprog_end = subprog[idx + 1].start;
70a87ffe 4440 for (; i < subprog_end; i++) {
7ddc80a4
AS
4441 int next_insn;
4442
69c087ba 4443 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
4444 continue;
4445 /* remember insn and function to return to */
4446 ret_insn[frame] = i + 1;
9c8105bd 4447 ret_prog[frame] = idx;
70a87ffe
AS
4448
4449 /* find the callee */
7ddc80a4
AS
4450 next_insn = i + insn[i].imm + 1;
4451 idx = find_subprog(env, next_insn);
9c8105bd 4452 if (idx < 0) {
70a87ffe 4453 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7ddc80a4 4454 next_insn);
70a87ffe
AS
4455 return -EFAULT;
4456 }
7ddc80a4
AS
4457 if (subprog[idx].is_async_cb) {
4458 if (subprog[idx].has_tail_call) {
4459 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4460 return -EFAULT;
4461 }
4462 /* async callbacks don't increase bpf prog stack size */
4463 continue;
4464 }
4465 i = next_insn;
ebf7d1f5
MF
4466
4467 if (subprog[idx].has_tail_call)
4468 tail_call_reachable = true;
4469
70a87ffe
AS
4470 frame++;
4471 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
4472 verbose(env, "the call stack of %d frames is too deep !\n",
4473 frame);
4474 return -E2BIG;
70a87ffe
AS
4475 }
4476 goto process_func;
4477 }
ebf7d1f5
MF
4478 /* if tail call got detected across bpf2bpf calls then mark each of the
4479 * currently present subprog frames as tail call reachable subprogs;
4480 * this info will be utilized by JIT so that we will be preserving the
4481 * tail call counter throughout bpf2bpf calls combined with tailcalls
4482 */
4483 if (tail_call_reachable)
4484 for (j = 0; j < frame; j++)
4485 subprog[ret_prog[j]].tail_call_reachable = true;
5dd0a6b8
DB
4486 if (subprog[0].tail_call_reachable)
4487 env->prog->aux->tail_call_reachable = true;
ebf7d1f5 4488
70a87ffe
AS
4489 /* end of for() loop means the last insn of the 'subprog'
4490 * was reached. Doesn't matter whether it was JA or EXIT
4491 */
4492 if (frame == 0)
4493 return 0;
9c8105bd 4494 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
4495 frame--;
4496 i = ret_insn[frame];
9c8105bd 4497 idx = ret_prog[frame];
70a87ffe 4498 goto continue_func;
f4d7e40a
AS
4499}
4500
19d28fbd 4501#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
4502static int get_callee_stack_depth(struct bpf_verifier_env *env,
4503 const struct bpf_insn *insn, int idx)
4504{
4505 int start = idx + insn->imm + 1, subprog;
4506
4507 subprog = find_subprog(env, start);
4508 if (subprog < 0) {
4509 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4510 start);
4511 return -EFAULT;
4512 }
9c8105bd 4513 return env->subprog_info[subprog].stack_depth;
1ea47e01 4514}
19d28fbd 4515#endif
1ea47e01 4516
afbf21dc
YS
4517static int __check_buffer_access(struct bpf_verifier_env *env,
4518 const char *buf_info,
4519 const struct bpf_reg_state *reg,
4520 int regno, int off, int size)
9df1c28b
MM
4521{
4522 if (off < 0) {
4523 verbose(env,
4fc00b79 4524 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 4525 regno, buf_info, off, size);
9df1c28b
MM
4526 return -EACCES;
4527 }
4528 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4529 char tn_buf[48];
4530
4531 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4532 verbose(env,
4fc00b79 4533 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
4534 regno, off, tn_buf);
4535 return -EACCES;
4536 }
afbf21dc
YS
4537
4538 return 0;
4539}
4540
4541static int check_tp_buffer_access(struct bpf_verifier_env *env,
4542 const struct bpf_reg_state *reg,
4543 int regno, int off, int size)
4544{
4545 int err;
4546
4547 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4548 if (err)
4549 return err;
4550
9df1c28b
MM
4551 if (off + size > env->prog->aux->max_tp_access)
4552 env->prog->aux->max_tp_access = off + size;
4553
4554 return 0;
4555}
4556
afbf21dc
YS
4557static int check_buffer_access(struct bpf_verifier_env *env,
4558 const struct bpf_reg_state *reg,
4559 int regno, int off, int size,
4560 bool zero_size_allowed,
afbf21dc
YS
4561 u32 *max_access)
4562{
44e9a741 4563 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
afbf21dc
YS
4564 int err;
4565
4566 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4567 if (err)
4568 return err;
4569
4570 if (off + size > *max_access)
4571 *max_access = off + size;
4572
4573 return 0;
4574}
4575
3f50f132
JF
4576/* BPF architecture zero extends alu32 ops into 64-bit registesr */
4577static void zext_32_to_64(struct bpf_reg_state *reg)
4578{
4579 reg->var_off = tnum_subreg(reg->var_off);
4580 __reg_assign_32_into_64(reg);
4581}
9df1c28b 4582
0c17d1d2
JH
4583/* truncate register to smaller size (in bytes)
4584 * must be called with size < BPF_REG_SIZE
4585 */
4586static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4587{
4588 u64 mask;
4589
4590 /* clear high bits in bit representation */
4591 reg->var_off = tnum_cast(reg->var_off, size);
4592
4593 /* fix arithmetic bounds */
4594 mask = ((u64)1 << (size * 8)) - 1;
4595 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4596 reg->umin_value &= mask;
4597 reg->umax_value &= mask;
4598 } else {
4599 reg->umin_value = 0;
4600 reg->umax_value = mask;
4601 }
4602 reg->smin_value = reg->umin_value;
4603 reg->smax_value = reg->umax_value;
3f50f132
JF
4604
4605 /* If size is smaller than 32bit register the 32bit register
4606 * values are also truncated so we push 64-bit bounds into
4607 * 32-bit bounds. Above were truncated < 32-bits already.
4608 */
4609 if (size >= 4)
4610 return;
4611 __reg_combine_64_into_32(reg);
0c17d1d2
JH
4612}
4613
a23740ec
AN
4614static bool bpf_map_is_rdonly(const struct bpf_map *map)
4615{
353050be
DB
4616 /* A map is considered read-only if the following condition are true:
4617 *
4618 * 1) BPF program side cannot change any of the map content. The
4619 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4620 * and was set at map creation time.
4621 * 2) The map value(s) have been initialized from user space by a
4622 * loader and then "frozen", such that no new map update/delete
4623 * operations from syscall side are possible for the rest of
4624 * the map's lifetime from that point onwards.
4625 * 3) Any parallel/pending map update/delete operations from syscall
4626 * side have been completed. Only after that point, it's safe to
4627 * assume that map value(s) are immutable.
4628 */
4629 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4630 READ_ONCE(map->frozen) &&
4631 !bpf_map_write_active(map);
a23740ec
AN
4632}
4633
4634static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4635{
4636 void *ptr;
4637 u64 addr;
4638 int err;
4639
4640 err = map->ops->map_direct_value_addr(map, &addr, off);
4641 if (err)
4642 return err;
2dedd7d2 4643 ptr = (void *)(long)addr + off;
a23740ec
AN
4644
4645 switch (size) {
4646 case sizeof(u8):
4647 *val = (u64)*(u8 *)ptr;
4648 break;
4649 case sizeof(u16):
4650 *val = (u64)*(u16 *)ptr;
4651 break;
4652 case sizeof(u32):
4653 *val = (u64)*(u32 *)ptr;
4654 break;
4655 case sizeof(u64):
4656 *val = *(u64 *)ptr;
4657 break;
4658 default:
4659 return -EINVAL;
4660 }
4661 return 0;
4662}
4663
9e15db66
AS
4664static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4665 struct bpf_reg_state *regs,
4666 int regno, int off, int size,
4667 enum bpf_access_type atype,
4668 int value_regno)
4669{
4670 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
4671 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4672 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
c6f1bfe8 4673 enum bpf_type_flag flag = 0;
9e15db66
AS
4674 u32 btf_id;
4675 int ret;
4676
9e15db66
AS
4677 if (off < 0) {
4678 verbose(env,
4679 "R%d is ptr_%s invalid negative access: off=%d\n",
4680 regno, tname, off);
4681 return -EACCES;
4682 }
4683 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4684 char tn_buf[48];
4685
4686 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4687 verbose(env,
4688 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4689 regno, tname, off, tn_buf);
4690 return -EACCES;
4691 }
4692
c6f1bfe8
YS
4693 if (reg->type & MEM_USER) {
4694 verbose(env,
4695 "R%d is ptr_%s access user memory: off=%d\n",
4696 regno, tname, off);
4697 return -EACCES;
4698 }
4699
5844101a
HL
4700 if (reg->type & MEM_PERCPU) {
4701 verbose(env,
4702 "R%d is ptr_%s access percpu memory: off=%d\n",
4703 regno, tname, off);
4704 return -EACCES;
4705 }
4706
282de143
KKD
4707 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) {
4708 if (!btf_is_kernel(reg->btf)) {
4709 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
4710 return -EFAULT;
4711 }
6728aea7 4712 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
27ae7997 4713 } else {
282de143
KKD
4714 /* Writes are permitted with default btf_struct_access for
4715 * program allocated objects (which always have ref_obj_id > 0),
4716 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
4717 */
4718 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
27ae7997
MKL
4719 verbose(env, "only read is supported\n");
4720 return -EACCES;
4721 }
4722
282de143
KKD
4723 if (type_is_alloc(reg->type) && !reg->ref_obj_id) {
4724 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
4725 return -EFAULT;
4726 }
4727
6728aea7 4728 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag);
27ae7997
MKL
4729 }
4730
9e15db66
AS
4731 if (ret < 0)
4732 return ret;
4733
6efe152d
KKD
4734 /* If this is an untrusted pointer, all pointers formed by walking it
4735 * also inherit the untrusted flag.
4736 */
4737 if (type_flag(reg->type) & PTR_UNTRUSTED)
4738 flag |= PTR_UNTRUSTED;
4739
3f00c523
DV
4740 /* Any pointer obtained from walking a trusted pointer is no longer trusted. */
4741 flag &= ~PTR_TRUSTED;
4742
41c48f3a 4743 if (atype == BPF_READ && value_regno >= 0)
c6f1bfe8 4744 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
41c48f3a
AI
4745
4746 return 0;
4747}
4748
4749static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4750 struct bpf_reg_state *regs,
4751 int regno, int off, int size,
4752 enum bpf_access_type atype,
4753 int value_regno)
4754{
4755 struct bpf_reg_state *reg = regs + regno;
4756 struct bpf_map *map = reg->map_ptr;
6728aea7 4757 struct bpf_reg_state map_reg;
c6f1bfe8 4758 enum bpf_type_flag flag = 0;
41c48f3a
AI
4759 const struct btf_type *t;
4760 const char *tname;
4761 u32 btf_id;
4762 int ret;
4763
4764 if (!btf_vmlinux) {
4765 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4766 return -ENOTSUPP;
4767 }
4768
4769 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4770 verbose(env, "map_ptr access not supported for map type %d\n",
4771 map->map_type);
4772 return -ENOTSUPP;
4773 }
4774
4775 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4776 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4777
4778 if (!env->allow_ptr_to_map_access) {
4779 verbose(env,
4780 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4781 tname);
4782 return -EPERM;
9e15db66 4783 }
27ae7997 4784
41c48f3a
AI
4785 if (off < 0) {
4786 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4787 regno, tname, off);
4788 return -EACCES;
4789 }
4790
4791 if (atype != BPF_READ) {
4792 verbose(env, "only read from %s is supported\n", tname);
4793 return -EACCES;
4794 }
4795
6728aea7
KKD
4796 /* Simulate access to a PTR_TO_BTF_ID */
4797 memset(&map_reg, 0, sizeof(map_reg));
4798 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
4799 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag);
41c48f3a
AI
4800 if (ret < 0)
4801 return ret;
4802
4803 if (value_regno >= 0)
c6f1bfe8 4804 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
41c48f3a 4805
9e15db66
AS
4806 return 0;
4807}
4808
01f810ac
AM
4809/* Check that the stack access at the given offset is within bounds. The
4810 * maximum valid offset is -1.
4811 *
4812 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4813 * -state->allocated_stack for reads.
4814 */
4815static int check_stack_slot_within_bounds(int off,
4816 struct bpf_func_state *state,
4817 enum bpf_access_type t)
4818{
4819 int min_valid_off;
4820
4821 if (t == BPF_WRITE)
4822 min_valid_off = -MAX_BPF_STACK;
4823 else
4824 min_valid_off = -state->allocated_stack;
4825
4826 if (off < min_valid_off || off > -1)
4827 return -EACCES;
4828 return 0;
4829}
4830
4831/* Check that the stack access at 'regno + off' falls within the maximum stack
4832 * bounds.
4833 *
4834 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4835 */
4836static int check_stack_access_within_bounds(
4837 struct bpf_verifier_env *env,
4838 int regno, int off, int access_size,
61df10c7 4839 enum bpf_access_src src, enum bpf_access_type type)
01f810ac
AM
4840{
4841 struct bpf_reg_state *regs = cur_regs(env);
4842 struct bpf_reg_state *reg = regs + regno;
4843 struct bpf_func_state *state = func(env, reg);
4844 int min_off, max_off;
4845 int err;
4846 char *err_extra;
4847
4848 if (src == ACCESS_HELPER)
4849 /* We don't know if helpers are reading or writing (or both). */
4850 err_extra = " indirect access to";
4851 else if (type == BPF_READ)
4852 err_extra = " read from";
4853 else
4854 err_extra = " write to";
4855
4856 if (tnum_is_const(reg->var_off)) {
4857 min_off = reg->var_off.value + off;
4858 if (access_size > 0)
4859 max_off = min_off + access_size - 1;
4860 else
4861 max_off = min_off;
4862 } else {
4863 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4864 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4865 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4866 err_extra, regno);
4867 return -EACCES;
4868 }
4869 min_off = reg->smin_value + off;
4870 if (access_size > 0)
4871 max_off = reg->smax_value + off + access_size - 1;
4872 else
4873 max_off = min_off;
4874 }
4875
4876 err = check_stack_slot_within_bounds(min_off, state, type);
4877 if (!err)
4878 err = check_stack_slot_within_bounds(max_off, state, type);
4879
4880 if (err) {
4881 if (tnum_is_const(reg->var_off)) {
4882 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4883 err_extra, regno, off, access_size);
4884 } else {
4885 char tn_buf[48];
4886
4887 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4888 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4889 err_extra, regno, tn_buf, access_size);
4890 }
4891 }
4892 return err;
4893}
41c48f3a 4894
17a52670
AS
4895/* check whether memory at (regno + off) is accessible for t = (read | write)
4896 * if t==write, value_regno is a register which value is stored into memory
4897 * if t==read, value_regno is a register which will receive the value from memory
4898 * if t==write && value_regno==-1, some unknown value is stored into memory
4899 * if t==read && value_regno==-1, don't care what we read from memory
4900 */
ca369602
DB
4901static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4902 int off, int bpf_size, enum bpf_access_type t,
4903 int value_regno, bool strict_alignment_once)
17a52670 4904{
638f5b90
AS
4905 struct bpf_reg_state *regs = cur_regs(env);
4906 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 4907 struct bpf_func_state *state;
17a52670
AS
4908 int size, err = 0;
4909
4910 size = bpf_size_to_bytes(bpf_size);
4911 if (size < 0)
4912 return size;
4913
f1174f77 4914 /* alignment checks will add in reg->off themselves */
ca369602 4915 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
4916 if (err)
4917 return err;
17a52670 4918
f1174f77
EC
4919 /* for access checks, reg->off is just part of off */
4920 off += reg->off;
4921
69c087ba
YS
4922 if (reg->type == PTR_TO_MAP_KEY) {
4923 if (t == BPF_WRITE) {
4924 verbose(env, "write to change key R%d not allowed\n", regno);
4925 return -EACCES;
4926 }
4927
4928 err = check_mem_region_access(env, regno, off, size,
4929 reg->map_ptr->key_size, false);
4930 if (err)
4931 return err;
4932 if (value_regno >= 0)
4933 mark_reg_unknown(env, regs, value_regno);
4934 } else if (reg->type == PTR_TO_MAP_VALUE) {
aa3496ac 4935 struct btf_field *kptr_field = NULL;
61df10c7 4936
1be7f75d
AS
4937 if (t == BPF_WRITE && value_regno >= 0 &&
4938 is_pointer_value(env, value_regno)) {
61bd5218 4939 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
4940 return -EACCES;
4941 }
591fe988
DB
4942 err = check_map_access_type(env, regno, off, size, t);
4943 if (err)
4944 return err;
61df10c7
KKD
4945 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4946 if (err)
4947 return err;
4948 if (tnum_is_const(reg->var_off))
aa3496ac
KKD
4949 kptr_field = btf_record_find(reg->map_ptr->record,
4950 off + reg->var_off.value, BPF_KPTR);
4951 if (kptr_field) {
4952 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
61df10c7 4953 } else if (t == BPF_READ && value_regno >= 0) {
a23740ec
AN
4954 struct bpf_map *map = reg->map_ptr;
4955
4956 /* if map is read-only, track its contents as scalars */
4957 if (tnum_is_const(reg->var_off) &&
4958 bpf_map_is_rdonly(map) &&
4959 map->ops->map_direct_value_addr) {
4960 int map_off = off + reg->var_off.value;
4961 u64 val = 0;
4962
4963 err = bpf_map_direct_read(map, map_off, size,
4964 &val);
4965 if (err)
4966 return err;
4967
4968 regs[value_regno].type = SCALAR_VALUE;
4969 __mark_reg_known(&regs[value_regno], val);
4970 } else {
4971 mark_reg_unknown(env, regs, value_regno);
4972 }
4973 }
34d3a78c
HL
4974 } else if (base_type(reg->type) == PTR_TO_MEM) {
4975 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4976
4977 if (type_may_be_null(reg->type)) {
4978 verbose(env, "R%d invalid mem access '%s'\n", regno,
4979 reg_type_str(env, reg->type));
4980 return -EACCES;
4981 }
4982
4983 if (t == BPF_WRITE && rdonly_mem) {
4984 verbose(env, "R%d cannot write into %s\n",
4985 regno, reg_type_str(env, reg->type));
4986 return -EACCES;
4987 }
4988
457f4436
AN
4989 if (t == BPF_WRITE && value_regno >= 0 &&
4990 is_pointer_value(env, value_regno)) {
4991 verbose(env, "R%d leaks addr into mem\n", value_regno);
4992 return -EACCES;
4993 }
34d3a78c 4994
457f4436
AN
4995 err = check_mem_region_access(env, regno, off, size,
4996 reg->mem_size, false);
34d3a78c 4997 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
457f4436 4998 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 4999 } else if (reg->type == PTR_TO_CTX) {
f1174f77 5000 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 5001 struct btf *btf = NULL;
9e15db66 5002 u32 btf_id = 0;
19de99f7 5003
1be7f75d
AS
5004 if (t == BPF_WRITE && value_regno >= 0 &&
5005 is_pointer_value(env, value_regno)) {
61bd5218 5006 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
5007 return -EACCES;
5008 }
f1174f77 5009
be80a1d3 5010 err = check_ptr_off_reg(env, reg, regno);
58990d1f
DB
5011 if (err < 0)
5012 return err;
5013
c6f1bfe8
YS
5014 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5015 &btf_id);
9e15db66
AS
5016 if (err)
5017 verbose_linfo(env, insn_idx, "; ");
969bf05e 5018 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 5019 /* ctx access returns either a scalar, or a
de8f3a83
DB
5020 * PTR_TO_PACKET[_META,_END]. In the latter
5021 * case, we know the offset is zero.
f1174f77 5022 */
46f8bc92 5023 if (reg_type == SCALAR_VALUE) {
638f5b90 5024 mark_reg_unknown(env, regs, value_regno);
46f8bc92 5025 } else {
638f5b90 5026 mark_reg_known_zero(env, regs,
61bd5218 5027 value_regno);
c25b2ae1 5028 if (type_may_be_null(reg_type))
46f8bc92 5029 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
5030 /* A load of ctx field could have different
5031 * actual load size with the one encoded in the
5032 * insn. When the dst is PTR, it is for sure not
5033 * a sub-register.
5034 */
5035 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
c25b2ae1 5036 if (base_type(reg_type) == PTR_TO_BTF_ID) {
22dc4a0f 5037 regs[value_regno].btf = btf;
9e15db66 5038 regs[value_regno].btf_id = btf_id;
22dc4a0f 5039 }
46f8bc92 5040 }
638f5b90 5041 regs[value_regno].type = reg_type;
969bf05e 5042 }
17a52670 5043
f1174f77 5044 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
5045 /* Basic bounds checks. */
5046 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
5047 if (err)
5048 return err;
8726679a 5049
f4d7e40a
AS
5050 state = func(env, reg);
5051 err = update_stack_depth(env, state, off);
5052 if (err)
5053 return err;
8726679a 5054
01f810ac
AM
5055 if (t == BPF_READ)
5056 err = check_stack_read(env, regno, off, size,
61bd5218 5057 value_regno);
01f810ac
AM
5058 else
5059 err = check_stack_write(env, regno, off, size,
5060 value_regno, insn_idx);
de8f3a83 5061 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 5062 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 5063 verbose(env, "cannot write into packet\n");
969bf05e
AS
5064 return -EACCES;
5065 }
4acf6c0b
BB
5066 if (t == BPF_WRITE && value_regno >= 0 &&
5067 is_pointer_value(env, value_regno)) {
61bd5218
JK
5068 verbose(env, "R%d leaks addr into packet\n",
5069 value_regno);
4acf6c0b
BB
5070 return -EACCES;
5071 }
9fd29c08 5072 err = check_packet_access(env, regno, off, size, false);
969bf05e 5073 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 5074 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
5075 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5076 if (t == BPF_WRITE && value_regno >= 0 &&
5077 is_pointer_value(env, value_regno)) {
5078 verbose(env, "R%d leaks addr into flow keys\n",
5079 value_regno);
5080 return -EACCES;
5081 }
5082
5083 err = check_flow_keys_access(env, off, size);
5084 if (!err && t == BPF_READ && value_regno >= 0)
5085 mark_reg_unknown(env, regs, value_regno);
46f8bc92 5086 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 5087 if (t == BPF_WRITE) {
46f8bc92 5088 verbose(env, "R%d cannot write into %s\n",
c25b2ae1 5089 regno, reg_type_str(env, reg->type));
c64b7983
JS
5090 return -EACCES;
5091 }
5f456649 5092 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
5093 if (!err && value_regno >= 0)
5094 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
5095 } else if (reg->type == PTR_TO_TP_BUFFER) {
5096 err = check_tp_buffer_access(env, reg, regno, off, size);
5097 if (!err && t == BPF_READ && value_regno >= 0)
5098 mark_reg_unknown(env, regs, value_regno);
bff61f6f
HL
5099 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5100 !type_may_be_null(reg->type)) {
9e15db66
AS
5101 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5102 value_regno);
41c48f3a
AI
5103 } else if (reg->type == CONST_PTR_TO_MAP) {
5104 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5105 value_regno);
20b2aff4
HL
5106 } else if (base_type(reg->type) == PTR_TO_BUF) {
5107 bool rdonly_mem = type_is_rdonly_mem(reg->type);
20b2aff4
HL
5108 u32 *max_access;
5109
5110 if (rdonly_mem) {
5111 if (t == BPF_WRITE) {
5112 verbose(env, "R%d cannot write into %s\n",
5113 regno, reg_type_str(env, reg->type));
5114 return -EACCES;
5115 }
20b2aff4
HL
5116 max_access = &env->prog->aux->max_rdonly_access;
5117 } else {
20b2aff4 5118 max_access = &env->prog->aux->max_rdwr_access;
afbf21dc 5119 }
20b2aff4 5120
f6dfbe31 5121 err = check_buffer_access(env, reg, regno, off, size, false,
44e9a741 5122 max_access);
20b2aff4
HL
5123
5124 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
afbf21dc 5125 mark_reg_unknown(env, regs, value_regno);
17a52670 5126 } else {
61bd5218 5127 verbose(env, "R%d invalid mem access '%s'\n", regno,
c25b2ae1 5128 reg_type_str(env, reg->type));
17a52670
AS
5129 return -EACCES;
5130 }
969bf05e 5131
f1174f77 5132 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 5133 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 5134 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 5135 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 5136 }
17a52670
AS
5137 return err;
5138}
5139
91c960b0 5140static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 5141{
5ffa2550 5142 int load_reg;
17a52670
AS
5143 int err;
5144
5ca419f2
BJ
5145 switch (insn->imm) {
5146 case BPF_ADD:
5147 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
5148 case BPF_AND:
5149 case BPF_AND | BPF_FETCH:
5150 case BPF_OR:
5151 case BPF_OR | BPF_FETCH:
5152 case BPF_XOR:
5153 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
5154 case BPF_XCHG:
5155 case BPF_CMPXCHG:
5ca419f2
BJ
5156 break;
5157 default:
91c960b0
BJ
5158 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5159 return -EINVAL;
5160 }
5161
5162 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5163 verbose(env, "invalid atomic operand size\n");
17a52670
AS
5164 return -EINVAL;
5165 }
5166
5167 /* check src1 operand */
dc503a8a 5168 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
5169 if (err)
5170 return err;
5171
5172 /* check src2 operand */
dc503a8a 5173 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
5174 if (err)
5175 return err;
5176
5ffa2550
BJ
5177 if (insn->imm == BPF_CMPXCHG) {
5178 /* Check comparison of R0 with memory location */
a82fe085
DB
5179 const u32 aux_reg = BPF_REG_0;
5180
5181 err = check_reg_arg(env, aux_reg, SRC_OP);
5ffa2550
BJ
5182 if (err)
5183 return err;
a82fe085
DB
5184
5185 if (is_pointer_value(env, aux_reg)) {
5186 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5187 return -EACCES;
5188 }
5ffa2550
BJ
5189 }
5190
6bdf6abc 5191 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 5192 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
5193 return -EACCES;
5194 }
5195
ca369602 5196 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 5197 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
5198 is_flow_key_reg(env, insn->dst_reg) ||
5199 is_sk_reg(env, insn->dst_reg)) {
91c960b0 5200 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f 5201 insn->dst_reg,
c25b2ae1 5202 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
5203 return -EACCES;
5204 }
5205
37086bfd
BJ
5206 if (insn->imm & BPF_FETCH) {
5207 if (insn->imm == BPF_CMPXCHG)
5208 load_reg = BPF_REG_0;
5209 else
5210 load_reg = insn->src_reg;
5211
5212 /* check and record load of old value */
5213 err = check_reg_arg(env, load_reg, DST_OP);
5214 if (err)
5215 return err;
5216 } else {
5217 /* This instruction accesses a memory location but doesn't
5218 * actually load it into a register.
5219 */
5220 load_reg = -1;
5221 }
5222
7d3baf0a
DB
5223 /* Check whether we can read the memory, with second call for fetch
5224 * case to simulate the register fill.
5225 */
31fd8581 5226 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7d3baf0a
DB
5227 BPF_SIZE(insn->code), BPF_READ, -1, true);
5228 if (!err && load_reg >= 0)
5229 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5230 BPF_SIZE(insn->code), BPF_READ, load_reg,
5231 true);
17a52670
AS
5232 if (err)
5233 return err;
5234
7d3baf0a 5235 /* Check whether we can write into the same memory. */
5ca419f2
BJ
5236 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5237 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5238 if (err)
5239 return err;
5240
5ca419f2 5241 return 0;
17a52670
AS
5242}
5243
01f810ac
AM
5244/* When register 'regno' is used to read the stack (either directly or through
5245 * a helper function) make sure that it's within stack boundary and, depending
5246 * on the access type, that all elements of the stack are initialized.
5247 *
5248 * 'off' includes 'regno->off', but not its dynamic part (if any).
5249 *
5250 * All registers that have been spilled on the stack in the slots within the
5251 * read offsets are marked as read.
5252 */
5253static int check_stack_range_initialized(
5254 struct bpf_verifier_env *env, int regno, int off,
5255 int access_size, bool zero_size_allowed,
61df10c7 5256 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
5257{
5258 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
5259 struct bpf_func_state *state = func(env, reg);
5260 int err, min_off, max_off, i, j, slot, spi;
5261 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5262 enum bpf_access_type bounds_check_type;
5263 /* Some accesses can write anything into the stack, others are
5264 * read-only.
5265 */
5266 bool clobber = false;
2011fccf 5267
01f810ac
AM
5268 if (access_size == 0 && !zero_size_allowed) {
5269 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
5270 return -EACCES;
5271 }
2011fccf 5272
01f810ac
AM
5273 if (type == ACCESS_HELPER) {
5274 /* The bounds checks for writes are more permissive than for
5275 * reads. However, if raw_mode is not set, we'll do extra
5276 * checks below.
5277 */
5278 bounds_check_type = BPF_WRITE;
5279 clobber = true;
5280 } else {
5281 bounds_check_type = BPF_READ;
5282 }
5283 err = check_stack_access_within_bounds(env, regno, off, access_size,
5284 type, bounds_check_type);
5285 if (err)
5286 return err;
5287
17a52670 5288
2011fccf 5289 if (tnum_is_const(reg->var_off)) {
01f810ac 5290 min_off = max_off = reg->var_off.value + off;
2011fccf 5291 } else {
088ec26d
AI
5292 /* Variable offset is prohibited for unprivileged mode for
5293 * simplicity since it requires corresponding support in
5294 * Spectre masking for stack ALU.
5295 * See also retrieve_ptr_limit().
5296 */
2c78ee89 5297 if (!env->bypass_spec_v1) {
088ec26d 5298 char tn_buf[48];
f1174f77 5299
088ec26d 5300 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
5301 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5302 regno, err_extra, tn_buf);
088ec26d
AI
5303 return -EACCES;
5304 }
f2bcd05e
AI
5305 /* Only initialized buffer on stack is allowed to be accessed
5306 * with variable offset. With uninitialized buffer it's hard to
5307 * guarantee that whole memory is marked as initialized on
5308 * helper return since specific bounds are unknown what may
5309 * cause uninitialized stack leaking.
5310 */
5311 if (meta && meta->raw_mode)
5312 meta = NULL;
5313
01f810ac
AM
5314 min_off = reg->smin_value + off;
5315 max_off = reg->smax_value + off;
17a52670
AS
5316 }
5317
435faee1
DB
5318 if (meta && meta->raw_mode) {
5319 meta->access_size = access_size;
5320 meta->regno = regno;
5321 return 0;
5322 }
5323
2011fccf 5324 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
5325 u8 *stype;
5326
2011fccf 5327 slot = -i - 1;
638f5b90 5328 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
5329 if (state->allocated_stack <= slot)
5330 goto err;
5331 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5332 if (*stype == STACK_MISC)
5333 goto mark;
5334 if (*stype == STACK_ZERO) {
01f810ac
AM
5335 if (clobber) {
5336 /* helper can write anything into the stack */
5337 *stype = STACK_MISC;
5338 }
cc2b14d5 5339 goto mark;
17a52670 5340 }
1d68f22b 5341
27113c59 5342 if (is_spilled_reg(&state->stack[spi]) &&
cd17d38f
YS
5343 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5344 env->allow_ptr_leaks)) {
01f810ac
AM
5345 if (clobber) {
5346 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5347 for (j = 0; j < BPF_REG_SIZE; j++)
354e8f19 5348 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
01f810ac 5349 }
f7cf25b2
AS
5350 goto mark;
5351 }
5352
cc2b14d5 5353err:
2011fccf 5354 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
5355 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5356 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
5357 } else {
5358 char tn_buf[48];
5359
5360 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
5361 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5362 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 5363 }
cc2b14d5
AS
5364 return -EACCES;
5365mark:
5366 /* reading any byte out of 8-byte 'spill_slot' will cause
5367 * the whole slot to be marked as 'read'
5368 */
679c782d 5369 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
5370 state->stack[spi].spilled_ptr.parent,
5371 REG_LIVE_READ64);
261f4664
KKD
5372 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5373 * be sure that whether stack slot is written to or not. Hence,
5374 * we must still conservatively propagate reads upwards even if
5375 * helper may write to the entire memory range.
5376 */
17a52670 5377 }
2011fccf 5378 return update_stack_depth(env, state, min_off);
17a52670
AS
5379}
5380
06c1c049
GB
5381static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5382 int access_size, bool zero_size_allowed,
5383 struct bpf_call_arg_meta *meta)
5384{
638f5b90 5385 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
20b2aff4 5386 u32 *max_access;
06c1c049 5387
20b2aff4 5388 switch (base_type(reg->type)) {
06c1c049 5389 case PTR_TO_PACKET:
de8f3a83 5390 case PTR_TO_PACKET_META:
9fd29c08
YS
5391 return check_packet_access(env, regno, reg->off, access_size,
5392 zero_size_allowed);
69c087ba 5393 case PTR_TO_MAP_KEY:
7b3552d3
KKD
5394 if (meta && meta->raw_mode) {
5395 verbose(env, "R%d cannot write into %s\n", regno,
5396 reg_type_str(env, reg->type));
5397 return -EACCES;
5398 }
69c087ba
YS
5399 return check_mem_region_access(env, regno, reg->off, access_size,
5400 reg->map_ptr->key_size, false);
06c1c049 5401 case PTR_TO_MAP_VALUE:
591fe988
DB
5402 if (check_map_access_type(env, regno, reg->off, access_size,
5403 meta && meta->raw_mode ? BPF_WRITE :
5404 BPF_READ))
5405 return -EACCES;
9fd29c08 5406 return check_map_access(env, regno, reg->off, access_size,
61df10c7 5407 zero_size_allowed, ACCESS_HELPER);
457f4436 5408 case PTR_TO_MEM:
97e6d7da
KKD
5409 if (type_is_rdonly_mem(reg->type)) {
5410 if (meta && meta->raw_mode) {
5411 verbose(env, "R%d cannot write into %s\n", regno,
5412 reg_type_str(env, reg->type));
5413 return -EACCES;
5414 }
5415 }
457f4436
AN
5416 return check_mem_region_access(env, regno, reg->off,
5417 access_size, reg->mem_size,
5418 zero_size_allowed);
20b2aff4
HL
5419 case PTR_TO_BUF:
5420 if (type_is_rdonly_mem(reg->type)) {
97e6d7da
KKD
5421 if (meta && meta->raw_mode) {
5422 verbose(env, "R%d cannot write into %s\n", regno,
5423 reg_type_str(env, reg->type));
20b2aff4 5424 return -EACCES;
97e6d7da 5425 }
20b2aff4 5426
20b2aff4
HL
5427 max_access = &env->prog->aux->max_rdonly_access;
5428 } else {
20b2aff4
HL
5429 max_access = &env->prog->aux->max_rdwr_access;
5430 }
afbf21dc
YS
5431 return check_buffer_access(env, reg, regno, reg->off,
5432 access_size, zero_size_allowed,
44e9a741 5433 max_access);
0d004c02 5434 case PTR_TO_STACK:
01f810ac
AM
5435 return check_stack_range_initialized(
5436 env,
5437 regno, reg->off, access_size,
5438 zero_size_allowed, ACCESS_HELPER, meta);
15baa55f
BT
5439 case PTR_TO_CTX:
5440 /* in case the function doesn't know how to access the context,
5441 * (because we are in a program of type SYSCALL for example), we
5442 * can not statically check its size.
5443 * Dynamically check it now.
5444 */
5445 if (!env->ops->convert_ctx_access) {
5446 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5447 int offset = access_size - 1;
5448
5449 /* Allow zero-byte read from PTR_TO_CTX */
5450 if (access_size == 0)
5451 return zero_size_allowed ? 0 : -EACCES;
5452
5453 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5454 atype, -1, false);
5455 }
5456
5457 fallthrough;
0d004c02
LB
5458 default: /* scalar_value or invalid ptr */
5459 /* Allow zero-byte read from NULL, regardless of pointer type */
5460 if (zero_size_allowed && access_size == 0 &&
5461 register_is_null(reg))
5462 return 0;
5463
c25b2ae1
HL
5464 verbose(env, "R%d type=%s ", regno,
5465 reg_type_str(env, reg->type));
5466 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
0d004c02 5467 return -EACCES;
06c1c049
GB
5468 }
5469}
5470
d583691c
KKD
5471static int check_mem_size_reg(struct bpf_verifier_env *env,
5472 struct bpf_reg_state *reg, u32 regno,
5473 bool zero_size_allowed,
5474 struct bpf_call_arg_meta *meta)
5475{
5476 int err;
5477
5478 /* This is used to refine r0 return value bounds for helpers
5479 * that enforce this value as an upper bound on return values.
5480 * See do_refine_retval_range() for helpers that can refine
5481 * the return value. C type of helper is u32 so we pull register
5482 * bound from umax_value however, if negative verifier errors
5483 * out. Only upper bounds can be learned because retval is an
5484 * int type and negative retvals are allowed.
5485 */
be77354a 5486 meta->msize_max_value = reg->umax_value;
d583691c
KKD
5487
5488 /* The register is SCALAR_VALUE; the access check
5489 * happens using its boundaries.
5490 */
5491 if (!tnum_is_const(reg->var_off))
5492 /* For unprivileged variable accesses, disable raw
5493 * mode so that the program is required to
5494 * initialize all the memory that the helper could
5495 * just partially fill up.
5496 */
5497 meta = NULL;
5498
5499 if (reg->smin_value < 0) {
5500 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5501 regno);
5502 return -EACCES;
5503 }
5504
5505 if (reg->umin_value == 0) {
5506 err = check_helper_mem_access(env, regno - 1, 0,
5507 zero_size_allowed,
5508 meta);
5509 if (err)
5510 return err;
5511 }
5512
5513 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5514 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5515 regno);
5516 return -EACCES;
5517 }
5518 err = check_helper_mem_access(env, regno - 1,
5519 reg->umax_value,
5520 zero_size_allowed, meta);
5521 if (!err)
5522 err = mark_chain_precision(env, regno);
5523 return err;
5524}
5525
e5069b9c
DB
5526int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5527 u32 regno, u32 mem_size)
5528{
be77354a
KKD
5529 bool may_be_null = type_may_be_null(reg->type);
5530 struct bpf_reg_state saved_reg;
5531 struct bpf_call_arg_meta meta;
5532 int err;
5533
e5069b9c
DB
5534 if (register_is_null(reg))
5535 return 0;
5536
be77354a
KKD
5537 memset(&meta, 0, sizeof(meta));
5538 /* Assuming that the register contains a value check if the memory
5539 * access is safe. Temporarily save and restore the register's state as
5540 * the conversion shouldn't be visible to a caller.
5541 */
5542 if (may_be_null) {
5543 saved_reg = *reg;
e5069b9c 5544 mark_ptr_not_null_reg(reg);
e5069b9c
DB
5545 }
5546
be77354a
KKD
5547 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5548 /* Check access for BPF_WRITE */
5549 meta.raw_mode = true;
5550 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5551
5552 if (may_be_null)
5553 *reg = saved_reg;
5554
5555 return err;
e5069b9c
DB
5556}
5557
00b85860
KKD
5558static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5559 u32 regno)
d583691c
KKD
5560{
5561 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5562 bool may_be_null = type_may_be_null(mem_reg->type);
5563 struct bpf_reg_state saved_reg;
be77354a 5564 struct bpf_call_arg_meta meta;
d583691c
KKD
5565 int err;
5566
5567 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5568
be77354a
KKD
5569 memset(&meta, 0, sizeof(meta));
5570
d583691c
KKD
5571 if (may_be_null) {
5572 saved_reg = *mem_reg;
5573 mark_ptr_not_null_reg(mem_reg);
5574 }
5575
be77354a
KKD
5576 err = check_mem_size_reg(env, reg, regno, true, &meta);
5577 /* Check access for BPF_WRITE */
5578 meta.raw_mode = true;
5579 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
d583691c
KKD
5580
5581 if (may_be_null)
5582 *mem_reg = saved_reg;
5583 return err;
5584}
5585
d83525ca 5586/* Implementation details:
4e814da0
KKD
5587 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
5588 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
d83525ca 5589 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4e814da0
KKD
5590 * Two separate bpf_obj_new will also have different reg->id.
5591 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
5592 * clears reg->id after value_or_null->value transition, since the verifier only
5593 * cares about the range of access to valid map value pointer and doesn't care
5594 * about actual address of the map element.
d83525ca
AS
5595 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5596 * reg->id > 0 after value_or_null->value transition. By doing so
5597 * two bpf_map_lookups will be considered two different pointers that
4e814da0
KKD
5598 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
5599 * returned from bpf_obj_new.
d83525ca
AS
5600 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5601 * dead-locks.
5602 * Since only one bpf_spin_lock is allowed the checks are simpler than
5603 * reg_is_refcounted() logic. The verifier needs to remember only
5604 * one spin_lock instead of array of acquired_refs.
d0d78c1d 5605 * cur_state->active_lock remembers which map value element or allocated
4e814da0 5606 * object got locked and clears it after bpf_spin_unlock.
d83525ca
AS
5607 */
5608static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5609 bool is_lock)
5610{
5611 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5612 struct bpf_verifier_state *cur = env->cur_state;
5613 bool is_const = tnum_is_const(reg->var_off);
d83525ca 5614 u64 val = reg->var_off.value;
4e814da0
KKD
5615 struct bpf_map *map = NULL;
5616 struct btf *btf = NULL;
5617 struct btf_record *rec;
d83525ca 5618
d83525ca
AS
5619 if (!is_const) {
5620 verbose(env,
5621 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5622 regno);
5623 return -EINVAL;
5624 }
4e814da0
KKD
5625 if (reg->type == PTR_TO_MAP_VALUE) {
5626 map = reg->map_ptr;
5627 if (!map->btf) {
5628 verbose(env,
5629 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5630 map->name);
5631 return -EINVAL;
5632 }
5633 } else {
5634 btf = reg->btf;
d83525ca 5635 }
4e814da0
KKD
5636
5637 rec = reg_btf_record(reg);
5638 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
5639 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
5640 map ? map->name : "kptr");
d83525ca
AS
5641 return -EINVAL;
5642 }
4e814da0 5643 if (rec->spin_lock_off != val + reg->off) {
db559117 5644 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
4e814da0 5645 val + reg->off, rec->spin_lock_off);
d83525ca
AS
5646 return -EINVAL;
5647 }
5648 if (is_lock) {
d0d78c1d 5649 if (cur->active_lock.ptr) {
d83525ca
AS
5650 verbose(env,
5651 "Locking two bpf_spin_locks are not allowed\n");
5652 return -EINVAL;
5653 }
d0d78c1d
KKD
5654 if (map)
5655 cur->active_lock.ptr = map;
5656 else
5657 cur->active_lock.ptr = btf;
5658 cur->active_lock.id = reg->id;
d83525ca 5659 } else {
534e86bc 5660 struct bpf_func_state *fstate = cur_func(env);
d0d78c1d 5661 void *ptr;
534e86bc 5662 int i;
d0d78c1d
KKD
5663
5664 if (map)
5665 ptr = map;
5666 else
5667 ptr = btf;
5668
5669 if (!cur->active_lock.ptr) {
d83525ca
AS
5670 verbose(env, "bpf_spin_unlock without taking a lock\n");
5671 return -EINVAL;
5672 }
d0d78c1d
KKD
5673 if (cur->active_lock.ptr != ptr ||
5674 cur->active_lock.id != reg->id) {
d83525ca
AS
5675 verbose(env, "bpf_spin_unlock of different lock\n");
5676 return -EINVAL;
5677 }
d0d78c1d
KKD
5678 cur->active_lock.ptr = NULL;
5679 cur->active_lock.id = 0;
534e86bc
KKD
5680
5681 for (i = 0; i < fstate->acquired_refs; i++) {
5682 int err;
5683
5684 /* Complain on error because this reference state cannot
5685 * be freed before this point, as bpf_spin_lock critical
5686 * section does not allow functions that release the
5687 * allocated object immediately.
5688 */
5689 if (!fstate->refs[i].release_on_unlock)
5690 continue;
5691 err = release_reference(env, fstate->refs[i].id);
5692 if (err) {
5693 verbose(env, "failed to release release_on_unlock reference");
5694 return err;
5695 }
5696 }
d83525ca
AS
5697 }
5698 return 0;
5699}
5700
b00628b1
AS
5701static int process_timer_func(struct bpf_verifier_env *env, int regno,
5702 struct bpf_call_arg_meta *meta)
5703{
5704 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5705 bool is_const = tnum_is_const(reg->var_off);
5706 struct bpf_map *map = reg->map_ptr;
5707 u64 val = reg->var_off.value;
5708
5709 if (!is_const) {
5710 verbose(env,
5711 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5712 regno);
5713 return -EINVAL;
5714 }
5715 if (!map->btf) {
5716 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5717 map->name);
5718 return -EINVAL;
5719 }
db559117
KKD
5720 if (!btf_record_has_field(map->record, BPF_TIMER)) {
5721 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
68134668
AS
5722 return -EINVAL;
5723 }
db559117 5724 if (map->record->timer_off != val + reg->off) {
68134668 5725 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
db559117 5726 val + reg->off, map->record->timer_off);
b00628b1
AS
5727 return -EINVAL;
5728 }
5729 if (meta->map_ptr) {
5730 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5731 return -EFAULT;
5732 }
3e8ce298 5733 meta->map_uid = reg->map_uid;
b00628b1
AS
5734 meta->map_ptr = map;
5735 return 0;
5736}
5737
c0a5a21c
KKD
5738static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5739 struct bpf_call_arg_meta *meta)
5740{
5741 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
c0a5a21c 5742 struct bpf_map *map_ptr = reg->map_ptr;
aa3496ac 5743 struct btf_field *kptr_field;
c0a5a21c 5744 u32 kptr_off;
c0a5a21c
KKD
5745
5746 if (!tnum_is_const(reg->var_off)) {
5747 verbose(env,
5748 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5749 regno);
5750 return -EINVAL;
5751 }
5752 if (!map_ptr->btf) {
5753 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5754 map_ptr->name);
5755 return -EINVAL;
5756 }
aa3496ac
KKD
5757 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
5758 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
c0a5a21c
KKD
5759 return -EINVAL;
5760 }
5761
5762 meta->map_ptr = map_ptr;
5763 kptr_off = reg->off + reg->var_off.value;
aa3496ac
KKD
5764 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
5765 if (!kptr_field) {
c0a5a21c
KKD
5766 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5767 return -EACCES;
5768 }
aa3496ac 5769 if (kptr_field->type != BPF_KPTR_REF) {
c0a5a21c
KKD
5770 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5771 return -EACCES;
5772 }
aa3496ac 5773 meta->kptr_field = kptr_field;
c0a5a21c
KKD
5774 return 0;
5775}
5776
90133415
DB
5777static bool arg_type_is_mem_size(enum bpf_arg_type type)
5778{
5779 return type == ARG_CONST_SIZE ||
5780 type == ARG_CONST_SIZE_OR_ZERO;
5781}
5782
8f14852e
KKD
5783static bool arg_type_is_release(enum bpf_arg_type type)
5784{
5785 return type & OBJ_RELEASE;
5786}
5787
97e03f52
JK
5788static bool arg_type_is_dynptr(enum bpf_arg_type type)
5789{
5790 return base_type(type) == ARG_PTR_TO_DYNPTR;
5791}
5792
57c3bb72
AI
5793static int int_ptr_type_to_size(enum bpf_arg_type type)
5794{
5795 if (type == ARG_PTR_TO_INT)
5796 return sizeof(u32);
5797 else if (type == ARG_PTR_TO_LONG)
5798 return sizeof(u64);
5799
5800 return -EINVAL;
5801}
5802
912f442c
LB
5803static int resolve_map_arg_type(struct bpf_verifier_env *env,
5804 const struct bpf_call_arg_meta *meta,
5805 enum bpf_arg_type *arg_type)
5806{
5807 if (!meta->map_ptr) {
5808 /* kernel subsystem misconfigured verifier */
5809 verbose(env, "invalid map_ptr to access map->type\n");
5810 return -EACCES;
5811 }
5812
5813 switch (meta->map_ptr->map_type) {
5814 case BPF_MAP_TYPE_SOCKMAP:
5815 case BPF_MAP_TYPE_SOCKHASH:
5816 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 5817 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
5818 } else {
5819 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5820 return -EINVAL;
5821 }
5822 break;
9330986c
JK
5823 case BPF_MAP_TYPE_BLOOM_FILTER:
5824 if (meta->func_id == BPF_FUNC_map_peek_elem)
5825 *arg_type = ARG_PTR_TO_MAP_VALUE;
5826 break;
912f442c
LB
5827 default:
5828 break;
5829 }
5830 return 0;
5831}
5832
f79e7ea5
LB
5833struct bpf_reg_types {
5834 const enum bpf_reg_type types[10];
1df8f55a 5835 u32 *btf_id;
f79e7ea5
LB
5836};
5837
f79e7ea5
LB
5838static const struct bpf_reg_types sock_types = {
5839 .types = {
5840 PTR_TO_SOCK_COMMON,
5841 PTR_TO_SOCKET,
5842 PTR_TO_TCP_SOCK,
5843 PTR_TO_XDP_SOCK,
5844 },
5845};
5846
49a2a4d4 5847#ifdef CONFIG_NET
1df8f55a
MKL
5848static const struct bpf_reg_types btf_id_sock_common_types = {
5849 .types = {
5850 PTR_TO_SOCK_COMMON,
5851 PTR_TO_SOCKET,
5852 PTR_TO_TCP_SOCK,
5853 PTR_TO_XDP_SOCK,
5854 PTR_TO_BTF_ID,
3f00c523 5855 PTR_TO_BTF_ID | PTR_TRUSTED,
1df8f55a
MKL
5856 },
5857 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5858};
49a2a4d4 5859#endif
1df8f55a 5860
f79e7ea5
LB
5861static const struct bpf_reg_types mem_types = {
5862 .types = {
5863 PTR_TO_STACK,
5864 PTR_TO_PACKET,
5865 PTR_TO_PACKET_META,
69c087ba 5866 PTR_TO_MAP_KEY,
f79e7ea5
LB
5867 PTR_TO_MAP_VALUE,
5868 PTR_TO_MEM,
894f2a8b 5869 PTR_TO_MEM | MEM_RINGBUF,
20b2aff4 5870 PTR_TO_BUF,
f79e7ea5
LB
5871 },
5872};
5873
5874static const struct bpf_reg_types int_ptr_types = {
5875 .types = {
5876 PTR_TO_STACK,
5877 PTR_TO_PACKET,
5878 PTR_TO_PACKET_META,
69c087ba 5879 PTR_TO_MAP_KEY,
f79e7ea5
LB
5880 PTR_TO_MAP_VALUE,
5881 },
5882};
5883
4e814da0
KKD
5884static const struct bpf_reg_types spin_lock_types = {
5885 .types = {
5886 PTR_TO_MAP_VALUE,
5887 PTR_TO_BTF_ID | MEM_ALLOC,
5888 }
5889};
5890
f79e7ea5
LB
5891static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5892static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5893static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
894f2a8b 5894static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
f79e7ea5 5895static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
3f00c523
DV
5896static const struct bpf_reg_types btf_ptr_types = {
5897 .types = {
5898 PTR_TO_BTF_ID,
5899 PTR_TO_BTF_ID | PTR_TRUSTED,
5900 },
5901};
5902static const struct bpf_reg_types percpu_btf_ptr_types = {
5903 .types = {
5904 PTR_TO_BTF_ID | MEM_PERCPU,
5905 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
5906 }
5907};
69c087ba
YS
5908static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5909static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 5910static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
b00628b1 5911static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
c0a5a21c 5912static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
20571567
DV
5913static const struct bpf_reg_types dynptr_types = {
5914 .types = {
5915 PTR_TO_STACK,
5916 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5917 }
5918};
f79e7ea5 5919
0789e13b 5920static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
d1673304
DM
5921 [ARG_PTR_TO_MAP_KEY] = &mem_types,
5922 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
f79e7ea5
LB
5923 [ARG_CONST_SIZE] = &scalar_types,
5924 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5925 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5926 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5927 [ARG_PTR_TO_CTX] = &context_types,
f79e7ea5 5928 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 5929#ifdef CONFIG_NET
1df8f55a 5930 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 5931#endif
f79e7ea5 5932 [ARG_PTR_TO_SOCKET] = &fullsock_types,
f79e7ea5
LB
5933 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5934 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5935 [ARG_PTR_TO_MEM] = &mem_types,
894f2a8b 5936 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
f79e7ea5
LB
5937 [ARG_PTR_TO_INT] = &int_ptr_types,
5938 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 5939 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba 5940 [ARG_PTR_TO_FUNC] = &func_ptr_types,
48946bd6 5941 [ARG_PTR_TO_STACK] = &stack_ptr_types,
fff13c4b 5942 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
b00628b1 5943 [ARG_PTR_TO_TIMER] = &timer_types,
c0a5a21c 5944 [ARG_PTR_TO_KPTR] = &kptr_types,
20571567 5945 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
f79e7ea5
LB
5946};
5947
5948static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2 5949 enum bpf_arg_type arg_type,
c0a5a21c
KKD
5950 const u32 *arg_btf_id,
5951 struct bpf_call_arg_meta *meta)
f79e7ea5
LB
5952{
5953 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5954 enum bpf_reg_type expected, type = reg->type;
a968d5e2 5955 const struct bpf_reg_types *compatible;
f79e7ea5
LB
5956 int i, j;
5957
48946bd6 5958 compatible = compatible_reg_types[base_type(arg_type)];
a968d5e2
MKL
5959 if (!compatible) {
5960 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5961 return -EFAULT;
5962 }
5963
216e3cd2
HL
5964 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5965 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5966 *
5967 * Same for MAYBE_NULL:
5968 *
5969 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5970 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5971 *
5972 * Therefore we fold these flags depending on the arg_type before comparison.
5973 */
5974 if (arg_type & MEM_RDONLY)
5975 type &= ~MEM_RDONLY;
5976 if (arg_type & PTR_MAYBE_NULL)
5977 type &= ~PTR_MAYBE_NULL;
5978
f79e7ea5
LB
5979 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5980 expected = compatible->types[i];
5981 if (expected == NOT_INIT)
5982 break;
5983
5984 if (type == expected)
a968d5e2 5985 goto found;
f79e7ea5
LB
5986 }
5987
216e3cd2 5988 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
f79e7ea5 5989 for (j = 0; j + 1 < i; j++)
c25b2ae1
HL
5990 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5991 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
f79e7ea5 5992 return -EACCES;
a968d5e2
MKL
5993
5994found:
3f00c523 5995 if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) {
2ab3b380
KKD
5996 /* For bpf_sk_release, it needs to match against first member
5997 * 'struct sock_common', hence make an exception for it. This
5998 * allows bpf_sk_release to work for multiple socket types.
5999 */
6000 bool strict_type_match = arg_type_is_release(arg_type) &&
6001 meta->func_id != BPF_FUNC_sk_release;
6002
1df8f55a
MKL
6003 if (!arg_btf_id) {
6004 if (!compatible->btf_id) {
6005 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6006 return -EFAULT;
6007 }
6008 arg_btf_id = compatible->btf_id;
6009 }
6010
c0a5a21c 6011 if (meta->func_id == BPF_FUNC_kptr_xchg) {
aa3496ac 6012 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
c0a5a21c 6013 return -EACCES;
47e34cb7
DM
6014 } else {
6015 if (arg_btf_id == BPF_PTR_POISON) {
6016 verbose(env, "verifier internal error:");
6017 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6018 regno);
6019 return -EACCES;
6020 }
6021
6022 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6023 btf_vmlinux, *arg_btf_id,
6024 strict_type_match)) {
6025 verbose(env, "R%d is of type %s but %s is expected\n",
6026 regno, kernel_type_name(reg->btf, reg->btf_id),
6027 kernel_type_name(btf_vmlinux, *arg_btf_id));
6028 return -EACCES;
6029 }
a968d5e2 6030 }
4e814da0
KKD
6031 } else if (type_is_alloc(reg->type)) {
6032 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) {
6033 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
6034 return -EFAULT;
6035 }
a968d5e2
MKL
6036 }
6037
6038 return 0;
f79e7ea5
LB
6039}
6040
25b35dd2
KKD
6041int check_func_arg_reg_off(struct bpf_verifier_env *env,
6042 const struct bpf_reg_state *reg, int regno,
8f14852e 6043 enum bpf_arg_type arg_type)
25b35dd2
KKD
6044{
6045 enum bpf_reg_type type = reg->type;
8f14852e 6046 bool fixed_off_ok = false;
25b35dd2
KKD
6047
6048 switch ((u32)type) {
25b35dd2 6049 /* Pointer types where reg offset is explicitly allowed: */
97e03f52
JK
6050 case PTR_TO_STACK:
6051 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
6052 verbose(env, "cannot pass in dynptr at an offset\n");
6053 return -EINVAL;
6054 }
6055 fallthrough;
25b35dd2
KKD
6056 case PTR_TO_PACKET:
6057 case PTR_TO_PACKET_META:
6058 case PTR_TO_MAP_KEY:
6059 case PTR_TO_MAP_VALUE:
6060 case PTR_TO_MEM:
6061 case PTR_TO_MEM | MEM_RDONLY:
894f2a8b 6062 case PTR_TO_MEM | MEM_RINGBUF:
25b35dd2
KKD
6063 case PTR_TO_BUF:
6064 case PTR_TO_BUF | MEM_RDONLY:
97e03f52 6065 case SCALAR_VALUE:
25b35dd2
KKD
6066 /* Some of the argument types nevertheless require a
6067 * zero register offset.
6068 */
894f2a8b 6069 if (base_type(arg_type) != ARG_PTR_TO_RINGBUF_MEM)
25b35dd2
KKD
6070 return 0;
6071 break;
6072 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6073 * fixed offset.
6074 */
6075 case PTR_TO_BTF_ID:
282de143 6076 case PTR_TO_BTF_ID | MEM_ALLOC:
3f00c523
DV
6077 case PTR_TO_BTF_ID | PTR_TRUSTED:
6078 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
24d5bb80 6079 /* When referenced PTR_TO_BTF_ID is passed to release function,
8f14852e
KKD
6080 * it's fixed offset must be 0. In the other cases, fixed offset
6081 * can be non-zero.
24d5bb80 6082 */
8f14852e 6083 if (arg_type_is_release(arg_type) && reg->off) {
24d5bb80
KKD
6084 verbose(env, "R%d must have zero offset when passed to release func\n",
6085 regno);
6086 return -EINVAL;
6087 }
8f14852e
KKD
6088 /* For arg is release pointer, fixed_off_ok must be false, but
6089 * we already checked and rejected reg->off != 0 above, so set
6090 * to true to allow fixed offset for all other cases.
24d5bb80 6091 */
25b35dd2
KKD
6092 fixed_off_ok = true;
6093 break;
6094 default:
6095 break;
6096 }
6097 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
6098}
6099
34d4ef57
JK
6100static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6101{
6102 struct bpf_func_state *state = func(env, reg);
6103 int spi = get_spi(reg->off);
6104
6105 return state->stack[spi].spilled_ptr.id;
6106}
6107
af7ec138
YS
6108static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6109 struct bpf_call_arg_meta *meta,
6110 const struct bpf_func_proto *fn)
17a52670 6111{
af7ec138 6112 u32 regno = BPF_REG_1 + arg;
638f5b90 6113 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 6114 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 6115 enum bpf_reg_type type = reg->type;
508362ac 6116 u32 *arg_btf_id = NULL;
17a52670
AS
6117 int err = 0;
6118
80f1d68c 6119 if (arg_type == ARG_DONTCARE)
17a52670
AS
6120 return 0;
6121
dc503a8a
EC
6122 err = check_reg_arg(env, regno, SRC_OP);
6123 if (err)
6124 return err;
17a52670 6125
1be7f75d
AS
6126 if (arg_type == ARG_ANYTHING) {
6127 if (is_pointer_value(env, regno)) {
61bd5218
JK
6128 verbose(env, "R%d leaks addr into helper function\n",
6129 regno);
1be7f75d
AS
6130 return -EACCES;
6131 }
80f1d68c 6132 return 0;
1be7f75d 6133 }
80f1d68c 6134
de8f3a83 6135 if (type_is_pkt_pointer(type) &&
3a0af8fd 6136 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 6137 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
6138 return -EACCES;
6139 }
6140
16d1e00c 6141 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
912f442c
LB
6142 err = resolve_map_arg_type(env, meta, &arg_type);
6143 if (err)
6144 return err;
6145 }
6146
48946bd6 6147 if (register_is_null(reg) && type_may_be_null(arg_type))
fd1b0d60
LB
6148 /* A NULL register has a SCALAR_VALUE type, so skip
6149 * type checking.
6150 */
6151 goto skip_type_check;
6152
508362ac 6153 /* arg_btf_id and arg_size are in a union. */
4e814da0
KKD
6154 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
6155 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
508362ac
MM
6156 arg_btf_id = fn->arg_btf_id[arg];
6157
6158 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
f79e7ea5
LB
6159 if (err)
6160 return err;
6161
8f14852e 6162 err = check_func_arg_reg_off(env, reg, regno, arg_type);
25b35dd2
KKD
6163 if (err)
6164 return err;
d7b9454a 6165
fd1b0d60 6166skip_type_check:
8f14852e 6167 if (arg_type_is_release(arg_type)) {
bc34dee6
JK
6168 if (arg_type_is_dynptr(arg_type)) {
6169 struct bpf_func_state *state = func(env, reg);
6170 int spi = get_spi(reg->off);
6171
6172 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6173 !state->stack[spi].spilled_ptr.id) {
6174 verbose(env, "arg %d is an unacquired reference\n", regno);
6175 return -EINVAL;
6176 }
6177 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8f14852e
KKD
6178 verbose(env, "R%d must be referenced when passed to release function\n",
6179 regno);
6180 return -EINVAL;
6181 }
6182 if (meta->release_regno) {
6183 verbose(env, "verifier internal error: more than one release argument\n");
6184 return -EFAULT;
6185 }
6186 meta->release_regno = regno;
6187 }
6188
02f7c958 6189 if (reg->ref_obj_id) {
457f4436
AN
6190 if (meta->ref_obj_id) {
6191 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6192 regno, reg->ref_obj_id,
6193 meta->ref_obj_id);
6194 return -EFAULT;
6195 }
6196 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
6197 }
6198
8ab4cdcf
JK
6199 switch (base_type(arg_type)) {
6200 case ARG_CONST_MAP_PTR:
17a52670 6201 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3e8ce298
AS
6202 if (meta->map_ptr) {
6203 /* Use map_uid (which is unique id of inner map) to reject:
6204 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6205 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6206 * if (inner_map1 && inner_map2) {
6207 * timer = bpf_map_lookup_elem(inner_map1);
6208 * if (timer)
6209 * // mismatch would have been allowed
6210 * bpf_timer_init(timer, inner_map2);
6211 * }
6212 *
6213 * Comparing map_ptr is enough to distinguish normal and outer maps.
6214 */
6215 if (meta->map_ptr != reg->map_ptr ||
6216 meta->map_uid != reg->map_uid) {
6217 verbose(env,
6218 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6219 meta->map_uid, reg->map_uid);
6220 return -EINVAL;
6221 }
b00628b1 6222 }
33ff9823 6223 meta->map_ptr = reg->map_ptr;
3e8ce298 6224 meta->map_uid = reg->map_uid;
8ab4cdcf
JK
6225 break;
6226 case ARG_PTR_TO_MAP_KEY:
17a52670
AS
6227 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6228 * check that [key, key + map->key_size) are within
6229 * stack limits and initialized
6230 */
33ff9823 6231 if (!meta->map_ptr) {
17a52670
AS
6232 /* in function declaration map_ptr must come before
6233 * map_key, so that it's verified and known before
6234 * we have to check map_key here. Otherwise it means
6235 * that kernel subsystem misconfigured verifier
6236 */
61bd5218 6237 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
6238 return -EACCES;
6239 }
d71962f3
PC
6240 err = check_helper_mem_access(env, regno,
6241 meta->map_ptr->key_size, false,
6242 NULL);
8ab4cdcf
JK
6243 break;
6244 case ARG_PTR_TO_MAP_VALUE:
48946bd6
HL
6245 if (type_may_be_null(arg_type) && register_is_null(reg))
6246 return 0;
6247
17a52670
AS
6248 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6249 * check [value, value + map->value_size) validity
6250 */
33ff9823 6251 if (!meta->map_ptr) {
17a52670 6252 /* kernel subsystem misconfigured verifier */
61bd5218 6253 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
6254 return -EACCES;
6255 }
16d1e00c 6256 meta->raw_mode = arg_type & MEM_UNINIT;
d71962f3
PC
6257 err = check_helper_mem_access(env, regno,
6258 meta->map_ptr->value_size, false,
2ea864c5 6259 meta);
8ab4cdcf
JK
6260 break;
6261 case ARG_PTR_TO_PERCPU_BTF_ID:
eaa6bcb7
HL
6262 if (!reg->btf_id) {
6263 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6264 return -EACCES;
6265 }
22dc4a0f 6266 meta->ret_btf = reg->btf;
eaa6bcb7 6267 meta->ret_btf_id = reg->btf_id;
8ab4cdcf
JK
6268 break;
6269 case ARG_PTR_TO_SPIN_LOCK:
c18f0b6a
LB
6270 if (meta->func_id == BPF_FUNC_spin_lock) {
6271 if (process_spin_lock(env, regno, true))
6272 return -EACCES;
6273 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6274 if (process_spin_lock(env, regno, false))
6275 return -EACCES;
6276 } else {
6277 verbose(env, "verifier internal error\n");
6278 return -EFAULT;
6279 }
8ab4cdcf
JK
6280 break;
6281 case ARG_PTR_TO_TIMER:
b00628b1
AS
6282 if (process_timer_func(env, regno, meta))
6283 return -EACCES;
8ab4cdcf
JK
6284 break;
6285 case ARG_PTR_TO_FUNC:
69c087ba 6286 meta->subprogno = reg->subprogno;
8ab4cdcf
JK
6287 break;
6288 case ARG_PTR_TO_MEM:
a2bbe7cc
LB
6289 /* The access to this pointer is only checked when we hit the
6290 * next is_mem_size argument below.
6291 */
16d1e00c 6292 meta->raw_mode = arg_type & MEM_UNINIT;
508362ac
MM
6293 if (arg_type & MEM_FIXED_SIZE) {
6294 err = check_helper_mem_access(env, regno,
6295 fn->arg_size[arg], false,
6296 meta);
6297 }
8ab4cdcf
JK
6298 break;
6299 case ARG_CONST_SIZE:
6300 err = check_mem_size_reg(env, reg, regno, false, meta);
6301 break;
6302 case ARG_CONST_SIZE_OR_ZERO:
6303 err = check_mem_size_reg(env, reg, regno, true, meta);
6304 break;
6305 case ARG_PTR_TO_DYNPTR:
20571567
DV
6306 /* We only need to check for initialized / uninitialized helper
6307 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6308 * assumption is that if it is, that a helper function
6309 * initialized the dynptr on behalf of the BPF program.
6310 */
6311 if (base_type(reg->type) == PTR_TO_DYNPTR)
6312 break;
97e03f52
JK
6313 if (arg_type & MEM_UNINIT) {
6314 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6315 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6316 return -EINVAL;
6317 }
6318
6319 /* We only support one dynptr being uninitialized at the moment,
6320 * which is sufficient for the helper functions we have right now.
6321 */
6322 if (meta->uninit_dynptr_regno) {
6323 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6324 return -EFAULT;
6325 }
6326
6327 meta->uninit_dynptr_regno = regno;
e9e315b4
RS
6328 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6329 verbose(env,
6330 "Expected an initialized dynptr as arg #%d\n",
6331 arg + 1);
6332 return -EINVAL;
6333 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
97e03f52
JK
6334 const char *err_extra = "";
6335
6336 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6337 case DYNPTR_TYPE_LOCAL:
e9e315b4 6338 err_extra = "local";
97e03f52 6339 break;
bc34dee6 6340 case DYNPTR_TYPE_RINGBUF:
e9e315b4 6341 err_extra = "ringbuf";
bc34dee6 6342 break;
97e03f52 6343 default:
e9e315b4 6344 err_extra = "<unknown>";
97e03f52
JK
6345 break;
6346 }
e9e315b4
RS
6347 verbose(env,
6348 "Expected a dynptr of type %s as arg #%d\n",
97e03f52
JK
6349 err_extra, arg + 1);
6350 return -EINVAL;
6351 }
8ab4cdcf
JK
6352 break;
6353 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
457f4436 6354 if (!tnum_is_const(reg->var_off)) {
28a8add6 6355 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
6356 regno);
6357 return -EACCES;
6358 }
6359 meta->mem_size = reg->var_off.value;
2fc31465
KKD
6360 err = mark_chain_precision(env, regno);
6361 if (err)
6362 return err;
8ab4cdcf
JK
6363 break;
6364 case ARG_PTR_TO_INT:
6365 case ARG_PTR_TO_LONG:
6366 {
57c3bb72
AI
6367 int size = int_ptr_type_to_size(arg_type);
6368
6369 err = check_helper_mem_access(env, regno, size, false, meta);
6370 if (err)
6371 return err;
6372 err = check_ptr_alignment(env, reg, 0, size, true);
8ab4cdcf
JK
6373 break;
6374 }
6375 case ARG_PTR_TO_CONST_STR:
6376 {
fff13c4b
FR
6377 struct bpf_map *map = reg->map_ptr;
6378 int map_off;
6379 u64 map_addr;
6380 char *str_ptr;
6381
a8fad73e 6382 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
6383 verbose(env, "R%d does not point to a readonly map'\n", regno);
6384 return -EACCES;
6385 }
6386
6387 if (!tnum_is_const(reg->var_off)) {
6388 verbose(env, "R%d is not a constant address'\n", regno);
6389 return -EACCES;
6390 }
6391
6392 if (!map->ops->map_direct_value_addr) {
6393 verbose(env, "no direct value access support for this map type\n");
6394 return -EACCES;
6395 }
6396
6397 err = check_map_access(env, regno, reg->off,
61df10c7
KKD
6398 map->value_size - reg->off, false,
6399 ACCESS_HELPER);
fff13c4b
FR
6400 if (err)
6401 return err;
6402
6403 map_off = reg->off + reg->var_off.value;
6404 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6405 if (err) {
6406 verbose(env, "direct value access on string failed\n");
6407 return err;
6408 }
6409
6410 str_ptr = (char *)(long)(map_addr);
6411 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6412 verbose(env, "string is not zero-terminated\n");
6413 return -EINVAL;
6414 }
8ab4cdcf
JK
6415 break;
6416 }
6417 case ARG_PTR_TO_KPTR:
c0a5a21c
KKD
6418 if (process_kptr_func(env, regno, meta))
6419 return -EACCES;
8ab4cdcf 6420 break;
17a52670
AS
6421 }
6422
6423 return err;
6424}
6425
0126240f
LB
6426static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6427{
6428 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 6429 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
6430
6431 if (func_id != BPF_FUNC_map_update_elem)
6432 return false;
6433
6434 /* It's not possible to get access to a locked struct sock in these
6435 * contexts, so updating is safe.
6436 */
6437 switch (type) {
6438 case BPF_PROG_TYPE_TRACING:
6439 if (eatype == BPF_TRACE_ITER)
6440 return true;
6441 break;
6442 case BPF_PROG_TYPE_SOCKET_FILTER:
6443 case BPF_PROG_TYPE_SCHED_CLS:
6444 case BPF_PROG_TYPE_SCHED_ACT:
6445 case BPF_PROG_TYPE_XDP:
6446 case BPF_PROG_TYPE_SK_REUSEPORT:
6447 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6448 case BPF_PROG_TYPE_SK_LOOKUP:
6449 return true;
6450 default:
6451 break;
6452 }
6453
6454 verbose(env, "cannot update sockmap in this context\n");
6455 return false;
6456}
6457
e411901c
MF
6458static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6459{
95acd881
TA
6460 return env->prog->jit_requested &&
6461 bpf_jit_supports_subprog_tailcalls();
e411901c
MF
6462}
6463
61bd5218
JK
6464static int check_map_func_compatibility(struct bpf_verifier_env *env,
6465 struct bpf_map *map, int func_id)
35578d79 6466{
35578d79
KX
6467 if (!map)
6468 return 0;
6469
6aff67c8
AS
6470 /* We need a two way check, first is from map perspective ... */
6471 switch (map->map_type) {
6472 case BPF_MAP_TYPE_PROG_ARRAY:
6473 if (func_id != BPF_FUNC_tail_call)
6474 goto error;
6475 break;
6476 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6477 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 6478 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 6479 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
6480 func_id != BPF_FUNC_perf_event_read_value &&
6481 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
6482 goto error;
6483 break;
457f4436
AN
6484 case BPF_MAP_TYPE_RINGBUF:
6485 if (func_id != BPF_FUNC_ringbuf_output &&
6486 func_id != BPF_FUNC_ringbuf_reserve &&
bc34dee6
JK
6487 func_id != BPF_FUNC_ringbuf_query &&
6488 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6489 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6490 func_id != BPF_FUNC_ringbuf_discard_dynptr)
457f4436
AN
6491 goto error;
6492 break;
583c1f42 6493 case BPF_MAP_TYPE_USER_RINGBUF:
20571567
DV
6494 if (func_id != BPF_FUNC_user_ringbuf_drain)
6495 goto error;
6496 break;
6aff67c8
AS
6497 case BPF_MAP_TYPE_STACK_TRACE:
6498 if (func_id != BPF_FUNC_get_stackid)
6499 goto error;
6500 break;
4ed8ec52 6501 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 6502 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 6503 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
6504 goto error;
6505 break;
cd339431 6506 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 6507 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
6508 if (func_id != BPF_FUNC_get_local_storage)
6509 goto error;
6510 break;
546ac1ff 6511 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 6512 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
6513 if (func_id != BPF_FUNC_redirect_map &&
6514 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
6515 goto error;
6516 break;
fbfc504a
BT
6517 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6518 * appear.
6519 */
6710e112
JDB
6520 case BPF_MAP_TYPE_CPUMAP:
6521 if (func_id != BPF_FUNC_redirect_map)
6522 goto error;
6523 break;
fada7fdc
JL
6524 case BPF_MAP_TYPE_XSKMAP:
6525 if (func_id != BPF_FUNC_redirect_map &&
6526 func_id != BPF_FUNC_map_lookup_elem)
6527 goto error;
6528 break;
56f668df 6529 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 6530 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
6531 if (func_id != BPF_FUNC_map_lookup_elem)
6532 goto error;
16a43625 6533 break;
174a79ff
JF
6534 case BPF_MAP_TYPE_SOCKMAP:
6535 if (func_id != BPF_FUNC_sk_redirect_map &&
6536 func_id != BPF_FUNC_sock_map_update &&
4f738adb 6537 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 6538 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 6539 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
6540 func_id != BPF_FUNC_map_lookup_elem &&
6541 !may_update_sockmap(env, func_id))
174a79ff
JF
6542 goto error;
6543 break;
81110384
JF
6544 case BPF_MAP_TYPE_SOCKHASH:
6545 if (func_id != BPF_FUNC_sk_redirect_hash &&
6546 func_id != BPF_FUNC_sock_hash_update &&
6547 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 6548 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 6549 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
6550 func_id != BPF_FUNC_map_lookup_elem &&
6551 !may_update_sockmap(env, func_id))
81110384
JF
6552 goto error;
6553 break;
2dbb9b9e
MKL
6554 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6555 if (func_id != BPF_FUNC_sk_select_reuseport)
6556 goto error;
6557 break;
f1a2e44a
MV
6558 case BPF_MAP_TYPE_QUEUE:
6559 case BPF_MAP_TYPE_STACK:
6560 if (func_id != BPF_FUNC_map_peek_elem &&
6561 func_id != BPF_FUNC_map_pop_elem &&
6562 func_id != BPF_FUNC_map_push_elem)
6563 goto error;
6564 break;
6ac99e8f
MKL
6565 case BPF_MAP_TYPE_SK_STORAGE:
6566 if (func_id != BPF_FUNC_sk_storage_get &&
6567 func_id != BPF_FUNC_sk_storage_delete)
6568 goto error;
6569 break;
8ea63684
KS
6570 case BPF_MAP_TYPE_INODE_STORAGE:
6571 if (func_id != BPF_FUNC_inode_storage_get &&
6572 func_id != BPF_FUNC_inode_storage_delete)
6573 goto error;
6574 break;
4cf1bc1f
KS
6575 case BPF_MAP_TYPE_TASK_STORAGE:
6576 if (func_id != BPF_FUNC_task_storage_get &&
6577 func_id != BPF_FUNC_task_storage_delete)
6578 goto error;
6579 break;
c4bcfb38
YS
6580 case BPF_MAP_TYPE_CGRP_STORAGE:
6581 if (func_id != BPF_FUNC_cgrp_storage_get &&
6582 func_id != BPF_FUNC_cgrp_storage_delete)
6583 goto error;
6584 break;
9330986c
JK
6585 case BPF_MAP_TYPE_BLOOM_FILTER:
6586 if (func_id != BPF_FUNC_map_peek_elem &&
6587 func_id != BPF_FUNC_map_push_elem)
6588 goto error;
6589 break;
6aff67c8
AS
6590 default:
6591 break;
6592 }
6593
6594 /* ... and second from the function itself. */
6595 switch (func_id) {
6596 case BPF_FUNC_tail_call:
6597 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6598 goto error;
e411901c
MF
6599 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6600 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
6601 return -EINVAL;
6602 }
6aff67c8
AS
6603 break;
6604 case BPF_FUNC_perf_event_read:
6605 case BPF_FUNC_perf_event_output:
908432ca 6606 case BPF_FUNC_perf_event_read_value:
a7658e1a 6607 case BPF_FUNC_skb_output:
d831ee84 6608 case BPF_FUNC_xdp_output:
6aff67c8
AS
6609 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6610 goto error;
6611 break;
5b029a32
DB
6612 case BPF_FUNC_ringbuf_output:
6613 case BPF_FUNC_ringbuf_reserve:
6614 case BPF_FUNC_ringbuf_query:
bc34dee6
JK
6615 case BPF_FUNC_ringbuf_reserve_dynptr:
6616 case BPF_FUNC_ringbuf_submit_dynptr:
6617 case BPF_FUNC_ringbuf_discard_dynptr:
5b029a32
DB
6618 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6619 goto error;
6620 break;
20571567
DV
6621 case BPF_FUNC_user_ringbuf_drain:
6622 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6623 goto error;
6624 break;
6aff67c8
AS
6625 case BPF_FUNC_get_stackid:
6626 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6627 goto error;
6628 break;
60d20f91 6629 case BPF_FUNC_current_task_under_cgroup:
747ea55e 6630 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
6631 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6632 goto error;
6633 break;
97f91a7c 6634 case BPF_FUNC_redirect_map:
9c270af3 6635 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 6636 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
6637 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6638 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
6639 goto error;
6640 break;
174a79ff 6641 case BPF_FUNC_sk_redirect_map:
4f738adb 6642 case BPF_FUNC_msg_redirect_map:
81110384 6643 case BPF_FUNC_sock_map_update:
174a79ff
JF
6644 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6645 goto error;
6646 break;
81110384
JF
6647 case BPF_FUNC_sk_redirect_hash:
6648 case BPF_FUNC_msg_redirect_hash:
6649 case BPF_FUNC_sock_hash_update:
6650 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
6651 goto error;
6652 break;
cd339431 6653 case BPF_FUNC_get_local_storage:
b741f163
RG
6654 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6655 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
6656 goto error;
6657 break;
2dbb9b9e 6658 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
6659 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6660 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6661 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
6662 goto error;
6663 break;
f1a2e44a 6664 case BPF_FUNC_map_pop_elem:
f1a2e44a
MV
6665 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6666 map->map_type != BPF_MAP_TYPE_STACK)
6667 goto error;
6668 break;
9330986c
JK
6669 case BPF_FUNC_map_peek_elem:
6670 case BPF_FUNC_map_push_elem:
6671 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6672 map->map_type != BPF_MAP_TYPE_STACK &&
6673 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6674 goto error;
6675 break;
07343110
FZ
6676 case BPF_FUNC_map_lookup_percpu_elem:
6677 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6678 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6679 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6680 goto error;
6681 break;
6ac99e8f
MKL
6682 case BPF_FUNC_sk_storage_get:
6683 case BPF_FUNC_sk_storage_delete:
6684 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6685 goto error;
6686 break;
8ea63684
KS
6687 case BPF_FUNC_inode_storage_get:
6688 case BPF_FUNC_inode_storage_delete:
6689 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6690 goto error;
6691 break;
4cf1bc1f
KS
6692 case BPF_FUNC_task_storage_get:
6693 case BPF_FUNC_task_storage_delete:
6694 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6695 goto error;
6696 break;
c4bcfb38
YS
6697 case BPF_FUNC_cgrp_storage_get:
6698 case BPF_FUNC_cgrp_storage_delete:
6699 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
6700 goto error;
6701 break;
6aff67c8
AS
6702 default:
6703 break;
35578d79
KX
6704 }
6705
6706 return 0;
6aff67c8 6707error:
61bd5218 6708 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 6709 map->map_type, func_id_name(func_id), func_id);
6aff67c8 6710 return -EINVAL;
35578d79
KX
6711}
6712
90133415 6713static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
6714{
6715 int count = 0;
6716
39f19ebb 6717 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 6718 count++;
39f19ebb 6719 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 6720 count++;
39f19ebb 6721 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 6722 count++;
39f19ebb 6723 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 6724 count++;
39f19ebb 6725 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
6726 count++;
6727
90133415
DB
6728 /* We only support one arg being in raw mode at the moment,
6729 * which is sufficient for the helper functions we have
6730 * right now.
6731 */
6732 return count <= 1;
6733}
6734
508362ac 6735static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
90133415 6736{
508362ac
MM
6737 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6738 bool has_size = fn->arg_size[arg] != 0;
6739 bool is_next_size = false;
6740
6741 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6742 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6743
6744 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6745 return is_next_size;
6746
6747 return has_size == is_next_size || is_next_size == is_fixed;
90133415
DB
6748}
6749
6750static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6751{
6752 /* bpf_xxx(..., buf, len) call will access 'len'
6753 * bytes from memory 'buf'. Both arg types need
6754 * to be paired, so make sure there's no buggy
6755 * helper function specification.
6756 */
6757 if (arg_type_is_mem_size(fn->arg1_type) ||
508362ac
MM
6758 check_args_pair_invalid(fn, 0) ||
6759 check_args_pair_invalid(fn, 1) ||
6760 check_args_pair_invalid(fn, 2) ||
6761 check_args_pair_invalid(fn, 3) ||
6762 check_args_pair_invalid(fn, 4))
90133415
DB
6763 return false;
6764
6765 return true;
6766}
6767
9436ef6e
LB
6768static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6769{
6770 int i;
6771
1df8f55a 6772 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4e814da0
KKD
6773 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
6774 return !!fn->arg_btf_id[i];
6775 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
6776 return fn->arg_btf_id[i] == BPF_PTR_POISON;
508362ac
MM
6777 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6778 /* arg_btf_id and arg_size are in a union. */
6779 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6780 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
1df8f55a
MKL
6781 return false;
6782 }
6783
9436ef6e
LB
6784 return true;
6785}
6786
0c9a7a7e 6787static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
6788{
6789 return check_raw_mode_ok(fn) &&
fd978bf7 6790 check_arg_pair_ok(fn) &&
b2d8ef19 6791 check_btf_id_ok(fn) ? 0 : -EINVAL;
435faee1
DB
6792}
6793
de8f3a83
DB
6794/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6795 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 6796 */
b239da34 6797static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 6798{
b239da34
KKD
6799 struct bpf_func_state *state;
6800 struct bpf_reg_state *reg;
969bf05e 6801
b239da34 6802 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
de8f3a83 6803 if (reg_is_pkt_pointer_any(reg))
f54c7898 6804 __mark_reg_unknown(env, reg);
b239da34 6805 }));
f4d7e40a
AS
6806}
6807
6d94e741
AS
6808enum {
6809 AT_PKT_END = -1,
6810 BEYOND_PKT_END = -2,
6811};
6812
6813static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6814{
6815 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6816 struct bpf_reg_state *reg = &state->regs[regn];
6817
6818 if (reg->type != PTR_TO_PACKET)
6819 /* PTR_TO_PACKET_META is not supported yet */
6820 return;
6821
6822 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6823 * How far beyond pkt_end it goes is unknown.
6824 * if (!range_open) it's the case of pkt >= pkt_end
6825 * if (range_open) it's the case of pkt > pkt_end
6826 * hence this pointer is at least 1 byte bigger than pkt_end
6827 */
6828 if (range_open)
6829 reg->range = BEYOND_PKT_END;
6830 else
6831 reg->range = AT_PKT_END;
6832}
6833
fd978bf7
JS
6834/* The pointer with the specified id has released its reference to kernel
6835 * resources. Identify all copies of the same pointer and clear the reference.
6836 */
6837static int release_reference(struct bpf_verifier_env *env,
1b986589 6838 int ref_obj_id)
fd978bf7 6839{
b239da34
KKD
6840 struct bpf_func_state *state;
6841 struct bpf_reg_state *reg;
1b986589 6842 int err;
fd978bf7 6843
1b986589
MKL
6844 err = release_reference_state(cur_func(env), ref_obj_id);
6845 if (err)
6846 return err;
6847
b239da34 6848 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
f1db2081
YL
6849 if (reg->ref_obj_id == ref_obj_id) {
6850 if (!env->allow_ptr_leaks)
6851 __mark_reg_not_init(env, reg);
6852 else
6853 __mark_reg_unknown(env, reg);
6854 }
b239da34 6855 }));
fd978bf7 6856
1b986589 6857 return 0;
fd978bf7
JS
6858}
6859
51c39bb1
AS
6860static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6861 struct bpf_reg_state *regs)
6862{
6863 int i;
6864
6865 /* after the call registers r0 - r5 were scratched */
6866 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6867 mark_reg_not_init(env, regs, caller_saved[i]);
6868 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6869 }
6870}
6871
14351375
YS
6872typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6873 struct bpf_func_state *caller,
6874 struct bpf_func_state *callee,
6875 int insn_idx);
6876
be2ef816
AN
6877static int set_callee_state(struct bpf_verifier_env *env,
6878 struct bpf_func_state *caller,
6879 struct bpf_func_state *callee, int insn_idx);
6880
14351375
YS
6881static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6882 int *insn_idx, int subprog,
6883 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
6884{
6885 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 6886 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 6887 struct bpf_func_state *caller, *callee;
14351375 6888 int err;
51c39bb1 6889 bool is_global = false;
f4d7e40a 6890
aada9ce6 6891 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 6892 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 6893 state->curframe + 2);
f4d7e40a
AS
6894 return -E2BIG;
6895 }
6896
f4d7e40a
AS
6897 caller = state->frame[state->curframe];
6898 if (state->frame[state->curframe + 1]) {
6899 verbose(env, "verifier bug. Frame %d already allocated\n",
6900 state->curframe + 1);
6901 return -EFAULT;
6902 }
6903
51c39bb1
AS
6904 func_info_aux = env->prog->aux->func_info_aux;
6905 if (func_info_aux)
6906 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
95f2f26f 6907 err = btf_check_subprog_call(env, subprog, caller->regs);
51c39bb1
AS
6908 if (err == -EFAULT)
6909 return err;
6910 if (is_global) {
6911 if (err) {
6912 verbose(env, "Caller passes invalid args into func#%d\n",
6913 subprog);
6914 return err;
6915 } else {
6916 if (env->log.level & BPF_LOG_LEVEL)
6917 verbose(env,
6918 "Func#%d is global and valid. Skipping.\n",
6919 subprog);
6920 clear_caller_saved_regs(env, caller->regs);
6921
45159b27 6922 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 6923 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 6924 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
6925
6926 /* continue with next insn after call */
6927 return 0;
6928 }
6929 }
6930
be2ef816
AN
6931 /* set_callee_state is used for direct subprog calls, but we are
6932 * interested in validating only BPF helpers that can call subprogs as
6933 * callbacks
6934 */
6935 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6936 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6937 func_id_name(insn->imm), insn->imm);
6938 return -EFAULT;
6939 }
6940
bfc6bb74 6941 if (insn->code == (BPF_JMP | BPF_CALL) &&
a5bebc4f 6942 insn->src_reg == 0 &&
bfc6bb74
AS
6943 insn->imm == BPF_FUNC_timer_set_callback) {
6944 struct bpf_verifier_state *async_cb;
6945
6946 /* there is no real recursion here. timer callbacks are async */
7ddc80a4 6947 env->subprog_info[subprog].is_async_cb = true;
bfc6bb74
AS
6948 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6949 *insn_idx, subprog);
6950 if (!async_cb)
6951 return -EFAULT;
6952 callee = async_cb->frame[0];
6953 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6954
6955 /* Convert bpf_timer_set_callback() args into timer callback args */
6956 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6957 if (err)
6958 return err;
6959
6960 clear_caller_saved_regs(env, caller->regs);
6961 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6962 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6963 /* continue with next insn after call */
6964 return 0;
6965 }
6966
f4d7e40a
AS
6967 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6968 if (!callee)
6969 return -ENOMEM;
6970 state->frame[state->curframe + 1] = callee;
6971
6972 /* callee cannot access r0, r6 - r9 for reading and has to write
6973 * into its own stack before reading from it.
6974 * callee can read/write into caller's stack
6975 */
6976 init_func_state(env, callee,
6977 /* remember the callsite, it will be used by bpf_exit */
6978 *insn_idx /* callsite */,
6979 state->curframe + 1 /* frameno within this callchain */,
f910cefa 6980 subprog /* subprog number within this prog */);
f4d7e40a 6981
fd978bf7 6982 /* Transfer references to the callee */
c69431aa 6983 err = copy_reference_state(callee, caller);
fd978bf7
JS
6984 if (err)
6985 return err;
6986
14351375
YS
6987 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6988 if (err)
6989 return err;
f4d7e40a 6990
51c39bb1 6991 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
6992
6993 /* only increment it after check_reg_arg() finished */
6994 state->curframe++;
6995
6996 /* and go analyze first insn of the callee */
14351375 6997 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 6998
06ee7115 6999 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 7000 verbose(env, "caller:\n");
0f55f9ed 7001 print_verifier_state(env, caller, true);
f4d7e40a 7002 verbose(env, "callee:\n");
0f55f9ed 7003 print_verifier_state(env, callee, true);
f4d7e40a
AS
7004 }
7005 return 0;
7006}
7007
314ee05e
YS
7008int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7009 struct bpf_func_state *caller,
7010 struct bpf_func_state *callee)
7011{
7012 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7013 * void *callback_ctx, u64 flags);
7014 * callback_fn(struct bpf_map *map, void *key, void *value,
7015 * void *callback_ctx);
7016 */
7017 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7018
7019 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7020 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7021 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7022
7023 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7024 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7025 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7026
7027 /* pointer to stack or null */
7028 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7029
7030 /* unused */
7031 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7032 return 0;
7033}
7034
14351375
YS
7035static int set_callee_state(struct bpf_verifier_env *env,
7036 struct bpf_func_state *caller,
7037 struct bpf_func_state *callee, int insn_idx)
7038{
7039 int i;
7040
7041 /* copy r1 - r5 args that callee can access. The copy includes parent
7042 * pointers, which connects us up to the liveness chain
7043 */
7044 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7045 callee->regs[i] = caller->regs[i];
7046 return 0;
7047}
7048
7049static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7050 int *insn_idx)
7051{
7052 int subprog, target_insn;
7053
7054 target_insn = *insn_idx + insn->imm + 1;
7055 subprog = find_subprog(env, target_insn);
7056 if (subprog < 0) {
7057 verbose(env, "verifier bug. No program starts at insn %d\n",
7058 target_insn);
7059 return -EFAULT;
7060 }
7061
7062 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7063}
7064
69c087ba
YS
7065static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7066 struct bpf_func_state *caller,
7067 struct bpf_func_state *callee,
7068 int insn_idx)
7069{
7070 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7071 struct bpf_map *map;
7072 int err;
7073
7074 if (bpf_map_ptr_poisoned(insn_aux)) {
7075 verbose(env, "tail_call abusing map_ptr\n");
7076 return -EINVAL;
7077 }
7078
7079 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7080 if (!map->ops->map_set_for_each_callback_args ||
7081 !map->ops->map_for_each_callback) {
7082 verbose(env, "callback function not allowed for map\n");
7083 return -ENOTSUPP;
7084 }
7085
7086 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7087 if (err)
7088 return err;
7089
7090 callee->in_callback_fn = true;
1bfe26fb 7091 callee->callback_ret_range = tnum_range(0, 1);
69c087ba
YS
7092 return 0;
7093}
7094
e6f2dd0f
JK
7095static int set_loop_callback_state(struct bpf_verifier_env *env,
7096 struct bpf_func_state *caller,
7097 struct bpf_func_state *callee,
7098 int insn_idx)
7099{
7100 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7101 * u64 flags);
7102 * callback_fn(u32 index, void *callback_ctx);
7103 */
7104 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7105 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7106
7107 /* unused */
7108 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7109 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7110 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7111
7112 callee->in_callback_fn = true;
1bfe26fb 7113 callee->callback_ret_range = tnum_range(0, 1);
e6f2dd0f
JK
7114 return 0;
7115}
7116
b00628b1
AS
7117static int set_timer_callback_state(struct bpf_verifier_env *env,
7118 struct bpf_func_state *caller,
7119 struct bpf_func_state *callee,
7120 int insn_idx)
7121{
7122 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7123
7124 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7125 * callback_fn(struct bpf_map *map, void *key, void *value);
7126 */
7127 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7128 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7129 callee->regs[BPF_REG_1].map_ptr = map_ptr;
7130
7131 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7132 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7133 callee->regs[BPF_REG_2].map_ptr = map_ptr;
7134
7135 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7136 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7137 callee->regs[BPF_REG_3].map_ptr = map_ptr;
7138
7139 /* unused */
7140 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7141 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
bfc6bb74 7142 callee->in_async_callback_fn = true;
1bfe26fb 7143 callee->callback_ret_range = tnum_range(0, 1);
b00628b1
AS
7144 return 0;
7145}
7146
7c7e3d31
SL
7147static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7148 struct bpf_func_state *caller,
7149 struct bpf_func_state *callee,
7150 int insn_idx)
7151{
7152 /* bpf_find_vma(struct task_struct *task, u64 addr,
7153 * void *callback_fn, void *callback_ctx, u64 flags)
7154 * (callback_fn)(struct task_struct *task,
7155 * struct vm_area_struct *vma, void *callback_ctx);
7156 */
7157 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7158
7159 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7160 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7161 callee->regs[BPF_REG_2].btf = btf_vmlinux;
d19ddb47 7162 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7c7e3d31
SL
7163
7164 /* pointer to stack or null */
7165 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7166
7167 /* unused */
7168 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7169 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7170 callee->in_callback_fn = true;
1bfe26fb 7171 callee->callback_ret_range = tnum_range(0, 1);
7c7e3d31
SL
7172 return 0;
7173}
7174
20571567
DV
7175static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7176 struct bpf_func_state *caller,
7177 struct bpf_func_state *callee,
7178 int insn_idx)
7179{
7180 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7181 * callback_ctx, u64 flags);
7182 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7183 */
7184 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7185 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7186 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7187 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7188
7189 /* unused */
7190 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7191 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7192 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7193
7194 callee->in_callback_fn = true;
c92a7a52 7195 callee->callback_ret_range = tnum_range(0, 1);
20571567
DV
7196 return 0;
7197}
7198
f4d7e40a
AS
7199static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7200{
7201 struct bpf_verifier_state *state = env->cur_state;
7202 struct bpf_func_state *caller, *callee;
7203 struct bpf_reg_state *r0;
fd978bf7 7204 int err;
f4d7e40a
AS
7205
7206 callee = state->frame[state->curframe];
7207 r0 = &callee->regs[BPF_REG_0];
7208 if (r0->type == PTR_TO_STACK) {
7209 /* technically it's ok to return caller's stack pointer
7210 * (or caller's caller's pointer) back to the caller,
7211 * since these pointers are valid. Only current stack
7212 * pointer will be invalid as soon as function exits,
7213 * but let's be conservative
7214 */
7215 verbose(env, "cannot return stack pointer to the caller\n");
7216 return -EINVAL;
7217 }
7218
7219 state->curframe--;
7220 caller = state->frame[state->curframe];
69c087ba
YS
7221 if (callee->in_callback_fn) {
7222 /* enforce R0 return value range [0, 1]. */
1bfe26fb 7223 struct tnum range = callee->callback_ret_range;
69c087ba
YS
7224
7225 if (r0->type != SCALAR_VALUE) {
7226 verbose(env, "R0 not a scalar value\n");
7227 return -EACCES;
7228 }
7229 if (!tnum_in(range, r0->var_off)) {
7230 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7231 return -EINVAL;
7232 }
7233 } else {
7234 /* return to the caller whatever r0 had in the callee */
7235 caller->regs[BPF_REG_0] = *r0;
7236 }
f4d7e40a 7237
9d9d00ac
KKD
7238 /* callback_fn frame should have released its own additions to parent's
7239 * reference state at this point, or check_reference_leak would
7240 * complain, hence it must be the same as the caller. There is no need
7241 * to copy it back.
7242 */
7243 if (!callee->in_callback_fn) {
7244 /* Transfer references to the caller */
7245 err = copy_reference_state(caller, callee);
7246 if (err)
7247 return err;
7248 }
fd978bf7 7249
f4d7e40a 7250 *insn_idx = callee->callsite + 1;
06ee7115 7251 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a 7252 verbose(env, "returning from callee:\n");
0f55f9ed 7253 print_verifier_state(env, callee, true);
f4d7e40a 7254 verbose(env, "to caller at %d:\n", *insn_idx);
0f55f9ed 7255 print_verifier_state(env, caller, true);
f4d7e40a
AS
7256 }
7257 /* clear everything in the callee */
7258 free_func_state(callee);
7259 state->frame[state->curframe + 1] = NULL;
7260 return 0;
7261}
7262
849fa506
YS
7263static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7264 int func_id,
7265 struct bpf_call_arg_meta *meta)
7266{
7267 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7268
7269 if (ret_type != RET_INTEGER ||
7270 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 7271 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
7272 func_id != BPF_FUNC_probe_read_str &&
7273 func_id != BPF_FUNC_probe_read_kernel_str &&
7274 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
7275 return;
7276
10060503 7277 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 7278 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
7279 ret_reg->smin_value = -MAX_ERRNO;
7280 ret_reg->s32_min_value = -MAX_ERRNO;
3844d153 7281 reg_bounds_sync(ret_reg);
849fa506
YS
7282}
7283
c93552c4
DB
7284static int
7285record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7286 int func_id, int insn_idx)
7287{
7288 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 7289 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
7290
7291 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
7292 func_id != BPF_FUNC_map_lookup_elem &&
7293 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
7294 func_id != BPF_FUNC_map_delete_elem &&
7295 func_id != BPF_FUNC_map_push_elem &&
7296 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 7297 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f 7298 func_id != BPF_FUNC_for_each_map_elem &&
07343110
FZ
7299 func_id != BPF_FUNC_redirect_map &&
7300 func_id != BPF_FUNC_map_lookup_percpu_elem)
c93552c4 7301 return 0;
09772d92 7302
591fe988 7303 if (map == NULL) {
c93552c4
DB
7304 verbose(env, "kernel subsystem misconfigured verifier\n");
7305 return -EINVAL;
7306 }
7307
591fe988
DB
7308 /* In case of read-only, some additional restrictions
7309 * need to be applied in order to prevent altering the
7310 * state of the map from program side.
7311 */
7312 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7313 (func_id == BPF_FUNC_map_delete_elem ||
7314 func_id == BPF_FUNC_map_update_elem ||
7315 func_id == BPF_FUNC_map_push_elem ||
7316 func_id == BPF_FUNC_map_pop_elem)) {
7317 verbose(env, "write into map forbidden\n");
7318 return -EACCES;
7319 }
7320
d2e4c1e6 7321 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 7322 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 7323 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 7324 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 7325 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 7326 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
7327 return 0;
7328}
7329
d2e4c1e6
DB
7330static int
7331record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7332 int func_id, int insn_idx)
7333{
7334 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7335 struct bpf_reg_state *regs = cur_regs(env), *reg;
7336 struct bpf_map *map = meta->map_ptr;
a657182a 7337 u64 val, max;
cc52d914 7338 int err;
d2e4c1e6
DB
7339
7340 if (func_id != BPF_FUNC_tail_call)
7341 return 0;
7342 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7343 verbose(env, "kernel subsystem misconfigured verifier\n");
7344 return -EINVAL;
7345 }
7346
d2e4c1e6 7347 reg = &regs[BPF_REG_3];
a657182a
DB
7348 val = reg->var_off.value;
7349 max = map->max_entries;
d2e4c1e6 7350
a657182a 7351 if (!(register_is_const(reg) && val < max)) {
d2e4c1e6
DB
7352 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7353 return 0;
7354 }
7355
cc52d914
DB
7356 err = mark_chain_precision(env, BPF_REG_3);
7357 if (err)
7358 return err;
d2e4c1e6
DB
7359 if (bpf_map_key_unseen(aux))
7360 bpf_map_key_store(aux, val);
7361 else if (!bpf_map_key_poisoned(aux) &&
7362 bpf_map_key_immediate(aux) != val)
7363 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7364 return 0;
7365}
7366
fd978bf7
JS
7367static int check_reference_leak(struct bpf_verifier_env *env)
7368{
7369 struct bpf_func_state *state = cur_func(env);
9d9d00ac 7370 bool refs_lingering = false;
fd978bf7
JS
7371 int i;
7372
9d9d00ac
KKD
7373 if (state->frameno && !state->in_callback_fn)
7374 return 0;
7375
fd978bf7 7376 for (i = 0; i < state->acquired_refs; i++) {
9d9d00ac
KKD
7377 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7378 continue;
fd978bf7
JS
7379 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7380 state->refs[i].id, state->refs[i].insn_idx);
9d9d00ac 7381 refs_lingering = true;
fd978bf7 7382 }
9d9d00ac 7383 return refs_lingering ? -EINVAL : 0;
fd978bf7
JS
7384}
7385
7b15523a
FR
7386static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7387 struct bpf_reg_state *regs)
7388{
7389 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7390 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7391 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7392 int err, fmt_map_off, num_args;
7393 u64 fmt_addr;
7394 char *fmt;
7395
7396 /* data must be an array of u64 */
7397 if (data_len_reg->var_off.value % 8)
7398 return -EINVAL;
7399 num_args = data_len_reg->var_off.value / 8;
7400
7401 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7402 * and map_direct_value_addr is set.
7403 */
7404 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7405 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7406 fmt_map_off);
8e8ee109
FR
7407 if (err) {
7408 verbose(env, "verifier bug\n");
7409 return -EFAULT;
7410 }
7b15523a
FR
7411 fmt = (char *)(long)fmt_addr + fmt_map_off;
7412
7413 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7414 * can focus on validating the format specifiers.
7415 */
48cac3f4 7416 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7b15523a
FR
7417 if (err < 0)
7418 verbose(env, "Invalid format string\n");
7419
7420 return err;
7421}
7422
9b99edca
JO
7423static int check_get_func_ip(struct bpf_verifier_env *env)
7424{
9b99edca
JO
7425 enum bpf_prog_type type = resolve_prog_type(env->prog);
7426 int func_id = BPF_FUNC_get_func_ip;
7427
7428 if (type == BPF_PROG_TYPE_TRACING) {
f92c1e18 7429 if (!bpf_prog_has_trampoline(env->prog)) {
9b99edca
JO
7430 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7431 func_id_name(func_id), func_id);
7432 return -ENOTSUPP;
7433 }
7434 return 0;
9ffd9f3f
JO
7435 } else if (type == BPF_PROG_TYPE_KPROBE) {
7436 return 0;
9b99edca
JO
7437 }
7438
7439 verbose(env, "func %s#%d not supported for program type %d\n",
7440 func_id_name(func_id), func_id, type);
7441 return -ENOTSUPP;
7442}
7443
1ade2371
EZ
7444static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7445{
7446 return &env->insn_aux_data[env->insn_idx];
7447}
7448
7449static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7450{
7451 struct bpf_reg_state *regs = cur_regs(env);
7452 struct bpf_reg_state *reg = &regs[BPF_REG_4];
7453 bool reg_is_null = register_is_null(reg);
7454
7455 if (reg_is_null)
7456 mark_chain_precision(env, BPF_REG_4);
7457
7458 return reg_is_null;
7459}
7460
7461static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7462{
7463 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7464
7465 if (!state->initialized) {
7466 state->initialized = 1;
7467 state->fit_for_inline = loop_flag_is_zero(env);
7468 state->callback_subprogno = subprogno;
7469 return;
7470 }
7471
7472 if (!state->fit_for_inline)
7473 return;
7474
7475 state->fit_for_inline = (loop_flag_is_zero(env) &&
7476 state->callback_subprogno == subprogno);
7477}
7478
69c087ba
YS
7479static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7480 int *insn_idx_p)
17a52670 7481{
aef9d4a3 7482 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17a52670 7483 const struct bpf_func_proto *fn = NULL;
3c480732 7484 enum bpf_return_type ret_type;
c25b2ae1 7485 enum bpf_type_flag ret_flag;
638f5b90 7486 struct bpf_reg_state *regs;
33ff9823 7487 struct bpf_call_arg_meta meta;
69c087ba 7488 int insn_idx = *insn_idx_p;
969bf05e 7489 bool changes_data;
69c087ba 7490 int i, err, func_id;
17a52670
AS
7491
7492 /* find function prototype */
69c087ba 7493 func_id = insn->imm;
17a52670 7494 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
7495 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7496 func_id);
17a52670
AS
7497 return -EINVAL;
7498 }
7499
00176a34 7500 if (env->ops->get_func_proto)
5e43f899 7501 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 7502 if (!fn) {
61bd5218
JK
7503 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7504 func_id);
17a52670
AS
7505 return -EINVAL;
7506 }
7507
7508 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 7509 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 7510 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
7511 return -EINVAL;
7512 }
7513
eae2e83e
JO
7514 if (fn->allowed && !fn->allowed(env->prog)) {
7515 verbose(env, "helper call is not allowed in probe\n");
7516 return -EINVAL;
7517 }
7518
01685c5b
YS
7519 if (!env->prog->aux->sleepable && fn->might_sleep) {
7520 verbose(env, "helper call might sleep in a non-sleepable prog\n");
7521 return -EINVAL;
7522 }
7523
04514d13 7524 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 7525 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
7526 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7527 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7528 func_id_name(func_id), func_id);
7529 return -EINVAL;
7530 }
969bf05e 7531
33ff9823 7532 memset(&meta, 0, sizeof(meta));
36bbef52 7533 meta.pkt_access = fn->pkt_access;
33ff9823 7534
0c9a7a7e 7535 err = check_func_proto(fn, func_id);
435faee1 7536 if (err) {
61bd5218 7537 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 7538 func_id_name(func_id), func_id);
435faee1
DB
7539 return err;
7540 }
7541
d83525ca 7542 meta.func_id = func_id;
17a52670 7543 /* check args */
523a4cf4 7544 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 7545 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
7546 if (err)
7547 return err;
7548 }
17a52670 7549
c93552c4
DB
7550 err = record_func_map(env, &meta, func_id, insn_idx);
7551 if (err)
7552 return err;
7553
d2e4c1e6
DB
7554 err = record_func_key(env, &meta, func_id, insn_idx);
7555 if (err)
7556 return err;
7557
435faee1
DB
7558 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7559 * is inferred from register state.
7560 */
7561 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
7562 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7563 BPF_WRITE, -1, false);
435faee1
DB
7564 if (err)
7565 return err;
7566 }
7567
8f14852e
KKD
7568 regs = cur_regs(env);
7569
97e03f52
JK
7570 if (meta.uninit_dynptr_regno) {
7571 /* we write BPF_DW bits (8 bytes) at a time */
7572 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7573 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7574 i, BPF_DW, BPF_WRITE, -1, false);
7575 if (err)
7576 return err;
7577 }
7578
7579 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7580 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7581 insn_idx);
7582 if (err)
7583 return err;
7584 }
7585
8f14852e
KKD
7586 if (meta.release_regno) {
7587 err = -EINVAL;
97e03f52
JK
7588 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7589 err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7590 else if (meta.ref_obj_id)
8f14852e
KKD
7591 err = release_reference(env, meta.ref_obj_id);
7592 /* meta.ref_obj_id can only be 0 if register that is meant to be
7593 * released is NULL, which must be > R0.
7594 */
7595 else if (register_is_null(&regs[meta.release_regno]))
7596 err = 0;
46f8bc92
MKL
7597 if (err) {
7598 verbose(env, "func %s#%d reference has not been acquired before\n",
7599 func_id_name(func_id), func_id);
fd978bf7 7600 return err;
46f8bc92 7601 }
fd978bf7
JS
7602 }
7603
e6f2dd0f
JK
7604 switch (func_id) {
7605 case BPF_FUNC_tail_call:
7606 err = check_reference_leak(env);
7607 if (err) {
7608 verbose(env, "tail_call would lead to reference leak\n");
7609 return err;
7610 }
7611 break;
7612 case BPF_FUNC_get_local_storage:
7613 /* check that flags argument in get_local_storage(map, flags) is 0,
7614 * this is required because get_local_storage() can't return an error.
7615 */
7616 if (!register_is_null(&regs[BPF_REG_2])) {
7617 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7618 return -EINVAL;
7619 }
7620 break;
7621 case BPF_FUNC_for_each_map_elem:
69c087ba
YS
7622 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7623 set_map_elem_callback_state);
e6f2dd0f
JK
7624 break;
7625 case BPF_FUNC_timer_set_callback:
b00628b1
AS
7626 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7627 set_timer_callback_state);
e6f2dd0f
JK
7628 break;
7629 case BPF_FUNC_find_vma:
7c7e3d31
SL
7630 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7631 set_find_vma_callback_state);
e6f2dd0f
JK
7632 break;
7633 case BPF_FUNC_snprintf:
7b15523a 7634 err = check_bpf_snprintf_call(env, regs);
e6f2dd0f
JK
7635 break;
7636 case BPF_FUNC_loop:
1ade2371 7637 update_loop_inline_state(env, meta.subprogno);
e6f2dd0f
JK
7638 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7639 set_loop_callback_state);
7640 break;
263ae152
JK
7641 case BPF_FUNC_dynptr_from_mem:
7642 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7643 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7644 reg_type_str(env, regs[BPF_REG_1].type));
7645 return -EACCES;
7646 }
69fd337a
SF
7647 break;
7648 case BPF_FUNC_set_retval:
aef9d4a3
SF
7649 if (prog_type == BPF_PROG_TYPE_LSM &&
7650 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
69fd337a
SF
7651 if (!env->prog->aux->attach_func_proto->type) {
7652 /* Make sure programs that attach to void
7653 * hooks don't try to modify return value.
7654 */
7655 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7656 return -EINVAL;
7657 }
7658 }
7659 break;
88374342
JK
7660 case BPF_FUNC_dynptr_data:
7661 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7662 if (arg_type_is_dynptr(fn->arg_type[i])) {
20571567
DV
7663 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7664
88374342
JK
7665 if (meta.ref_obj_id) {
7666 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7667 return -EFAULT;
7668 }
20571567
DV
7669
7670 if (base_type(reg->type) != PTR_TO_DYNPTR)
7671 /* Find the id of the dynptr we're
7672 * tracking the reference of
7673 */
7674 meta.ref_obj_id = stack_slot_get_id(env, reg);
88374342
JK
7675 break;
7676 }
7677 }
7678 if (i == MAX_BPF_FUNC_REG_ARGS) {
7679 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7680 return -EFAULT;
7681 }
7682 break;
20571567
DV
7683 case BPF_FUNC_user_ringbuf_drain:
7684 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7685 set_user_ringbuf_callback_state);
7686 break;
7b15523a
FR
7687 }
7688
e6f2dd0f
JK
7689 if (err)
7690 return err;
7691
17a52670 7692 /* reset caller saved regs */
dc503a8a 7693 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 7694 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
7695 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7696 }
17a52670 7697
5327ed3d
JW
7698 /* helper call returns 64-bit value. */
7699 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7700
dc503a8a 7701 /* update return register (already marked as written above) */
3c480732 7702 ret_type = fn->ret_type;
0c9a7a7e
JK
7703 ret_flag = type_flag(ret_type);
7704
7705 switch (base_type(ret_type)) {
7706 case RET_INTEGER:
f1174f77 7707 /* sets type to SCALAR_VALUE */
61bd5218 7708 mark_reg_unknown(env, regs, BPF_REG_0);
0c9a7a7e
JK
7709 break;
7710 case RET_VOID:
17a52670 7711 regs[BPF_REG_0].type = NOT_INIT;
0c9a7a7e
JK
7712 break;
7713 case RET_PTR_TO_MAP_VALUE:
f1174f77 7714 /* There is no offset yet applied, variable or fixed */
61bd5218 7715 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
7716 /* remember map_ptr, so that check_map_access()
7717 * can check 'value_size' boundary of memory access
7718 * to map element returned from bpf_map_lookup_elem()
7719 */
33ff9823 7720 if (meta.map_ptr == NULL) {
61bd5218
JK
7721 verbose(env,
7722 "kernel subsystem misconfigured verifier\n");
17a52670
AS
7723 return -EINVAL;
7724 }
33ff9823 7725 regs[BPF_REG_0].map_ptr = meta.map_ptr;
3e8ce298 7726 regs[BPF_REG_0].map_uid = meta.map_uid;
c25b2ae1
HL
7727 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7728 if (!type_may_be_null(ret_type) &&
db559117 7729 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
c25b2ae1 7730 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301 7731 }
0c9a7a7e
JK
7732 break;
7733 case RET_PTR_TO_SOCKET:
c64b7983 7734 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 7735 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
0c9a7a7e
JK
7736 break;
7737 case RET_PTR_TO_SOCK_COMMON:
85a51f8c 7738 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 7739 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
0c9a7a7e
JK
7740 break;
7741 case RET_PTR_TO_TCP_SOCK:
655a51e5 7742 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 7743 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
0c9a7a7e 7744 break;
2de2669b 7745 case RET_PTR_TO_MEM:
457f4436 7746 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 7747 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
457f4436 7748 regs[BPF_REG_0].mem_size = meta.mem_size;
0c9a7a7e
JK
7749 break;
7750 case RET_PTR_TO_MEM_OR_BTF_ID:
7751 {
eaa6bcb7
HL
7752 const struct btf_type *t;
7753
7754 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 7755 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
7756 if (!btf_type_is_struct(t)) {
7757 u32 tsize;
7758 const struct btf_type *ret;
7759 const char *tname;
7760
7761 /* resolve the type size of ksym. */
22dc4a0f 7762 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 7763 if (IS_ERR(ret)) {
22dc4a0f 7764 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
7765 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7766 tname, PTR_ERR(ret));
7767 return -EINVAL;
7768 }
c25b2ae1 7769 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
eaa6bcb7
HL
7770 regs[BPF_REG_0].mem_size = tsize;
7771 } else {
34d3a78c
HL
7772 /* MEM_RDONLY may be carried from ret_flag, but it
7773 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7774 * it will confuse the check of PTR_TO_BTF_ID in
7775 * check_mem_access().
7776 */
7777 ret_flag &= ~MEM_RDONLY;
7778
c25b2ae1 7779 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
22dc4a0f 7780 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
7781 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7782 }
0c9a7a7e
JK
7783 break;
7784 }
7785 case RET_PTR_TO_BTF_ID:
7786 {
c0a5a21c 7787 struct btf *ret_btf;
af7ec138
YS
7788 int ret_btf_id;
7789
7790 mark_reg_known_zero(env, regs, BPF_REG_0);
c25b2ae1 7791 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
c0a5a21c 7792 if (func_id == BPF_FUNC_kptr_xchg) {
aa3496ac
KKD
7793 ret_btf = meta.kptr_field->kptr.btf;
7794 ret_btf_id = meta.kptr_field->kptr.btf_id;
c0a5a21c 7795 } else {
47e34cb7
DM
7796 if (fn->ret_btf_id == BPF_PTR_POISON) {
7797 verbose(env, "verifier internal error:");
7798 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7799 func_id_name(func_id));
7800 return -EINVAL;
7801 }
c0a5a21c
KKD
7802 ret_btf = btf_vmlinux;
7803 ret_btf_id = *fn->ret_btf_id;
7804 }
af7ec138 7805 if (ret_btf_id == 0) {
3c480732
HL
7806 verbose(env, "invalid return type %u of func %s#%d\n",
7807 base_type(ret_type), func_id_name(func_id),
7808 func_id);
af7ec138
YS
7809 return -EINVAL;
7810 }
c0a5a21c 7811 regs[BPF_REG_0].btf = ret_btf;
af7ec138 7812 regs[BPF_REG_0].btf_id = ret_btf_id;
0c9a7a7e
JK
7813 break;
7814 }
7815 default:
3c480732
HL
7816 verbose(env, "unknown return type %u of func %s#%d\n",
7817 base_type(ret_type), func_id_name(func_id), func_id);
17a52670
AS
7818 return -EINVAL;
7819 }
04fd61ab 7820
c25b2ae1 7821 if (type_may_be_null(regs[BPF_REG_0].type))
93c230e3
MKL
7822 regs[BPF_REG_0].id = ++env->id_gen;
7823
b2d8ef19
DM
7824 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7825 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7826 func_id_name(func_id), func_id);
7827 return -EFAULT;
7828 }
7829
88374342 7830 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
1b986589
MKL
7831 /* For release_reference() */
7832 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 7833 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
7834 int id = acquire_reference_state(env, insn_idx);
7835
7836 if (id < 0)
7837 return id;
7838 /* For mark_ptr_or_null_reg() */
7839 regs[BPF_REG_0].id = id;
7840 /* For release_reference() */
7841 regs[BPF_REG_0].ref_obj_id = id;
7842 }
1b986589 7843
849fa506
YS
7844 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7845
61bd5218 7846 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
7847 if (err)
7848 return err;
04fd61ab 7849
fa28dcb8
SL
7850 if ((func_id == BPF_FUNC_get_stack ||
7851 func_id == BPF_FUNC_get_task_stack) &&
7852 !env->prog->has_callchain_buf) {
c195651e
YS
7853 const char *err_str;
7854
7855#ifdef CONFIG_PERF_EVENTS
7856 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7857 err_str = "cannot get callchain buffer for func %s#%d\n";
7858#else
7859 err = -ENOTSUPP;
7860 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7861#endif
7862 if (err) {
7863 verbose(env, err_str, func_id_name(func_id), func_id);
7864 return err;
7865 }
7866
7867 env->prog->has_callchain_buf = true;
7868 }
7869
5d99cb2c
SL
7870 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7871 env->prog->call_get_stack = true;
7872
9b99edca
JO
7873 if (func_id == BPF_FUNC_get_func_ip) {
7874 if (check_get_func_ip(env))
7875 return -ENOTSUPP;
7876 env->prog->call_get_func_ip = true;
7877 }
7878
969bf05e
AS
7879 if (changes_data)
7880 clear_all_pkt_pointers(env);
7881 return 0;
7882}
7883
e6ac2450
MKL
7884/* mark_btf_func_reg_size() is used when the reg size is determined by
7885 * the BTF func_proto's return value size and argument.
7886 */
7887static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7888 size_t reg_size)
7889{
7890 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7891
7892 if (regno == BPF_REG_0) {
7893 /* Function return value */
7894 reg->live |= REG_LIVE_WRITTEN;
7895 reg->subreg_def = reg_size == sizeof(u64) ?
7896 DEF_NOT_SUBREG : env->insn_idx + 1;
7897 } else {
7898 /* Function argument */
7899 if (reg_size == sizeof(u64)) {
7900 mark_insn_zext(env, reg);
7901 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7902 } else {
7903 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7904 }
7905 }
7906}
7907
00b85860
KKD
7908struct bpf_kfunc_call_arg_meta {
7909 /* In parameters */
7910 struct btf *btf;
7911 u32 func_id;
7912 u32 kfunc_flags;
7913 const struct btf_type *func_proto;
7914 const char *func_name;
7915 /* Out parameters */
7916 u32 ref_obj_id;
7917 u8 release_regno;
7918 bool r0_rdonly;
fd264ca0 7919 u32 ret_btf_id;
00b85860 7920 u64 r0_size;
a50388db
KKD
7921 struct {
7922 u64 value;
7923 bool found;
7924 } arg_constant;
ac9f0605
KKD
7925 struct {
7926 struct btf *btf;
7927 u32 btf_id;
7928 } arg_obj_drop;
8cab76ec
KKD
7929 struct {
7930 struct btf_field *field;
7931 } arg_list_head;
00b85860
KKD
7932};
7933
7934static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
7935{
7936 return meta->kfunc_flags & KF_ACQUIRE;
7937}
7938
7939static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
7940{
7941 return meta->kfunc_flags & KF_RET_NULL;
7942}
7943
7944static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
7945{
7946 return meta->kfunc_flags & KF_RELEASE;
7947}
7948
7949static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
7950{
7951 return meta->kfunc_flags & KF_TRUSTED_ARGS;
7952}
7953
7954static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
7955{
7956 return meta->kfunc_flags & KF_SLEEPABLE;
7957}
7958
7959static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
7960{
7961 return meta->kfunc_flags & KF_DESTRUCTIVE;
7962}
7963
7964static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
7965{
7966 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
7967}
7968
3f00c523
DV
7969static bool is_trusted_reg(const struct bpf_reg_state *reg)
7970{
7971 /* A referenced register is always trusted. */
7972 if (reg->ref_obj_id)
7973 return true;
7974
7975 /* If a register is not referenced, it is trusted if it has either the
7976 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
7977 * other type modifiers may be safe, but we elect to take an opt-in
7978 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
7979 * not.
7980 *
7981 * Eventually, we should make PTR_TRUSTED the single source of truth
7982 * for whether a register is trusted.
7983 */
7984 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
7985 !bpf_type_has_unsafe_modifiers(reg->type);
7986}
7987
a50388db
KKD
7988static bool __kfunc_param_match_suffix(const struct btf *btf,
7989 const struct btf_param *arg,
7990 const char *suffix)
00b85860 7991{
a50388db 7992 int suffix_len = strlen(suffix), len;
00b85860
KKD
7993 const char *param_name;
7994
00b85860
KKD
7995 /* In the future, this can be ported to use BTF tagging */
7996 param_name = btf_name_by_offset(btf, arg->name_off);
7997 if (str_is_empty(param_name))
7998 return false;
7999 len = strlen(param_name);
a50388db 8000 if (len < suffix_len)
00b85860 8001 return false;
a50388db
KKD
8002 param_name += len - suffix_len;
8003 return !strncmp(param_name, suffix, suffix_len);
8004}
8005
8006static bool is_kfunc_arg_mem_size(const struct btf *btf,
8007 const struct btf_param *arg,
8008 const struct bpf_reg_state *reg)
8009{
8010 const struct btf_type *t;
8011
8012 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8013 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
00b85860
KKD
8014 return false;
8015
a50388db
KKD
8016 return __kfunc_param_match_suffix(btf, arg, "__sz");
8017}
8018
8019static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
8020{
8021 return __kfunc_param_match_suffix(btf, arg, "__k");
00b85860
KKD
8022}
8023
958cf2e2
KKD
8024static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
8025{
8026 return __kfunc_param_match_suffix(btf, arg, "__ign");
8027}
8028
ac9f0605
KKD
8029static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
8030{
8031 return __kfunc_param_match_suffix(btf, arg, "__alloc");
8032}
8033
00b85860
KKD
8034static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8035 const struct btf_param *arg,
8036 const char *name)
8037{
8038 int len, target_len = strlen(name);
8039 const char *param_name;
8040
8041 param_name = btf_name_by_offset(btf, arg->name_off);
8042 if (str_is_empty(param_name))
8043 return false;
8044 len = strlen(param_name);
8045 if (len != target_len)
8046 return false;
8047 if (strcmp(param_name, name))
8048 return false;
8049
8050 return true;
8051}
8052
8053enum {
8054 KF_ARG_DYNPTR_ID,
8cab76ec
KKD
8055 KF_ARG_LIST_HEAD_ID,
8056 KF_ARG_LIST_NODE_ID,
00b85860
KKD
8057};
8058
8059BTF_ID_LIST(kf_arg_btf_ids)
8060BTF_ID(struct, bpf_dynptr_kern)
8cab76ec
KKD
8061BTF_ID(struct, bpf_list_head)
8062BTF_ID(struct, bpf_list_node)
00b85860 8063
8cab76ec
KKD
8064static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
8065 const struct btf_param *arg, int type)
00b85860
KKD
8066{
8067 const struct btf_type *t;
8068 u32 res_id;
8069
8070 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8071 if (!t)
8072 return false;
8073 if (!btf_type_is_ptr(t))
8074 return false;
8075 t = btf_type_skip_modifiers(btf, t->type, &res_id);
8076 if (!t)
8077 return false;
8cab76ec
KKD
8078 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
8079}
8080
8081static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
8082{
8083 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
8084}
8085
8086static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
8087{
8088 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
8089}
8090
8091static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
8092{
8093 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
00b85860
KKD
8094}
8095
8096/* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
8097static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
8098 const struct btf *btf,
8099 const struct btf_type *t, int rec)
8100{
8101 const struct btf_type *member_type;
8102 const struct btf_member *member;
8103 u32 i;
8104
8105 if (!btf_type_is_struct(t))
8106 return false;
8107
8108 for_each_member(i, t, member) {
8109 const struct btf_array *array;
8110
8111 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
8112 if (btf_type_is_struct(member_type)) {
8113 if (rec >= 3) {
8114 verbose(env, "max struct nesting depth exceeded\n");
8115 return false;
8116 }
8117 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
8118 return false;
8119 continue;
8120 }
8121 if (btf_type_is_array(member_type)) {
8122 array = btf_array(member_type);
8123 if (!array->nelems)
8124 return false;
8125 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
8126 if (!btf_type_is_scalar(member_type))
8127 return false;
8128 continue;
8129 }
8130 if (!btf_type_is_scalar(member_type))
8131 return false;
8132 }
8133 return true;
8134}
8135
8136
8137static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
8138#ifdef CONFIG_NET
8139 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
8140 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8141 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
8142#endif
8143};
8144
8145enum kfunc_ptr_arg_type {
8146 KF_ARG_PTR_TO_CTX,
ac9f0605 8147 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
00b85860
KKD
8148 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */
8149 KF_ARG_PTR_TO_DYNPTR,
8cab76ec
KKD
8150 KF_ARG_PTR_TO_LIST_HEAD,
8151 KF_ARG_PTR_TO_LIST_NODE,
00b85860
KKD
8152 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
8153 KF_ARG_PTR_TO_MEM,
8154 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
8155};
8156
ac9f0605
KKD
8157enum special_kfunc_type {
8158 KF_bpf_obj_new_impl,
8159 KF_bpf_obj_drop_impl,
8cab76ec
KKD
8160 KF_bpf_list_push_front,
8161 KF_bpf_list_push_back,
8162 KF_bpf_list_pop_front,
8163 KF_bpf_list_pop_back,
fd264ca0 8164 KF_bpf_cast_to_kern_ctx,
a35b9af4 8165 KF_bpf_rdonly_cast,
ac9f0605
KKD
8166};
8167
8168BTF_SET_START(special_kfunc_set)
8169BTF_ID(func, bpf_obj_new_impl)
8170BTF_ID(func, bpf_obj_drop_impl)
8cab76ec
KKD
8171BTF_ID(func, bpf_list_push_front)
8172BTF_ID(func, bpf_list_push_back)
8173BTF_ID(func, bpf_list_pop_front)
8174BTF_ID(func, bpf_list_pop_back)
fd264ca0 8175BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 8176BTF_ID(func, bpf_rdonly_cast)
ac9f0605
KKD
8177BTF_SET_END(special_kfunc_set)
8178
8179BTF_ID_LIST(special_kfunc_list)
8180BTF_ID(func, bpf_obj_new_impl)
8181BTF_ID(func, bpf_obj_drop_impl)
8cab76ec
KKD
8182BTF_ID(func, bpf_list_push_front)
8183BTF_ID(func, bpf_list_push_back)
8184BTF_ID(func, bpf_list_pop_front)
8185BTF_ID(func, bpf_list_pop_back)
fd264ca0 8186BTF_ID(func, bpf_cast_to_kern_ctx)
a35b9af4 8187BTF_ID(func, bpf_rdonly_cast)
ac9f0605 8188
00b85860
KKD
8189static enum kfunc_ptr_arg_type
8190get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
8191 struct bpf_kfunc_call_arg_meta *meta,
8192 const struct btf_type *t, const struct btf_type *ref_t,
8193 const char *ref_tname, const struct btf_param *args,
8194 int argno, int nargs)
8195{
8196 u32 regno = argno + 1;
8197 struct bpf_reg_state *regs = cur_regs(env);
8198 struct bpf_reg_state *reg = &regs[regno];
8199 bool arg_mem_size = false;
8200
fd264ca0
YS
8201 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
8202 return KF_ARG_PTR_TO_CTX;
8203
00b85860
KKD
8204 /* In this function, we verify the kfunc's BTF as per the argument type,
8205 * leaving the rest of the verification with respect to the register
8206 * type to our caller. When a set of conditions hold in the BTF type of
8207 * arguments, we resolve it to a known kfunc_ptr_arg_type.
8208 */
8209 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
8210 return KF_ARG_PTR_TO_CTX;
8211
ac9f0605
KKD
8212 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
8213 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
8214
00b85860
KKD
8215 if (is_kfunc_arg_kptr_get(meta, argno)) {
8216 if (!btf_type_is_ptr(ref_t)) {
8217 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
8218 return -EINVAL;
8219 }
8220 ref_t = btf_type_by_id(meta->btf, ref_t->type);
8221 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
8222 if (!btf_type_is_struct(ref_t)) {
8223 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
8224 meta->func_name, btf_type_str(ref_t), ref_tname);
8225 return -EINVAL;
8226 }
8227 return KF_ARG_PTR_TO_KPTR;
8228 }
8229
8230 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
8231 return KF_ARG_PTR_TO_DYNPTR;
8232
8cab76ec
KKD
8233 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
8234 return KF_ARG_PTR_TO_LIST_HEAD;
8235
8236 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
8237 return KF_ARG_PTR_TO_LIST_NODE;
8238
00b85860
KKD
8239 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
8240 if (!btf_type_is_struct(ref_t)) {
8241 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
8242 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8243 return -EINVAL;
8244 }
8245 return KF_ARG_PTR_TO_BTF_ID;
8246 }
8247
8248 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]))
8249 arg_mem_size = true;
8250
8251 /* This is the catch all argument type of register types supported by
8252 * check_helper_mem_access. However, we only allow when argument type is
8253 * pointer to scalar, or struct composed (recursively) of scalars. When
8254 * arg_mem_size is true, the pointer can be void *.
8255 */
8256 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
8257 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
8258 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
8259 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
8260 return -EINVAL;
8261 }
8262 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
8263}
8264
8265static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
8266 struct bpf_reg_state *reg,
8267 const struct btf_type *ref_t,
8268 const char *ref_tname, u32 ref_id,
8269 struct bpf_kfunc_call_arg_meta *meta,
8270 int argno)
8271{
8272 const struct btf_type *reg_ref_t;
8273 bool strict_type_match = false;
8274 const struct btf *reg_btf;
8275 const char *reg_ref_tname;
8276 u32 reg_ref_id;
8277
3f00c523 8278 if (base_type(reg->type) == PTR_TO_BTF_ID) {
00b85860
KKD
8279 reg_btf = reg->btf;
8280 reg_ref_id = reg->btf_id;
8281 } else {
8282 reg_btf = btf_vmlinux;
8283 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
8284 }
8285
8286 if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id))
8287 strict_type_match = true;
8288
8289 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
8290 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
8291 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
8292 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
8293 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
8294 btf_type_str(reg_ref_t), reg_ref_tname);
8295 return -EINVAL;
8296 }
8297 return 0;
8298}
8299
8300static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
8301 struct bpf_reg_state *reg,
8302 const struct btf_type *ref_t,
8303 const char *ref_tname,
8304 struct bpf_kfunc_call_arg_meta *meta,
8305 int argno)
8306{
8307 struct btf_field *kptr_field;
8308
8309 /* check_func_arg_reg_off allows var_off for
8310 * PTR_TO_MAP_VALUE, but we need fixed offset to find
8311 * off_desc.
8312 */
8313 if (!tnum_is_const(reg->var_off)) {
8314 verbose(env, "arg#0 must have constant offset\n");
8315 return -EINVAL;
8316 }
8317
8318 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
8319 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
8320 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
8321 reg->off + reg->var_off.value);
8322 return -EINVAL;
8323 }
8324
8325 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
8326 kptr_field->kptr.btf_id, true)) {
8327 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
8328 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
8329 return -EINVAL;
8330 }
8331 return 0;
8332}
8333
534e86bc
KKD
8334static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id)
8335{
8336 struct bpf_func_state *state = cur_func(env);
8337 struct bpf_reg_state *reg;
8338 int i;
8339
8340 /* bpf_spin_lock only allows calling list_push and list_pop, no BPF
8341 * subprogs, no global functions. This means that the references would
8342 * not be released inside the critical section but they may be added to
8343 * the reference state, and the acquired_refs are never copied out for a
8344 * different frame as BPF to BPF calls don't work in bpf_spin_lock
8345 * critical sections.
8346 */
8347 if (!ref_obj_id) {
8348 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n");
8349 return -EFAULT;
8350 }
8351 for (i = 0; i < state->acquired_refs; i++) {
8352 if (state->refs[i].id == ref_obj_id) {
8353 if (state->refs[i].release_on_unlock) {
8354 verbose(env, "verifier internal error: expected false release_on_unlock");
8355 return -EFAULT;
8356 }
8357 state->refs[i].release_on_unlock = true;
8358 /* Now mark everyone sharing same ref_obj_id as untrusted */
8359 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8360 if (reg->ref_obj_id == ref_obj_id)
8361 reg->type |= PTR_UNTRUSTED;
8362 }));
8363 return 0;
8364 }
8365 }
8366 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
8367 return -EFAULT;
8368}
8369
8cab76ec
KKD
8370/* Implementation details:
8371 *
8372 * Each register points to some region of memory, which we define as an
8373 * allocation. Each allocation may embed a bpf_spin_lock which protects any
8374 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
8375 * allocation. The lock and the data it protects are colocated in the same
8376 * memory region.
8377 *
8378 * Hence, everytime a register holds a pointer value pointing to such
8379 * allocation, the verifier preserves a unique reg->id for it.
8380 *
8381 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
8382 * bpf_spin_lock is called.
8383 *
8384 * To enable this, lock state in the verifier captures two values:
8385 * active_lock.ptr = Register's type specific pointer
8386 * active_lock.id = A unique ID for each register pointer value
8387 *
8388 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
8389 * supported register types.
8390 *
8391 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
8392 * allocated objects is the reg->btf pointer.
8393 *
8394 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
8395 * can establish the provenance of the map value statically for each distinct
8396 * lookup into such maps. They always contain a single map value hence unique
8397 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
8398 *
8399 * So, in case of global variables, they use array maps with max_entries = 1,
8400 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
8401 * into the same map value as max_entries is 1, as described above).
8402 *
8403 * In case of inner map lookups, the inner map pointer has same map_ptr as the
8404 * outer map pointer (in verifier context), but each lookup into an inner map
8405 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
8406 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
8407 * will get different reg->id assigned to each lookup, hence different
8408 * active_lock.id.
8409 *
8410 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
8411 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
8412 * returned from bpf_obj_new. Each allocation receives a new reg->id.
8413 */
8414static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8415{
8416 void *ptr;
8417 u32 id;
8418
8419 switch ((int)reg->type) {
8420 case PTR_TO_MAP_VALUE:
8421 ptr = reg->map_ptr;
8422 break;
8423 case PTR_TO_BTF_ID | MEM_ALLOC:
3f00c523 8424 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED:
8cab76ec
KKD
8425 ptr = reg->btf;
8426 break;
8427 default:
8428 verbose(env, "verifier internal error: unknown reg type for lock check\n");
8429 return -EFAULT;
8430 }
8431 id = reg->id;
8432
8433 if (!env->cur_state->active_lock.ptr)
8434 return -EINVAL;
8435 if (env->cur_state->active_lock.ptr != ptr ||
8436 env->cur_state->active_lock.id != id) {
8437 verbose(env, "held lock and object are not in the same allocation\n");
8438 return -EINVAL;
8439 }
8440 return 0;
8441}
8442
8443static bool is_bpf_list_api_kfunc(u32 btf_id)
8444{
8445 return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
8446 btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
8447 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8448 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
8449}
8450
8451static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8452 struct bpf_reg_state *reg, u32 regno,
8453 struct bpf_kfunc_call_arg_meta *meta)
8454{
8455 struct btf_field *field;
8456 struct btf_record *rec;
8457 u32 list_head_off;
8458
8459 if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) {
8460 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n");
8461 return -EFAULT;
8462 }
8463
8464 if (!tnum_is_const(reg->var_off)) {
8465 verbose(env,
8466 "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n",
8467 regno);
8468 return -EINVAL;
8469 }
8470
8471 rec = reg_btf_record(reg);
8472 list_head_off = reg->off + reg->var_off.value;
8473 field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD);
8474 if (!field) {
8475 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off);
8476 return -EINVAL;
8477 }
8478
8479 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
8480 if (check_reg_allocation_locked(env, reg)) {
8481 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n",
8482 rec->spin_lock_off);
8483 return -EINVAL;
8484 }
8485
8486 if (meta->arg_list_head.field) {
8487 verbose(env, "verifier internal error: repeating bpf_list_head arg\n");
8488 return -EFAULT;
8489 }
8490 meta->arg_list_head.field = field;
8491 return 0;
8492}
8493
8494static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8495 struct bpf_reg_state *reg, u32 regno,
8496 struct bpf_kfunc_call_arg_meta *meta)
8497{
8498 const struct btf_type *et, *t;
8499 struct btf_field *field;
8500 struct btf_record *rec;
8501 u32 list_node_off;
8502
8503 if (meta->btf != btf_vmlinux ||
8504 (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] &&
8505 meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) {
8506 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n");
8507 return -EFAULT;
8508 }
8509
8510 if (!tnum_is_const(reg->var_off)) {
8511 verbose(env,
8512 "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n",
8513 regno);
8514 return -EINVAL;
8515 }
8516
8517 rec = reg_btf_record(reg);
8518 list_node_off = reg->off + reg->var_off.value;
8519 field = btf_record_find(rec, list_node_off, BPF_LIST_NODE);
8520 if (!field || field->offset != list_node_off) {
8521 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off);
8522 return -EINVAL;
8523 }
8524
8525 field = meta->arg_list_head.field;
8526
8527 et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id);
8528 t = btf_type_by_id(reg->btf, reg->btf_id);
8529 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf,
8530 field->list_head.value_btf_id, true)) {
8531 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d "
8532 "in struct %s, but arg is at offset=%d in struct %s\n",
8533 field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off),
8534 list_node_off, btf_name_by_offset(reg->btf, t->name_off));
8535 return -EINVAL;
8536 }
8537
8538 if (list_node_off != field->list_head.node_offset) {
8539 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n",
8540 list_node_off, field->list_head.node_offset,
8541 btf_name_by_offset(field->list_head.btf, et->name_off));
8542 return -EINVAL;
8543 }
534e86bc
KKD
8544 /* Set arg#1 for expiration after unlock */
8545 return ref_set_release_on_unlock(env, reg->ref_obj_id);
8cab76ec
KKD
8546}
8547
00b85860
KKD
8548static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
8549{
8550 const char *func_name = meta->func_name, *ref_tname;
8551 const struct btf *btf = meta->btf;
8552 const struct btf_param *args;
8553 u32 i, nargs;
8554 int ret;
8555
8556 args = (const struct btf_param *)(meta->func_proto + 1);
8557 nargs = btf_type_vlen(meta->func_proto);
8558 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
8559 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
8560 MAX_BPF_FUNC_REG_ARGS);
8561 return -EINVAL;
8562 }
8563
8564 /* Check that BTF function arguments match actual types that the
8565 * verifier sees.
8566 */
8567 for (i = 0; i < nargs; i++) {
8568 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
8569 const struct btf_type *t, *ref_t, *resolve_ret;
8570 enum bpf_arg_type arg_type = ARG_DONTCARE;
8571 u32 regno = i + 1, ref_id, type_size;
8572 bool is_ret_buf_sz = false;
8573 int kf_arg_type;
8574
8575 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
958cf2e2
KKD
8576
8577 if (is_kfunc_arg_ignore(btf, &args[i]))
8578 continue;
8579
00b85860
KKD
8580 if (btf_type_is_scalar(t)) {
8581 if (reg->type != SCALAR_VALUE) {
8582 verbose(env, "R%d is not a scalar\n", regno);
8583 return -EINVAL;
8584 }
a50388db
KKD
8585
8586 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
8587 if (meta->arg_constant.found) {
8588 verbose(env, "verifier internal error: only one constant argument permitted\n");
8589 return -EFAULT;
8590 }
8591 if (!tnum_is_const(reg->var_off)) {
8592 verbose(env, "R%d must be a known constant\n", regno);
8593 return -EINVAL;
8594 }
8595 ret = mark_chain_precision(env, regno);
8596 if (ret < 0)
8597 return ret;
8598 meta->arg_constant.found = true;
8599 meta->arg_constant.value = reg->var_off.value;
8600 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
00b85860
KKD
8601 meta->r0_rdonly = true;
8602 is_ret_buf_sz = true;
8603 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
8604 is_ret_buf_sz = true;
8605 }
8606
8607 if (is_ret_buf_sz) {
8608 if (meta->r0_size) {
8609 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
8610 return -EINVAL;
8611 }
8612
8613 if (!tnum_is_const(reg->var_off)) {
8614 verbose(env, "R%d is not a const\n", regno);
8615 return -EINVAL;
8616 }
8617
8618 meta->r0_size = reg->var_off.value;
8619 ret = mark_chain_precision(env, regno);
8620 if (ret)
8621 return ret;
8622 }
8623 continue;
8624 }
8625
8626 if (!btf_type_is_ptr(t)) {
8627 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
8628 return -EINVAL;
8629 }
8630
8631 if (reg->ref_obj_id) {
8632 if (is_kfunc_release(meta) && meta->ref_obj_id) {
8633 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8634 regno, reg->ref_obj_id,
8635 meta->ref_obj_id);
8636 return -EFAULT;
8637 }
8638 meta->ref_obj_id = reg->ref_obj_id;
8639 if (is_kfunc_release(meta))
8640 meta->release_regno = regno;
8641 }
8642
8643 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
8644 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
8645
8646 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
8647 if (kf_arg_type < 0)
8648 return kf_arg_type;
8649
8650 switch (kf_arg_type) {
ac9f0605 8651 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
00b85860
KKD
8652 case KF_ARG_PTR_TO_BTF_ID:
8653 if (!is_kfunc_trusted_args(meta))
8654 break;
3f00c523
DV
8655
8656 if (!is_trusted_reg(reg)) {
8657 verbose(env, "R%d must be referenced or trusted\n", regno);
00b85860
KKD
8658 return -EINVAL;
8659 }
8660 fallthrough;
8661 case KF_ARG_PTR_TO_CTX:
8662 /* Trusted arguments have the same offset checks as release arguments */
8663 arg_type |= OBJ_RELEASE;
8664 break;
8665 case KF_ARG_PTR_TO_KPTR:
8666 case KF_ARG_PTR_TO_DYNPTR:
8cab76ec
KKD
8667 case KF_ARG_PTR_TO_LIST_HEAD:
8668 case KF_ARG_PTR_TO_LIST_NODE:
00b85860
KKD
8669 case KF_ARG_PTR_TO_MEM:
8670 case KF_ARG_PTR_TO_MEM_SIZE:
8671 /* Trusted by default */
8672 break;
8673 default:
8674 WARN_ON_ONCE(1);
8675 return -EFAULT;
8676 }
8677
8678 if (is_kfunc_release(meta) && reg->ref_obj_id)
8679 arg_type |= OBJ_RELEASE;
8680 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
8681 if (ret < 0)
8682 return ret;
8683
8684 switch (kf_arg_type) {
8685 case KF_ARG_PTR_TO_CTX:
8686 if (reg->type != PTR_TO_CTX) {
8687 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
8688 return -EINVAL;
8689 }
fd264ca0
YS
8690
8691 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8692 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
8693 if (ret < 0)
8694 return -EINVAL;
8695 meta->ret_btf_id = ret;
8696 }
00b85860 8697 break;
ac9f0605
KKD
8698 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
8699 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8700 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8701 return -EINVAL;
8702 }
8703 if (!reg->ref_obj_id) {
8704 verbose(env, "allocated object must be referenced\n");
8705 return -EINVAL;
8706 }
8707 if (meta->btf == btf_vmlinux &&
8708 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8709 meta->arg_obj_drop.btf = reg->btf;
8710 meta->arg_obj_drop.btf_id = reg->btf_id;
8711 }
8712 break;
00b85860
KKD
8713 case KF_ARG_PTR_TO_KPTR:
8714 if (reg->type != PTR_TO_MAP_VALUE) {
8715 verbose(env, "arg#0 expected pointer to map value\n");
8716 return -EINVAL;
8717 }
8718 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
8719 if (ret < 0)
8720 return ret;
8721 break;
8722 case KF_ARG_PTR_TO_DYNPTR:
8723 if (reg->type != PTR_TO_STACK) {
8724 verbose(env, "arg#%d expected pointer to stack\n", i);
8725 return -EINVAL;
8726 }
8727
8728 if (!is_dynptr_reg_valid_init(env, reg)) {
8729 verbose(env, "arg#%d pointer type %s %s must be valid and initialized\n",
8730 i, btf_type_str(ref_t), ref_tname);
8731 return -EINVAL;
8732 }
8733
8734 if (!is_dynptr_type_expected(env, reg, ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL)) {
8735 verbose(env, "arg#%d pointer type %s %s points to unsupported dynamic pointer type\n",
8736 i, btf_type_str(ref_t), ref_tname);
8737 return -EINVAL;
8738 }
8739 break;
8cab76ec
KKD
8740 case KF_ARG_PTR_TO_LIST_HEAD:
8741 if (reg->type != PTR_TO_MAP_VALUE &&
8742 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8743 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
8744 return -EINVAL;
8745 }
8746 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
8747 verbose(env, "allocated object must be referenced\n");
8748 return -EINVAL;
8749 }
8750 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
8751 if (ret < 0)
8752 return ret;
8753 break;
8754 case KF_ARG_PTR_TO_LIST_NODE:
8755 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
8756 verbose(env, "arg#%d expected pointer to allocated object\n", i);
8757 return -EINVAL;
8758 }
8759 if (!reg->ref_obj_id) {
8760 verbose(env, "allocated object must be referenced\n");
8761 return -EINVAL;
8762 }
8763 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
8764 if (ret < 0)
8765 return ret;
8766 break;
00b85860
KKD
8767 case KF_ARG_PTR_TO_BTF_ID:
8768 /* Only base_type is checked, further checks are done here */
3f00c523
DV
8769 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
8770 bpf_type_has_unsafe_modifiers(reg->type)) &&
8771 !reg2btf_ids[base_type(reg->type)]) {
8772 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
8773 verbose(env, "expected %s or socket\n",
8774 reg_type_str(env, base_type(reg->type) |
8775 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
00b85860
KKD
8776 return -EINVAL;
8777 }
8778 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
8779 if (ret < 0)
8780 return ret;
8781 break;
8782 case KF_ARG_PTR_TO_MEM:
8783 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
8784 if (IS_ERR(resolve_ret)) {
8785 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8786 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
8787 return -EINVAL;
8788 }
8789 ret = check_mem_reg(env, reg, regno, type_size);
8790 if (ret < 0)
8791 return ret;
8792 break;
8793 case KF_ARG_PTR_TO_MEM_SIZE:
8794 ret = check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1);
8795 if (ret < 0) {
8796 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
8797 return ret;
8798 }
8799 /* Skip next '__sz' argument */
8800 i++;
8801 break;
8802 }
8803 }
8804
8805 if (is_kfunc_release(meta) && !meta->release_regno) {
8806 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
8807 func_name);
8808 return -EINVAL;
8809 }
8810
8811 return 0;
8812}
8813
5c073f26
KKD
8814static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8815 int *insn_idx_p)
e6ac2450
MKL
8816{
8817 const struct btf_type *t, *func, *func_proto, *ptr_type;
8818 struct bpf_reg_state *regs = cur_regs(env);
8819 const char *func_name, *ptr_type_name;
00b85860 8820 struct bpf_kfunc_call_arg_meta meta;
e6ac2450 8821 u32 i, nargs, func_id, ptr_type_id;
5c073f26 8822 int err, insn_idx = *insn_idx_p;
e6ac2450 8823 const struct btf_param *args;
a35b9af4 8824 const struct btf_type *ret_t;
2357672c 8825 struct btf *desc_btf;
a4703e31 8826 u32 *kfunc_flags;
e6ac2450 8827
a5d82727
KKD
8828 /* skip for now, but return error when we find this in fixup_kfunc_call */
8829 if (!insn->imm)
8830 return 0;
8831
43bf0878 8832 desc_btf = find_kfunc_desc_btf(env, insn->off);
2357672c
KKD
8833 if (IS_ERR(desc_btf))
8834 return PTR_ERR(desc_btf);
8835
e6ac2450 8836 func_id = insn->imm;
2357672c
KKD
8837 func = btf_type_by_id(desc_btf, func_id);
8838 func_name = btf_name_by_offset(desc_btf, func->name_off);
8839 func_proto = btf_type_by_id(desc_btf, func->type);
e6ac2450 8840
a4703e31
KKD
8841 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
8842 if (!kfunc_flags) {
e6ac2450
MKL
8843 verbose(env, "calling kernel function %s is not allowed\n",
8844 func_name);
8845 return -EACCES;
8846 }
00b85860
KKD
8847
8848 /* Prepare kfunc call metadata */
8849 memset(&meta, 0, sizeof(meta));
8850 meta.btf = desc_btf;
8851 meta.func_id = func_id;
8852 meta.kfunc_flags = *kfunc_flags;
8853 meta.func_proto = func_proto;
8854 meta.func_name = func_name;
8855
8856 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
8857 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
4dd48c6f
AS
8858 return -EACCES;
8859 }
8860
00b85860
KKD
8861 if (is_kfunc_sleepable(&meta) && !env->prog->aux->sleepable) {
8862 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
8863 return -EACCES;
8864 }
eb1f7f71 8865
e6ac2450 8866 /* Check the arguments */
00b85860 8867 err = check_kfunc_args(env, &meta);
5c073f26 8868 if (err < 0)
e6ac2450 8869 return err;
5c073f26 8870 /* In case of release function, we get register number of refcounted
00b85860 8871 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
5c073f26 8872 */
00b85860
KKD
8873 if (meta.release_regno) {
8874 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
5c073f26
KKD
8875 if (err) {
8876 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
8877 func_name, func_id);
8878 return err;
8879 }
8880 }
e6ac2450
MKL
8881
8882 for (i = 0; i < CALLER_SAVED_REGS; i++)
8883 mark_reg_not_init(env, regs, caller_saved[i]);
8884
8885 /* Check return type */
2357672c 8886 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
5c073f26 8887
00b85860 8888 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
958cf2e2
KKD
8889 /* Only exception is bpf_obj_new_impl */
8890 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
8891 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
8892 return -EINVAL;
8893 }
5c073f26
KKD
8894 }
8895
e6ac2450
MKL
8896 if (btf_type_is_scalar(t)) {
8897 mark_reg_unknown(env, regs, BPF_REG_0);
8898 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
8899 } else if (btf_type_is_ptr(t)) {
958cf2e2
KKD
8900 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
8901
8902 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
8903 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
958cf2e2
KKD
8904 struct btf *ret_btf;
8905 u32 ret_btf_id;
8906
e181d3f1
KKD
8907 if (unlikely(!bpf_global_ma_set))
8908 return -ENOMEM;
8909
958cf2e2
KKD
8910 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
8911 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
8912 return -EINVAL;
8913 }
8914
8915 ret_btf = env->prog->aux->btf;
8916 ret_btf_id = meta.arg_constant.value;
8917
8918 /* This may be NULL due to user not supplying a BTF */
8919 if (!ret_btf) {
8920 verbose(env, "bpf_obj_new requires prog BTF\n");
8921 return -EINVAL;
8922 }
8923
8924 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
8925 if (!ret_t || !__btf_type_is_struct(ret_t)) {
8926 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
8927 return -EINVAL;
8928 }
8929
8930 mark_reg_known_zero(env, regs, BPF_REG_0);
8931 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8932 regs[BPF_REG_0].btf = ret_btf;
8933 regs[BPF_REG_0].btf_id = ret_btf_id;
8934
8935 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size;
8936 env->insn_aux_data[insn_idx].kptr_struct_meta =
8937 btf_find_struct_meta(ret_btf, ret_btf_id);
ac9f0605
KKD
8938 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
8939 env->insn_aux_data[insn_idx].kptr_struct_meta =
8940 btf_find_struct_meta(meta.arg_obj_drop.btf,
8941 meta.arg_obj_drop.btf_id);
8cab76ec
KKD
8942 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
8943 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
8944 struct btf_field *field = meta.arg_list_head.field;
8945
8946 mark_reg_known_zero(env, regs, BPF_REG_0);
8947 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
8948 regs[BPF_REG_0].btf = field->list_head.btf;
8949 regs[BPF_REG_0].btf_id = field->list_head.value_btf_id;
8950 regs[BPF_REG_0].off = field->list_head.node_offset;
fd264ca0
YS
8951 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
8952 mark_reg_known_zero(env, regs, BPF_REG_0);
8953 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
8954 regs[BPF_REG_0].btf = desc_btf;
8955 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
a35b9af4
YS
8956 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
8957 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
8958 if (!ret_t || !btf_type_is_struct(ret_t)) {
8959 verbose(env,
8960 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
8961 return -EINVAL;
8962 }
8963
8964 mark_reg_known_zero(env, regs, BPF_REG_0);
8965 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
8966 regs[BPF_REG_0].btf = desc_btf;
8967 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
958cf2e2
KKD
8968 } else {
8969 verbose(env, "kernel function %s unhandled dynamic return type\n",
8970 meta.func_name);
8971 return -EFAULT;
8972 }
8973 } else if (!__btf_type_is_struct(ptr_type)) {
eb1f7f71
BT
8974 if (!meta.r0_size) {
8975 ptr_type_name = btf_name_by_offset(desc_btf,
8976 ptr_type->name_off);
8977 verbose(env,
8978 "kernel function %s returns pointer type %s %s is not supported\n",
8979 func_name,
8980 btf_type_str(ptr_type),
8981 ptr_type_name);
8982 return -EINVAL;
8983 }
8984
8985 mark_reg_known_zero(env, regs, BPF_REG_0);
8986 regs[BPF_REG_0].type = PTR_TO_MEM;
8987 regs[BPF_REG_0].mem_size = meta.r0_size;
8988
8989 if (meta.r0_rdonly)
8990 regs[BPF_REG_0].type |= MEM_RDONLY;
8991
8992 /* Ensures we don't access the memory after a release_reference() */
8993 if (meta.ref_obj_id)
8994 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8995 } else {
8996 mark_reg_known_zero(env, regs, BPF_REG_0);
8997 regs[BPF_REG_0].btf = desc_btf;
8998 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
8999 regs[BPF_REG_0].btf_id = ptr_type_id;
e6ac2450 9000 }
958cf2e2 9001
00b85860 9002 if (is_kfunc_ret_null(&meta)) {
5c073f26
KKD
9003 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
9004 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
9005 regs[BPF_REG_0].id = ++env->id_gen;
9006 }
e6ac2450 9007 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
00b85860 9008 if (is_kfunc_acquire(&meta)) {
5c073f26
KKD
9009 int id = acquire_reference_state(env, insn_idx);
9010
9011 if (id < 0)
9012 return id;
00b85860
KKD
9013 if (is_kfunc_ret_null(&meta))
9014 regs[BPF_REG_0].id = id;
5c073f26
KKD
9015 regs[BPF_REG_0].ref_obj_id = id;
9016 }
00b85860
KKD
9017 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
9018 regs[BPF_REG_0].id = ++env->id_gen;
e6ac2450
MKL
9019 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
9020
9021 nargs = btf_type_vlen(func_proto);
9022 args = (const struct btf_param *)(func_proto + 1);
9023 for (i = 0; i < nargs; i++) {
9024 u32 regno = i + 1;
9025
2357672c 9026 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
e6ac2450
MKL
9027 if (btf_type_is_ptr(t))
9028 mark_btf_func_reg_size(env, regno, sizeof(void *));
9029 else
9030 /* scalar. ensured by btf_check_kfunc_arg_match() */
9031 mark_btf_func_reg_size(env, regno, t->size);
9032 }
9033
9034 return 0;
9035}
9036
b03c9f9f
EC
9037static bool signed_add_overflows(s64 a, s64 b)
9038{
9039 /* Do the add in u64, where overflow is well-defined */
9040 s64 res = (s64)((u64)a + (u64)b);
9041
9042 if (b < 0)
9043 return res > a;
9044 return res < a;
9045}
9046
bc895e8b 9047static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
9048{
9049 /* Do the add in u32, where overflow is well-defined */
9050 s32 res = (s32)((u32)a + (u32)b);
9051
9052 if (b < 0)
9053 return res > a;
9054 return res < a;
9055}
9056
bc895e8b 9057static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
9058{
9059 /* Do the sub in u64, where overflow is well-defined */
9060 s64 res = (s64)((u64)a - (u64)b);
9061
9062 if (b < 0)
9063 return res < a;
9064 return res > a;
969bf05e
AS
9065}
9066
3f50f132
JF
9067static bool signed_sub32_overflows(s32 a, s32 b)
9068{
bc895e8b 9069 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
9070 s32 res = (s32)((u32)a - (u32)b);
9071
9072 if (b < 0)
9073 return res < a;
9074 return res > a;
9075}
9076
bb7f0f98
AS
9077static bool check_reg_sane_offset(struct bpf_verifier_env *env,
9078 const struct bpf_reg_state *reg,
9079 enum bpf_reg_type type)
9080{
9081 bool known = tnum_is_const(reg->var_off);
9082 s64 val = reg->var_off.value;
9083 s64 smin = reg->smin_value;
9084
9085 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
9086 verbose(env, "math between %s pointer and %lld is not allowed\n",
c25b2ae1 9087 reg_type_str(env, type), val);
bb7f0f98
AS
9088 return false;
9089 }
9090
9091 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
9092 verbose(env, "%s pointer offset %d is not allowed\n",
c25b2ae1 9093 reg_type_str(env, type), reg->off);
bb7f0f98
AS
9094 return false;
9095 }
9096
9097 if (smin == S64_MIN) {
9098 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
c25b2ae1 9099 reg_type_str(env, type));
bb7f0f98
AS
9100 return false;
9101 }
9102
9103 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
9104 verbose(env, "value %lld makes %s pointer be out of bounds\n",
c25b2ae1 9105 smin, reg_type_str(env, type));
bb7f0f98
AS
9106 return false;
9107 }
9108
9109 return true;
9110}
9111
a6aaece0
DB
9112enum {
9113 REASON_BOUNDS = -1,
9114 REASON_TYPE = -2,
9115 REASON_PATHS = -3,
9116 REASON_LIMIT = -4,
9117 REASON_STACK = -5,
9118};
9119
979d63d5 9120static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 9121 u32 *alu_limit, bool mask_to_left)
979d63d5 9122{
7fedb63a 9123 u32 max = 0, ptr_limit = 0;
979d63d5
DB
9124
9125 switch (ptr_reg->type) {
9126 case PTR_TO_STACK:
1b1597e6 9127 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
9128 * left direction, see BPF_REG_FP. Also, unknown scalar
9129 * offset where we would need to deal with min/max bounds is
9130 * currently prohibited for unprivileged.
1b1597e6
PK
9131 */
9132 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 9133 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 9134 break;
979d63d5 9135 case PTR_TO_MAP_VALUE:
1b1597e6 9136 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
9137 ptr_limit = (mask_to_left ?
9138 ptr_reg->smin_value :
9139 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 9140 break;
979d63d5 9141 default:
a6aaece0 9142 return REASON_TYPE;
979d63d5 9143 }
b658bbb8
DB
9144
9145 if (ptr_limit >= max)
a6aaece0 9146 return REASON_LIMIT;
b658bbb8
DB
9147 *alu_limit = ptr_limit;
9148 return 0;
979d63d5
DB
9149}
9150
d3bd7413
DB
9151static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
9152 const struct bpf_insn *insn)
9153{
2c78ee89 9154 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
9155}
9156
9157static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
9158 u32 alu_state, u32 alu_limit)
9159{
9160 /* If we arrived here from different branches with different
9161 * state or limits to sanitize, then this won't work.
9162 */
9163 if (aux->alu_state &&
9164 (aux->alu_state != alu_state ||
9165 aux->alu_limit != alu_limit))
a6aaece0 9166 return REASON_PATHS;
d3bd7413 9167
e6ac5933 9168 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
9169 aux->alu_state = alu_state;
9170 aux->alu_limit = alu_limit;
9171 return 0;
9172}
9173
9174static int sanitize_val_alu(struct bpf_verifier_env *env,
9175 struct bpf_insn *insn)
9176{
9177 struct bpf_insn_aux_data *aux = cur_aux(env);
9178
9179 if (can_skip_alu_sanitation(env, insn))
9180 return 0;
9181
9182 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
9183}
9184
f5288193
DB
9185static bool sanitize_needed(u8 opcode)
9186{
9187 return opcode == BPF_ADD || opcode == BPF_SUB;
9188}
9189
3d0220f6
DB
9190struct bpf_sanitize_info {
9191 struct bpf_insn_aux_data aux;
bb01a1bb 9192 bool mask_to_left;
3d0220f6
DB
9193};
9194
9183671a
DB
9195static struct bpf_verifier_state *
9196sanitize_speculative_path(struct bpf_verifier_env *env,
9197 const struct bpf_insn *insn,
9198 u32 next_idx, u32 curr_idx)
9199{
9200 struct bpf_verifier_state *branch;
9201 struct bpf_reg_state *regs;
9202
9203 branch = push_stack(env, next_idx, curr_idx, true);
9204 if (branch && insn) {
9205 regs = branch->frame[branch->curframe]->regs;
9206 if (BPF_SRC(insn->code) == BPF_K) {
9207 mark_reg_unknown(env, regs, insn->dst_reg);
9208 } else if (BPF_SRC(insn->code) == BPF_X) {
9209 mark_reg_unknown(env, regs, insn->dst_reg);
9210 mark_reg_unknown(env, regs, insn->src_reg);
9211 }
9212 }
9213 return branch;
9214}
9215
979d63d5
DB
9216static int sanitize_ptr_alu(struct bpf_verifier_env *env,
9217 struct bpf_insn *insn,
9218 const struct bpf_reg_state *ptr_reg,
6f55b2f2 9219 const struct bpf_reg_state *off_reg,
979d63d5 9220 struct bpf_reg_state *dst_reg,
3d0220f6 9221 struct bpf_sanitize_info *info,
7fedb63a 9222 const bool commit_window)
979d63d5 9223{
3d0220f6 9224 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 9225 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 9226 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 9227 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
9228 bool ptr_is_dst_reg = ptr_reg == dst_reg;
9229 u8 opcode = BPF_OP(insn->code);
9230 u32 alu_state, alu_limit;
9231 struct bpf_reg_state tmp;
9232 bool ret;
f232326f 9233 int err;
979d63d5 9234
d3bd7413 9235 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
9236 return 0;
9237
9238 /* We already marked aux for masking from non-speculative
9239 * paths, thus we got here in the first place. We only care
9240 * to explore bad access from here.
9241 */
9242 if (vstate->speculative)
9243 goto do_sim;
9244
bb01a1bb
DB
9245 if (!commit_window) {
9246 if (!tnum_is_const(off_reg->var_off) &&
9247 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
9248 return REASON_BOUNDS;
9249
9250 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
9251 (opcode == BPF_SUB && !off_is_neg);
9252 }
9253
9254 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
9255 if (err < 0)
9256 return err;
9257
7fedb63a
DB
9258 if (commit_window) {
9259 /* In commit phase we narrow the masking window based on
9260 * the observed pointer move after the simulated operation.
9261 */
3d0220f6
DB
9262 alu_state = info->aux.alu_state;
9263 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
9264 } else {
9265 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 9266 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
9267 alu_state |= ptr_is_dst_reg ?
9268 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
e042aa53
DB
9269
9270 /* Limit pruning on unknown scalars to enable deep search for
9271 * potential masking differences from other program paths.
9272 */
9273 if (!off_is_imm)
9274 env->explore_alu_limits = true;
7fedb63a
DB
9275 }
9276
f232326f
PK
9277 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
9278 if (err < 0)
9279 return err;
979d63d5 9280do_sim:
7fedb63a
DB
9281 /* If we're in commit phase, we're done here given we already
9282 * pushed the truncated dst_reg into the speculative verification
9283 * stack.
a7036191
DB
9284 *
9285 * Also, when register is a known constant, we rewrite register-based
9286 * operation to immediate-based, and thus do not need masking (and as
9287 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 9288 */
a7036191 9289 if (commit_window || off_is_imm)
7fedb63a
DB
9290 return 0;
9291
979d63d5
DB
9292 /* Simulate and find potential out-of-bounds access under
9293 * speculative execution from truncation as a result of
9294 * masking when off was not within expected range. If off
9295 * sits in dst, then we temporarily need to move ptr there
9296 * to simulate dst (== 0) +/-= ptr. Needed, for example,
9297 * for cases where we use K-based arithmetic in one direction
9298 * and truncated reg-based in the other in order to explore
9299 * bad access.
9300 */
9301 if (!ptr_is_dst_reg) {
9302 tmp = *dst_reg;
9303 *dst_reg = *ptr_reg;
9304 }
9183671a
DB
9305 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
9306 env->insn_idx);
0803278b 9307 if (!ptr_is_dst_reg && ret)
979d63d5 9308 *dst_reg = tmp;
a6aaece0
DB
9309 return !ret ? REASON_STACK : 0;
9310}
9311
fe9a5ca7
DB
9312static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
9313{
9314 struct bpf_verifier_state *vstate = env->cur_state;
9315
9316 /* If we simulate paths under speculation, we don't update the
9317 * insn as 'seen' such that when we verify unreachable paths in
9318 * the non-speculative domain, sanitize_dead_code() can still
9319 * rewrite/sanitize them.
9320 */
9321 if (!vstate->speculative)
9322 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9323}
9324
a6aaece0
DB
9325static int sanitize_err(struct bpf_verifier_env *env,
9326 const struct bpf_insn *insn, int reason,
9327 const struct bpf_reg_state *off_reg,
9328 const struct bpf_reg_state *dst_reg)
9329{
9330 static const char *err = "pointer arithmetic with it prohibited for !root";
9331 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
9332 u32 dst = insn->dst_reg, src = insn->src_reg;
9333
9334 switch (reason) {
9335 case REASON_BOUNDS:
9336 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
9337 off_reg == dst_reg ? dst : src, err);
9338 break;
9339 case REASON_TYPE:
9340 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
9341 off_reg == dst_reg ? src : dst, err);
9342 break;
9343 case REASON_PATHS:
9344 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
9345 dst, op, err);
9346 break;
9347 case REASON_LIMIT:
9348 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
9349 dst, op, err);
9350 break;
9351 case REASON_STACK:
9352 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
9353 dst, err);
9354 break;
9355 default:
9356 verbose(env, "verifier internal error: unknown reason (%d)\n",
9357 reason);
9358 break;
9359 }
9360
9361 return -EACCES;
979d63d5
DB
9362}
9363
01f810ac
AM
9364/* check that stack access falls within stack limits and that 'reg' doesn't
9365 * have a variable offset.
9366 *
9367 * Variable offset is prohibited for unprivileged mode for simplicity since it
9368 * requires corresponding support in Spectre masking for stack ALU. See also
9369 * retrieve_ptr_limit().
9370 *
9371 *
9372 * 'off' includes 'reg->off'.
9373 */
9374static int check_stack_access_for_ptr_arithmetic(
9375 struct bpf_verifier_env *env,
9376 int regno,
9377 const struct bpf_reg_state *reg,
9378 int off)
9379{
9380 if (!tnum_is_const(reg->var_off)) {
9381 char tn_buf[48];
9382
9383 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
9384 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
9385 regno, tn_buf, off);
9386 return -EACCES;
9387 }
9388
9389 if (off >= 0 || off < -MAX_BPF_STACK) {
9390 verbose(env, "R%d stack pointer arithmetic goes out of range, "
9391 "prohibited for !root; off=%d\n", regno, off);
9392 return -EACCES;
9393 }
9394
9395 return 0;
9396}
9397
073815b7
DB
9398static int sanitize_check_bounds(struct bpf_verifier_env *env,
9399 const struct bpf_insn *insn,
9400 const struct bpf_reg_state *dst_reg)
9401{
9402 u32 dst = insn->dst_reg;
9403
9404 /* For unprivileged we require that resulting offset must be in bounds
9405 * in order to be able to sanitize access later on.
9406 */
9407 if (env->bypass_spec_v1)
9408 return 0;
9409
9410 switch (dst_reg->type) {
9411 case PTR_TO_STACK:
9412 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
9413 dst_reg->off + dst_reg->var_off.value))
9414 return -EACCES;
9415 break;
9416 case PTR_TO_MAP_VALUE:
61df10c7 9417 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
073815b7
DB
9418 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
9419 "prohibited for !root\n", dst);
9420 return -EACCES;
9421 }
9422 break;
9423 default:
9424 break;
9425 }
9426
9427 return 0;
9428}
01f810ac 9429
f1174f77 9430/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
9431 * Caller should also handle BPF_MOV case separately.
9432 * If we return -EACCES, caller may want to try again treating pointer as a
9433 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
9434 */
9435static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
9436 struct bpf_insn *insn,
9437 const struct bpf_reg_state *ptr_reg,
9438 const struct bpf_reg_state *off_reg)
969bf05e 9439{
f4d7e40a
AS
9440 struct bpf_verifier_state *vstate = env->cur_state;
9441 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9442 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 9443 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
9444 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
9445 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
9446 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
9447 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 9448 struct bpf_sanitize_info info = {};
969bf05e 9449 u8 opcode = BPF_OP(insn->code);
24c109bb 9450 u32 dst = insn->dst_reg;
979d63d5 9451 int ret;
969bf05e 9452
f1174f77 9453 dst_reg = &regs[dst];
969bf05e 9454
6f16101e
DB
9455 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
9456 smin_val > smax_val || umin_val > umax_val) {
9457 /* Taint dst register if offset had invalid bounds derived from
9458 * e.g. dead branches.
9459 */
f54c7898 9460 __mark_reg_unknown(env, dst_reg);
6f16101e 9461 return 0;
f1174f77
EC
9462 }
9463
9464 if (BPF_CLASS(insn->code) != BPF_ALU64) {
9465 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
9466 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9467 __mark_reg_unknown(env, dst_reg);
9468 return 0;
9469 }
9470
82abbf8d
AS
9471 verbose(env,
9472 "R%d 32-bit pointer arithmetic prohibited\n",
9473 dst);
f1174f77 9474 return -EACCES;
969bf05e
AS
9475 }
9476
c25b2ae1 9477 if (ptr_reg->type & PTR_MAYBE_NULL) {
aad2eeaf 9478 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
c25b2ae1 9479 dst, reg_type_str(env, ptr_reg->type));
f1174f77 9480 return -EACCES;
c25b2ae1
HL
9481 }
9482
9483 switch (base_type(ptr_reg->type)) {
aad2eeaf 9484 case CONST_PTR_TO_MAP:
7c696732
YS
9485 /* smin_val represents the known value */
9486 if (known && smin_val == 0 && opcode == BPF_ADD)
9487 break;
8731745e 9488 fallthrough;
aad2eeaf 9489 case PTR_TO_PACKET_END:
c64b7983 9490 case PTR_TO_SOCKET:
46f8bc92 9491 case PTR_TO_SOCK_COMMON:
655a51e5 9492 case PTR_TO_TCP_SOCK:
fada7fdc 9493 case PTR_TO_XDP_SOCK:
aad2eeaf 9494 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
c25b2ae1 9495 dst, reg_type_str(env, ptr_reg->type));
f1174f77 9496 return -EACCES;
aad2eeaf
JS
9497 default:
9498 break;
f1174f77
EC
9499 }
9500
9501 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
9502 * The id may be overwritten later if we create a new variable offset.
969bf05e 9503 */
f1174f77
EC
9504 dst_reg->type = ptr_reg->type;
9505 dst_reg->id = ptr_reg->id;
969bf05e 9506
bb7f0f98
AS
9507 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
9508 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
9509 return -EINVAL;
9510
3f50f132
JF
9511 /* pointer types do not carry 32-bit bounds at the moment. */
9512 __mark_reg32_unbounded(dst_reg);
9513
7fedb63a
DB
9514 if (sanitize_needed(opcode)) {
9515 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 9516 &info, false);
a6aaece0
DB
9517 if (ret < 0)
9518 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 9519 }
a6aaece0 9520
f1174f77
EC
9521 switch (opcode) {
9522 case BPF_ADD:
9523 /* We can take a fixed offset as long as it doesn't overflow
9524 * the s32 'off' field
969bf05e 9525 */
b03c9f9f
EC
9526 if (known && (ptr_reg->off + smin_val ==
9527 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 9528 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
9529 dst_reg->smin_value = smin_ptr;
9530 dst_reg->smax_value = smax_ptr;
9531 dst_reg->umin_value = umin_ptr;
9532 dst_reg->umax_value = umax_ptr;
f1174f77 9533 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 9534 dst_reg->off = ptr_reg->off + smin_val;
0962590e 9535 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
9536 break;
9537 }
f1174f77
EC
9538 /* A new variable offset is created. Note that off_reg->off
9539 * == 0, since it's a scalar.
9540 * dst_reg gets the pointer type and since some positive
9541 * integer value was added to the pointer, give it a new 'id'
9542 * if it's a PTR_TO_PACKET.
9543 * this creates a new 'base' pointer, off_reg (variable) gets
9544 * added into the variable offset, and we copy the fixed offset
9545 * from ptr_reg.
969bf05e 9546 */
b03c9f9f
EC
9547 if (signed_add_overflows(smin_ptr, smin_val) ||
9548 signed_add_overflows(smax_ptr, smax_val)) {
9549 dst_reg->smin_value = S64_MIN;
9550 dst_reg->smax_value = S64_MAX;
9551 } else {
9552 dst_reg->smin_value = smin_ptr + smin_val;
9553 dst_reg->smax_value = smax_ptr + smax_val;
9554 }
9555 if (umin_ptr + umin_val < umin_ptr ||
9556 umax_ptr + umax_val < umax_ptr) {
9557 dst_reg->umin_value = 0;
9558 dst_reg->umax_value = U64_MAX;
9559 } else {
9560 dst_reg->umin_value = umin_ptr + umin_val;
9561 dst_reg->umax_value = umax_ptr + umax_val;
9562 }
f1174f77
EC
9563 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
9564 dst_reg->off = ptr_reg->off;
0962590e 9565 dst_reg->raw = ptr_reg->raw;
de8f3a83 9566 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
9567 dst_reg->id = ++env->id_gen;
9568 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 9569 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
9570 }
9571 break;
9572 case BPF_SUB:
9573 if (dst_reg == off_reg) {
9574 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
9575 verbose(env, "R%d tried to subtract pointer from scalar\n",
9576 dst);
f1174f77
EC
9577 return -EACCES;
9578 }
9579 /* We don't allow subtraction from FP, because (according to
9580 * test_verifier.c test "invalid fp arithmetic", JITs might not
9581 * be able to deal with it.
969bf05e 9582 */
f1174f77 9583 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
9584 verbose(env, "R%d subtraction from stack pointer prohibited\n",
9585 dst);
f1174f77
EC
9586 return -EACCES;
9587 }
b03c9f9f
EC
9588 if (known && (ptr_reg->off - smin_val ==
9589 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 9590 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
9591 dst_reg->smin_value = smin_ptr;
9592 dst_reg->smax_value = smax_ptr;
9593 dst_reg->umin_value = umin_ptr;
9594 dst_reg->umax_value = umax_ptr;
f1174f77
EC
9595 dst_reg->var_off = ptr_reg->var_off;
9596 dst_reg->id = ptr_reg->id;
b03c9f9f 9597 dst_reg->off = ptr_reg->off - smin_val;
0962590e 9598 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
9599 break;
9600 }
f1174f77
EC
9601 /* A new variable offset is created. If the subtrahend is known
9602 * nonnegative, then any reg->range we had before is still good.
969bf05e 9603 */
b03c9f9f
EC
9604 if (signed_sub_overflows(smin_ptr, smax_val) ||
9605 signed_sub_overflows(smax_ptr, smin_val)) {
9606 /* Overflow possible, we know nothing */
9607 dst_reg->smin_value = S64_MIN;
9608 dst_reg->smax_value = S64_MAX;
9609 } else {
9610 dst_reg->smin_value = smin_ptr - smax_val;
9611 dst_reg->smax_value = smax_ptr - smin_val;
9612 }
9613 if (umin_ptr < umax_val) {
9614 /* Overflow possible, we know nothing */
9615 dst_reg->umin_value = 0;
9616 dst_reg->umax_value = U64_MAX;
9617 } else {
9618 /* Cannot overflow (as long as bounds are consistent) */
9619 dst_reg->umin_value = umin_ptr - umax_val;
9620 dst_reg->umax_value = umax_ptr - umin_val;
9621 }
f1174f77
EC
9622 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
9623 dst_reg->off = ptr_reg->off;
0962590e 9624 dst_reg->raw = ptr_reg->raw;
de8f3a83 9625 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
9626 dst_reg->id = ++env->id_gen;
9627 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 9628 if (smin_val < 0)
22dc4a0f 9629 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 9630 }
f1174f77
EC
9631 break;
9632 case BPF_AND:
9633 case BPF_OR:
9634 case BPF_XOR:
82abbf8d
AS
9635 /* bitwise ops on pointers are troublesome, prohibit. */
9636 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
9637 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
9638 return -EACCES;
9639 default:
9640 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
9641 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
9642 dst, bpf_alu_string[opcode >> 4]);
f1174f77 9643 return -EACCES;
43188702
JF
9644 }
9645
bb7f0f98
AS
9646 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
9647 return -EINVAL;
3844d153 9648 reg_bounds_sync(dst_reg);
073815b7
DB
9649 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
9650 return -EACCES;
7fedb63a
DB
9651 if (sanitize_needed(opcode)) {
9652 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 9653 &info, true);
7fedb63a
DB
9654 if (ret < 0)
9655 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
9656 }
9657
43188702
JF
9658 return 0;
9659}
9660
3f50f132
JF
9661static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
9662 struct bpf_reg_state *src_reg)
9663{
9664 s32 smin_val = src_reg->s32_min_value;
9665 s32 smax_val = src_reg->s32_max_value;
9666 u32 umin_val = src_reg->u32_min_value;
9667 u32 umax_val = src_reg->u32_max_value;
9668
9669 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
9670 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
9671 dst_reg->s32_min_value = S32_MIN;
9672 dst_reg->s32_max_value = S32_MAX;
9673 } else {
9674 dst_reg->s32_min_value += smin_val;
9675 dst_reg->s32_max_value += smax_val;
9676 }
9677 if (dst_reg->u32_min_value + umin_val < umin_val ||
9678 dst_reg->u32_max_value + umax_val < umax_val) {
9679 dst_reg->u32_min_value = 0;
9680 dst_reg->u32_max_value = U32_MAX;
9681 } else {
9682 dst_reg->u32_min_value += umin_val;
9683 dst_reg->u32_max_value += umax_val;
9684 }
9685}
9686
07cd2631
JF
9687static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
9688 struct bpf_reg_state *src_reg)
9689{
9690 s64 smin_val = src_reg->smin_value;
9691 s64 smax_val = src_reg->smax_value;
9692 u64 umin_val = src_reg->umin_value;
9693 u64 umax_val = src_reg->umax_value;
9694
9695 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
9696 signed_add_overflows(dst_reg->smax_value, smax_val)) {
9697 dst_reg->smin_value = S64_MIN;
9698 dst_reg->smax_value = S64_MAX;
9699 } else {
9700 dst_reg->smin_value += smin_val;
9701 dst_reg->smax_value += smax_val;
9702 }
9703 if (dst_reg->umin_value + umin_val < umin_val ||
9704 dst_reg->umax_value + umax_val < umax_val) {
9705 dst_reg->umin_value = 0;
9706 dst_reg->umax_value = U64_MAX;
9707 } else {
9708 dst_reg->umin_value += umin_val;
9709 dst_reg->umax_value += umax_val;
9710 }
3f50f132
JF
9711}
9712
9713static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
9714 struct bpf_reg_state *src_reg)
9715{
9716 s32 smin_val = src_reg->s32_min_value;
9717 s32 smax_val = src_reg->s32_max_value;
9718 u32 umin_val = src_reg->u32_min_value;
9719 u32 umax_val = src_reg->u32_max_value;
9720
9721 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
9722 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
9723 /* Overflow possible, we know nothing */
9724 dst_reg->s32_min_value = S32_MIN;
9725 dst_reg->s32_max_value = S32_MAX;
9726 } else {
9727 dst_reg->s32_min_value -= smax_val;
9728 dst_reg->s32_max_value -= smin_val;
9729 }
9730 if (dst_reg->u32_min_value < umax_val) {
9731 /* Overflow possible, we know nothing */
9732 dst_reg->u32_min_value = 0;
9733 dst_reg->u32_max_value = U32_MAX;
9734 } else {
9735 /* Cannot overflow (as long as bounds are consistent) */
9736 dst_reg->u32_min_value -= umax_val;
9737 dst_reg->u32_max_value -= umin_val;
9738 }
07cd2631
JF
9739}
9740
9741static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
9742 struct bpf_reg_state *src_reg)
9743{
9744 s64 smin_val = src_reg->smin_value;
9745 s64 smax_val = src_reg->smax_value;
9746 u64 umin_val = src_reg->umin_value;
9747 u64 umax_val = src_reg->umax_value;
9748
9749 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
9750 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
9751 /* Overflow possible, we know nothing */
9752 dst_reg->smin_value = S64_MIN;
9753 dst_reg->smax_value = S64_MAX;
9754 } else {
9755 dst_reg->smin_value -= smax_val;
9756 dst_reg->smax_value -= smin_val;
9757 }
9758 if (dst_reg->umin_value < umax_val) {
9759 /* Overflow possible, we know nothing */
9760 dst_reg->umin_value = 0;
9761 dst_reg->umax_value = U64_MAX;
9762 } else {
9763 /* Cannot overflow (as long as bounds are consistent) */
9764 dst_reg->umin_value -= umax_val;
9765 dst_reg->umax_value -= umin_val;
9766 }
3f50f132
JF
9767}
9768
9769static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
9770 struct bpf_reg_state *src_reg)
9771{
9772 s32 smin_val = src_reg->s32_min_value;
9773 u32 umin_val = src_reg->u32_min_value;
9774 u32 umax_val = src_reg->u32_max_value;
9775
9776 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
9777 /* Ain't nobody got time to multiply that sign */
9778 __mark_reg32_unbounded(dst_reg);
9779 return;
9780 }
9781 /* Both values are positive, so we can work with unsigned and
9782 * copy the result to signed (unless it exceeds S32_MAX).
9783 */
9784 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
9785 /* Potential overflow, we know nothing */
9786 __mark_reg32_unbounded(dst_reg);
9787 return;
9788 }
9789 dst_reg->u32_min_value *= umin_val;
9790 dst_reg->u32_max_value *= umax_val;
9791 if (dst_reg->u32_max_value > S32_MAX) {
9792 /* Overflow possible, we know nothing */
9793 dst_reg->s32_min_value = S32_MIN;
9794 dst_reg->s32_max_value = S32_MAX;
9795 } else {
9796 dst_reg->s32_min_value = dst_reg->u32_min_value;
9797 dst_reg->s32_max_value = dst_reg->u32_max_value;
9798 }
07cd2631
JF
9799}
9800
9801static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
9802 struct bpf_reg_state *src_reg)
9803{
9804 s64 smin_val = src_reg->smin_value;
9805 u64 umin_val = src_reg->umin_value;
9806 u64 umax_val = src_reg->umax_value;
9807
07cd2631
JF
9808 if (smin_val < 0 || dst_reg->smin_value < 0) {
9809 /* Ain't nobody got time to multiply that sign */
3f50f132 9810 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
9811 return;
9812 }
9813 /* Both values are positive, so we can work with unsigned and
9814 * copy the result to signed (unless it exceeds S64_MAX).
9815 */
9816 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
9817 /* Potential overflow, we know nothing */
3f50f132 9818 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
9819 return;
9820 }
9821 dst_reg->umin_value *= umin_val;
9822 dst_reg->umax_value *= umax_val;
9823 if (dst_reg->umax_value > S64_MAX) {
9824 /* Overflow possible, we know nothing */
9825 dst_reg->smin_value = S64_MIN;
9826 dst_reg->smax_value = S64_MAX;
9827 } else {
9828 dst_reg->smin_value = dst_reg->umin_value;
9829 dst_reg->smax_value = dst_reg->umax_value;
9830 }
9831}
9832
3f50f132
JF
9833static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
9834 struct bpf_reg_state *src_reg)
9835{
9836 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9837 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9838 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9839 s32 smin_val = src_reg->s32_min_value;
9840 u32 umax_val = src_reg->u32_max_value;
9841
049c4e13
DB
9842 if (src_known && dst_known) {
9843 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 9844 return;
049c4e13 9845 }
3f50f132
JF
9846
9847 /* We get our minimum from the var_off, since that's inherently
9848 * bitwise. Our maximum is the minimum of the operands' maxima.
9849 */
9850 dst_reg->u32_min_value = var32_off.value;
9851 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
9852 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9853 /* Lose signed bounds when ANDing negative numbers,
9854 * ain't nobody got time for that.
9855 */
9856 dst_reg->s32_min_value = S32_MIN;
9857 dst_reg->s32_max_value = S32_MAX;
9858 } else {
9859 /* ANDing two positives gives a positive, so safe to
9860 * cast result into s64.
9861 */
9862 dst_reg->s32_min_value = dst_reg->u32_min_value;
9863 dst_reg->s32_max_value = dst_reg->u32_max_value;
9864 }
3f50f132
JF
9865}
9866
07cd2631
JF
9867static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
9868 struct bpf_reg_state *src_reg)
9869{
3f50f132
JF
9870 bool src_known = tnum_is_const(src_reg->var_off);
9871 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
9872 s64 smin_val = src_reg->smin_value;
9873 u64 umax_val = src_reg->umax_value;
9874
3f50f132 9875 if (src_known && dst_known) {
4fbb38a3 9876 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
9877 return;
9878 }
9879
07cd2631
JF
9880 /* We get our minimum from the var_off, since that's inherently
9881 * bitwise. Our maximum is the minimum of the operands' maxima.
9882 */
07cd2631
JF
9883 dst_reg->umin_value = dst_reg->var_off.value;
9884 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
9885 if (dst_reg->smin_value < 0 || smin_val < 0) {
9886 /* Lose signed bounds when ANDing negative numbers,
9887 * ain't nobody got time for that.
9888 */
9889 dst_reg->smin_value = S64_MIN;
9890 dst_reg->smax_value = S64_MAX;
9891 } else {
9892 /* ANDing two positives gives a positive, so safe to
9893 * cast result into s64.
9894 */
9895 dst_reg->smin_value = dst_reg->umin_value;
9896 dst_reg->smax_value = dst_reg->umax_value;
9897 }
9898 /* We may learn something more from the var_off */
9899 __update_reg_bounds(dst_reg);
9900}
9901
3f50f132
JF
9902static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
9903 struct bpf_reg_state *src_reg)
9904{
9905 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9906 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9907 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
9908 s32 smin_val = src_reg->s32_min_value;
9909 u32 umin_val = src_reg->u32_min_value;
3f50f132 9910
049c4e13
DB
9911 if (src_known && dst_known) {
9912 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 9913 return;
049c4e13 9914 }
3f50f132
JF
9915
9916 /* We get our maximum from the var_off, and our minimum is the
9917 * maximum of the operands' minima
9918 */
9919 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
9920 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9921 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
9922 /* Lose signed bounds when ORing negative numbers,
9923 * ain't nobody got time for that.
9924 */
9925 dst_reg->s32_min_value = S32_MIN;
9926 dst_reg->s32_max_value = S32_MAX;
9927 } else {
9928 /* ORing two positives gives a positive, so safe to
9929 * cast result into s64.
9930 */
5b9fbeb7
DB
9931 dst_reg->s32_min_value = dst_reg->u32_min_value;
9932 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
9933 }
9934}
9935
07cd2631
JF
9936static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
9937 struct bpf_reg_state *src_reg)
9938{
3f50f132
JF
9939 bool src_known = tnum_is_const(src_reg->var_off);
9940 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
9941 s64 smin_val = src_reg->smin_value;
9942 u64 umin_val = src_reg->umin_value;
9943
3f50f132 9944 if (src_known && dst_known) {
4fbb38a3 9945 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
9946 return;
9947 }
9948
07cd2631
JF
9949 /* We get our maximum from the var_off, and our minimum is the
9950 * maximum of the operands' minima
9951 */
07cd2631
JF
9952 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
9953 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
9954 if (dst_reg->smin_value < 0 || smin_val < 0) {
9955 /* Lose signed bounds when ORing negative numbers,
9956 * ain't nobody got time for that.
9957 */
9958 dst_reg->smin_value = S64_MIN;
9959 dst_reg->smax_value = S64_MAX;
9960 } else {
9961 /* ORing two positives gives a positive, so safe to
9962 * cast result into s64.
9963 */
9964 dst_reg->smin_value = dst_reg->umin_value;
9965 dst_reg->smax_value = dst_reg->umax_value;
9966 }
9967 /* We may learn something more from the var_off */
9968 __update_reg_bounds(dst_reg);
9969}
9970
2921c90d
YS
9971static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
9972 struct bpf_reg_state *src_reg)
9973{
9974 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9975 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9976 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9977 s32 smin_val = src_reg->s32_min_value;
9978
049c4e13
DB
9979 if (src_known && dst_known) {
9980 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 9981 return;
049c4e13 9982 }
2921c90d
YS
9983
9984 /* We get both minimum and maximum from the var32_off. */
9985 dst_reg->u32_min_value = var32_off.value;
9986 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9987
9988 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
9989 /* XORing two positive sign numbers gives a positive,
9990 * so safe to cast u32 result into s32.
9991 */
9992 dst_reg->s32_min_value = dst_reg->u32_min_value;
9993 dst_reg->s32_max_value = dst_reg->u32_max_value;
9994 } else {
9995 dst_reg->s32_min_value = S32_MIN;
9996 dst_reg->s32_max_value = S32_MAX;
9997 }
9998}
9999
10000static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
10001 struct bpf_reg_state *src_reg)
10002{
10003 bool src_known = tnum_is_const(src_reg->var_off);
10004 bool dst_known = tnum_is_const(dst_reg->var_off);
10005 s64 smin_val = src_reg->smin_value;
10006
10007 if (src_known && dst_known) {
10008 /* dst_reg->var_off.value has been updated earlier */
10009 __mark_reg_known(dst_reg, dst_reg->var_off.value);
10010 return;
10011 }
10012
10013 /* We get both minimum and maximum from the var_off. */
10014 dst_reg->umin_value = dst_reg->var_off.value;
10015 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
10016
10017 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
10018 /* XORing two positive sign numbers gives a positive,
10019 * so safe to cast u64 result into s64.
10020 */
10021 dst_reg->smin_value = dst_reg->umin_value;
10022 dst_reg->smax_value = dst_reg->umax_value;
10023 } else {
10024 dst_reg->smin_value = S64_MIN;
10025 dst_reg->smax_value = S64_MAX;
10026 }
10027
10028 __update_reg_bounds(dst_reg);
10029}
10030
3f50f132
JF
10031static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10032 u64 umin_val, u64 umax_val)
07cd2631 10033{
07cd2631
JF
10034 /* We lose all sign bit information (except what we can pick
10035 * up from var_off)
10036 */
3f50f132
JF
10037 dst_reg->s32_min_value = S32_MIN;
10038 dst_reg->s32_max_value = S32_MAX;
10039 /* If we might shift our top bit out, then we know nothing */
10040 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
10041 dst_reg->u32_min_value = 0;
10042 dst_reg->u32_max_value = U32_MAX;
10043 } else {
10044 dst_reg->u32_min_value <<= umin_val;
10045 dst_reg->u32_max_value <<= umax_val;
10046 }
10047}
10048
10049static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
10050 struct bpf_reg_state *src_reg)
10051{
10052 u32 umax_val = src_reg->u32_max_value;
10053 u32 umin_val = src_reg->u32_min_value;
10054 /* u32 alu operation will zext upper bits */
10055 struct tnum subreg = tnum_subreg(dst_reg->var_off);
10056
10057 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10058 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
10059 /* Not required but being careful mark reg64 bounds as unknown so
10060 * that we are forced to pick them up from tnum and zext later and
10061 * if some path skips this step we are still safe.
10062 */
10063 __mark_reg64_unbounded(dst_reg);
10064 __update_reg32_bounds(dst_reg);
10065}
10066
10067static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
10068 u64 umin_val, u64 umax_val)
10069{
10070 /* Special case <<32 because it is a common compiler pattern to sign
10071 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
10072 * positive we know this shift will also be positive so we can track
10073 * bounds correctly. Otherwise we lose all sign bit information except
10074 * what we can pick up from var_off. Perhaps we can generalize this
10075 * later to shifts of any length.
10076 */
10077 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
10078 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
10079 else
10080 dst_reg->smax_value = S64_MAX;
10081
10082 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
10083 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
10084 else
10085 dst_reg->smin_value = S64_MIN;
10086
07cd2631
JF
10087 /* If we might shift our top bit out, then we know nothing */
10088 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
10089 dst_reg->umin_value = 0;
10090 dst_reg->umax_value = U64_MAX;
10091 } else {
10092 dst_reg->umin_value <<= umin_val;
10093 dst_reg->umax_value <<= umax_val;
10094 }
3f50f132
JF
10095}
10096
10097static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
10098 struct bpf_reg_state *src_reg)
10099{
10100 u64 umax_val = src_reg->umax_value;
10101 u64 umin_val = src_reg->umin_value;
10102
10103 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
10104 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
10105 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
10106
07cd2631
JF
10107 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
10108 /* We may learn something more from the var_off */
10109 __update_reg_bounds(dst_reg);
10110}
10111
3f50f132
JF
10112static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
10113 struct bpf_reg_state *src_reg)
10114{
10115 struct tnum subreg = tnum_subreg(dst_reg->var_off);
10116 u32 umax_val = src_reg->u32_max_value;
10117 u32 umin_val = src_reg->u32_min_value;
10118
10119 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
10120 * be negative, then either:
10121 * 1) src_reg might be zero, so the sign bit of the result is
10122 * unknown, so we lose our signed bounds
10123 * 2) it's known negative, thus the unsigned bounds capture the
10124 * signed bounds
10125 * 3) the signed bounds cross zero, so they tell us nothing
10126 * about the result
10127 * If the value in dst_reg is known nonnegative, then again the
18b24d78 10128 * unsigned bounds capture the signed bounds.
3f50f132
JF
10129 * Thus, in all cases it suffices to blow away our signed bounds
10130 * and rely on inferring new ones from the unsigned bounds and
10131 * var_off of the result.
10132 */
10133 dst_reg->s32_min_value = S32_MIN;
10134 dst_reg->s32_max_value = S32_MAX;
10135
10136 dst_reg->var_off = tnum_rshift(subreg, umin_val);
10137 dst_reg->u32_min_value >>= umax_val;
10138 dst_reg->u32_max_value >>= umin_val;
10139
10140 __mark_reg64_unbounded(dst_reg);
10141 __update_reg32_bounds(dst_reg);
10142}
10143
07cd2631
JF
10144static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
10145 struct bpf_reg_state *src_reg)
10146{
10147 u64 umax_val = src_reg->umax_value;
10148 u64 umin_val = src_reg->umin_value;
10149
10150 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
10151 * be negative, then either:
10152 * 1) src_reg might be zero, so the sign bit of the result is
10153 * unknown, so we lose our signed bounds
10154 * 2) it's known negative, thus the unsigned bounds capture the
10155 * signed bounds
10156 * 3) the signed bounds cross zero, so they tell us nothing
10157 * about the result
10158 * If the value in dst_reg is known nonnegative, then again the
18b24d78 10159 * unsigned bounds capture the signed bounds.
07cd2631
JF
10160 * Thus, in all cases it suffices to blow away our signed bounds
10161 * and rely on inferring new ones from the unsigned bounds and
10162 * var_off of the result.
10163 */
10164 dst_reg->smin_value = S64_MIN;
10165 dst_reg->smax_value = S64_MAX;
10166 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
10167 dst_reg->umin_value >>= umax_val;
10168 dst_reg->umax_value >>= umin_val;
3f50f132
JF
10169
10170 /* Its not easy to operate on alu32 bounds here because it depends
10171 * on bits being shifted in. Take easy way out and mark unbounded
10172 * so we can recalculate later from tnum.
10173 */
10174 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
10175 __update_reg_bounds(dst_reg);
10176}
10177
3f50f132
JF
10178static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
10179 struct bpf_reg_state *src_reg)
07cd2631 10180{
3f50f132 10181 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
10182
10183 /* Upon reaching here, src_known is true and
10184 * umax_val is equal to umin_val.
10185 */
3f50f132
JF
10186 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
10187 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 10188
3f50f132
JF
10189 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
10190
10191 /* blow away the dst_reg umin_value/umax_value and rely on
10192 * dst_reg var_off to refine the result.
10193 */
10194 dst_reg->u32_min_value = 0;
10195 dst_reg->u32_max_value = U32_MAX;
10196
10197 __mark_reg64_unbounded(dst_reg);
10198 __update_reg32_bounds(dst_reg);
10199}
10200
10201static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
10202 struct bpf_reg_state *src_reg)
10203{
10204 u64 umin_val = src_reg->umin_value;
10205
10206 /* Upon reaching here, src_known is true and umax_val is equal
10207 * to umin_val.
10208 */
10209 dst_reg->smin_value >>= umin_val;
10210 dst_reg->smax_value >>= umin_val;
10211
10212 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
10213
10214 /* blow away the dst_reg umin_value/umax_value and rely on
10215 * dst_reg var_off to refine the result.
10216 */
10217 dst_reg->umin_value = 0;
10218 dst_reg->umax_value = U64_MAX;
3f50f132
JF
10219
10220 /* Its not easy to operate on alu32 bounds here because it depends
10221 * on bits being shifted in from upper 32-bits. Take easy way out
10222 * and mark unbounded so we can recalculate later from tnum.
10223 */
10224 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
10225 __update_reg_bounds(dst_reg);
10226}
10227
468f6eaf
JH
10228/* WARNING: This function does calculations on 64-bit values, but the actual
10229 * execution may occur on 32-bit values. Therefore, things like bitshifts
10230 * need extra checks in the 32-bit case.
10231 */
f1174f77
EC
10232static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
10233 struct bpf_insn *insn,
10234 struct bpf_reg_state *dst_reg,
10235 struct bpf_reg_state src_reg)
969bf05e 10236{
638f5b90 10237 struct bpf_reg_state *regs = cur_regs(env);
48461135 10238 u8 opcode = BPF_OP(insn->code);
b0b3fb67 10239 bool src_known;
b03c9f9f
EC
10240 s64 smin_val, smax_val;
10241 u64 umin_val, umax_val;
3f50f132
JF
10242 s32 s32_min_val, s32_max_val;
10243 u32 u32_min_val, u32_max_val;
468f6eaf 10244 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 10245 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 10246 int ret;
b799207e 10247
b03c9f9f
EC
10248 smin_val = src_reg.smin_value;
10249 smax_val = src_reg.smax_value;
10250 umin_val = src_reg.umin_value;
10251 umax_val = src_reg.umax_value;
f23cc643 10252
3f50f132
JF
10253 s32_min_val = src_reg.s32_min_value;
10254 s32_max_val = src_reg.s32_max_value;
10255 u32_min_val = src_reg.u32_min_value;
10256 u32_max_val = src_reg.u32_max_value;
10257
10258 if (alu32) {
10259 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
10260 if ((src_known &&
10261 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
10262 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
10263 /* Taint dst register if offset had invalid bounds
10264 * derived from e.g. dead branches.
10265 */
10266 __mark_reg_unknown(env, dst_reg);
10267 return 0;
10268 }
10269 } else {
10270 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
10271 if ((src_known &&
10272 (smin_val != smax_val || umin_val != umax_val)) ||
10273 smin_val > smax_val || umin_val > umax_val) {
10274 /* Taint dst register if offset had invalid bounds
10275 * derived from e.g. dead branches.
10276 */
10277 __mark_reg_unknown(env, dst_reg);
10278 return 0;
10279 }
6f16101e
DB
10280 }
10281
bb7f0f98
AS
10282 if (!src_known &&
10283 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 10284 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
10285 return 0;
10286 }
10287
f5288193
DB
10288 if (sanitize_needed(opcode)) {
10289 ret = sanitize_val_alu(env, insn);
10290 if (ret < 0)
10291 return sanitize_err(env, insn, ret, NULL, NULL);
10292 }
10293
3f50f132
JF
10294 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
10295 * There are two classes of instructions: The first class we track both
10296 * alu32 and alu64 sign/unsigned bounds independently this provides the
10297 * greatest amount of precision when alu operations are mixed with jmp32
10298 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
10299 * and BPF_OR. This is possible because these ops have fairly easy to
10300 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
10301 * See alu32 verifier tests for examples. The second class of
10302 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
10303 * with regards to tracking sign/unsigned bounds because the bits may
10304 * cross subreg boundaries in the alu64 case. When this happens we mark
10305 * the reg unbounded in the subreg bound space and use the resulting
10306 * tnum to calculate an approximation of the sign/unsigned bounds.
10307 */
48461135
JB
10308 switch (opcode) {
10309 case BPF_ADD:
3f50f132 10310 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 10311 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 10312 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
10313 break;
10314 case BPF_SUB:
3f50f132 10315 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 10316 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 10317 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
10318 break;
10319 case BPF_MUL:
3f50f132
JF
10320 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
10321 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 10322 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
10323 break;
10324 case BPF_AND:
3f50f132
JF
10325 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
10326 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 10327 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
10328 break;
10329 case BPF_OR:
3f50f132
JF
10330 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
10331 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 10332 scalar_min_max_or(dst_reg, &src_reg);
48461135 10333 break;
2921c90d
YS
10334 case BPF_XOR:
10335 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
10336 scalar32_min_max_xor(dst_reg, &src_reg);
10337 scalar_min_max_xor(dst_reg, &src_reg);
10338 break;
48461135 10339 case BPF_LSH:
468f6eaf
JH
10340 if (umax_val >= insn_bitness) {
10341 /* Shifts greater than 31 or 63 are undefined.
10342 * This includes shifts by a negative number.
b03c9f9f 10343 */
61bd5218 10344 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
10345 break;
10346 }
3f50f132
JF
10347 if (alu32)
10348 scalar32_min_max_lsh(dst_reg, &src_reg);
10349 else
10350 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
10351 break;
10352 case BPF_RSH:
468f6eaf
JH
10353 if (umax_val >= insn_bitness) {
10354 /* Shifts greater than 31 or 63 are undefined.
10355 * This includes shifts by a negative number.
b03c9f9f 10356 */
61bd5218 10357 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
10358 break;
10359 }
3f50f132
JF
10360 if (alu32)
10361 scalar32_min_max_rsh(dst_reg, &src_reg);
10362 else
10363 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 10364 break;
9cbe1f5a
YS
10365 case BPF_ARSH:
10366 if (umax_val >= insn_bitness) {
10367 /* Shifts greater than 31 or 63 are undefined.
10368 * This includes shifts by a negative number.
10369 */
10370 mark_reg_unknown(env, regs, insn->dst_reg);
10371 break;
10372 }
3f50f132
JF
10373 if (alu32)
10374 scalar32_min_max_arsh(dst_reg, &src_reg);
10375 else
10376 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 10377 break;
48461135 10378 default:
61bd5218 10379 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
10380 break;
10381 }
10382
3f50f132
JF
10383 /* ALU32 ops are zero extended into 64bit register */
10384 if (alu32)
10385 zext_32_to_64(dst_reg);
3844d153 10386 reg_bounds_sync(dst_reg);
f1174f77
EC
10387 return 0;
10388}
10389
10390/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
10391 * and var_off.
10392 */
10393static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
10394 struct bpf_insn *insn)
10395{
f4d7e40a
AS
10396 struct bpf_verifier_state *vstate = env->cur_state;
10397 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10398 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
10399 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
10400 u8 opcode = BPF_OP(insn->code);
b5dc0163 10401 int err;
f1174f77
EC
10402
10403 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
10404 src_reg = NULL;
10405 if (dst_reg->type != SCALAR_VALUE)
10406 ptr_reg = dst_reg;
75748837
AS
10407 else
10408 /* Make sure ID is cleared otherwise dst_reg min/max could be
10409 * incorrectly propagated into other registers by find_equal_scalars()
10410 */
10411 dst_reg->id = 0;
f1174f77
EC
10412 if (BPF_SRC(insn->code) == BPF_X) {
10413 src_reg = &regs[insn->src_reg];
f1174f77
EC
10414 if (src_reg->type != SCALAR_VALUE) {
10415 if (dst_reg->type != SCALAR_VALUE) {
10416 /* Combining two pointers by any ALU op yields
82abbf8d
AS
10417 * an arbitrary scalar. Disallow all math except
10418 * pointer subtraction
f1174f77 10419 */
dd066823 10420 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
10421 mark_reg_unknown(env, regs, insn->dst_reg);
10422 return 0;
f1174f77 10423 }
82abbf8d
AS
10424 verbose(env, "R%d pointer %s pointer prohibited\n",
10425 insn->dst_reg,
10426 bpf_alu_string[opcode >> 4]);
10427 return -EACCES;
f1174f77
EC
10428 } else {
10429 /* scalar += pointer
10430 * This is legal, but we have to reverse our
10431 * src/dest handling in computing the range
10432 */
b5dc0163
AS
10433 err = mark_chain_precision(env, insn->dst_reg);
10434 if (err)
10435 return err;
82abbf8d
AS
10436 return adjust_ptr_min_max_vals(env, insn,
10437 src_reg, dst_reg);
f1174f77
EC
10438 }
10439 } else if (ptr_reg) {
10440 /* pointer += scalar */
b5dc0163
AS
10441 err = mark_chain_precision(env, insn->src_reg);
10442 if (err)
10443 return err;
82abbf8d
AS
10444 return adjust_ptr_min_max_vals(env, insn,
10445 dst_reg, src_reg);
a3b666bf
AN
10446 } else if (dst_reg->precise) {
10447 /* if dst_reg is precise, src_reg should be precise as well */
10448 err = mark_chain_precision(env, insn->src_reg);
10449 if (err)
10450 return err;
f1174f77
EC
10451 }
10452 } else {
10453 /* Pretend the src is a reg with a known value, since we only
10454 * need to be able to read from this state.
10455 */
10456 off_reg.type = SCALAR_VALUE;
b03c9f9f 10457 __mark_reg_known(&off_reg, insn->imm);
f1174f77 10458 src_reg = &off_reg;
82abbf8d
AS
10459 if (ptr_reg) /* pointer += K */
10460 return adjust_ptr_min_max_vals(env, insn,
10461 ptr_reg, src_reg);
f1174f77
EC
10462 }
10463
10464 /* Got here implies adding two SCALAR_VALUEs */
10465 if (WARN_ON_ONCE(ptr_reg)) {
0f55f9ed 10466 print_verifier_state(env, state, true);
61bd5218 10467 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
10468 return -EINVAL;
10469 }
10470 if (WARN_ON(!src_reg)) {
0f55f9ed 10471 print_verifier_state(env, state, true);
61bd5218 10472 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
10473 return -EINVAL;
10474 }
10475 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
10476}
10477
17a52670 10478/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 10479static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 10480{
638f5b90 10481 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
10482 u8 opcode = BPF_OP(insn->code);
10483 int err;
10484
10485 if (opcode == BPF_END || opcode == BPF_NEG) {
10486 if (opcode == BPF_NEG) {
395e942d 10487 if (BPF_SRC(insn->code) != BPF_K ||
17a52670
AS
10488 insn->src_reg != BPF_REG_0 ||
10489 insn->off != 0 || insn->imm != 0) {
61bd5218 10490 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
10491 return -EINVAL;
10492 }
10493 } else {
10494 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
10495 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
10496 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 10497 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
10498 return -EINVAL;
10499 }
10500 }
10501
10502 /* check src operand */
dc503a8a 10503 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10504 if (err)
10505 return err;
10506
1be7f75d 10507 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 10508 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
10509 insn->dst_reg);
10510 return -EACCES;
10511 }
10512
17a52670 10513 /* check dest operand */
dc503a8a 10514 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
10515 if (err)
10516 return err;
10517
10518 } else if (opcode == BPF_MOV) {
10519
10520 if (BPF_SRC(insn->code) == BPF_X) {
10521 if (insn->imm != 0 || insn->off != 0) {
61bd5218 10522 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
10523 return -EINVAL;
10524 }
10525
10526 /* check src operand */
dc503a8a 10527 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10528 if (err)
10529 return err;
10530 } else {
10531 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 10532 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
10533 return -EINVAL;
10534 }
10535 }
10536
fbeb1603
AF
10537 /* check dest operand, mark as required later */
10538 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10539 if (err)
10540 return err;
10541
10542 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
10543 struct bpf_reg_state *src_reg = regs + insn->src_reg;
10544 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
10545
17a52670
AS
10546 if (BPF_CLASS(insn->code) == BPF_ALU64) {
10547 /* case: R1 = R2
10548 * copy register state to dest reg
10549 */
75748837
AS
10550 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
10551 /* Assign src and dst registers the same ID
10552 * that will be used by find_equal_scalars()
10553 * to propagate min/max range.
10554 */
10555 src_reg->id = ++env->id_gen;
e434b8cd
JW
10556 *dst_reg = *src_reg;
10557 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 10558 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 10559 } else {
f1174f77 10560 /* R1 = (u32) R2 */
1be7f75d 10561 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
10562 verbose(env,
10563 "R%d partial copy of pointer\n",
1be7f75d
AS
10564 insn->src_reg);
10565 return -EACCES;
e434b8cd
JW
10566 } else if (src_reg->type == SCALAR_VALUE) {
10567 *dst_reg = *src_reg;
75748837
AS
10568 /* Make sure ID is cleared otherwise
10569 * dst_reg min/max could be incorrectly
10570 * propagated into src_reg by find_equal_scalars()
10571 */
10572 dst_reg->id = 0;
e434b8cd 10573 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 10574 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
10575 } else {
10576 mark_reg_unknown(env, regs,
10577 insn->dst_reg);
1be7f75d 10578 }
3f50f132 10579 zext_32_to_64(dst_reg);
3844d153 10580 reg_bounds_sync(dst_reg);
17a52670
AS
10581 }
10582 } else {
10583 /* case: R = imm
10584 * remember the value we stored into this reg
10585 */
fbeb1603
AF
10586 /* clear any state __mark_reg_known doesn't set */
10587 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 10588 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
10589 if (BPF_CLASS(insn->code) == BPF_ALU64) {
10590 __mark_reg_known(regs + insn->dst_reg,
10591 insn->imm);
10592 } else {
10593 __mark_reg_known(regs + insn->dst_reg,
10594 (u32)insn->imm);
10595 }
17a52670
AS
10596 }
10597
10598 } else if (opcode > BPF_END) {
61bd5218 10599 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
10600 return -EINVAL;
10601
10602 } else { /* all other ALU ops: and, sub, xor, add, ... */
10603
17a52670
AS
10604 if (BPF_SRC(insn->code) == BPF_X) {
10605 if (insn->imm != 0 || insn->off != 0) {
61bd5218 10606 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
10607 return -EINVAL;
10608 }
10609 /* check src1 operand */
dc503a8a 10610 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10611 if (err)
10612 return err;
10613 } else {
10614 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 10615 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
10616 return -EINVAL;
10617 }
10618 }
10619
10620 /* check src2 operand */
dc503a8a 10621 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10622 if (err)
10623 return err;
10624
10625 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
10626 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 10627 verbose(env, "div by zero\n");
17a52670
AS
10628 return -EINVAL;
10629 }
10630
229394e8
RV
10631 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
10632 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
10633 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
10634
10635 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 10636 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
10637 return -EINVAL;
10638 }
10639 }
10640
1a0dc1ac 10641 /* check dest operand */
dc503a8a 10642 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
10643 if (err)
10644 return err;
10645
f1174f77 10646 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
10647 }
10648
10649 return 0;
10650}
10651
f4d7e40a 10652static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 10653 struct bpf_reg_state *dst_reg,
f8ddadc4 10654 enum bpf_reg_type type,
fb2a311a 10655 bool range_right_open)
969bf05e 10656{
b239da34
KKD
10657 struct bpf_func_state *state;
10658 struct bpf_reg_state *reg;
10659 int new_range;
2d2be8ca 10660
fb2a311a
DB
10661 if (dst_reg->off < 0 ||
10662 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
10663 /* This doesn't give us any range */
10664 return;
10665
b03c9f9f
EC
10666 if (dst_reg->umax_value > MAX_PACKET_OFF ||
10667 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
10668 /* Risk of overflow. For instance, ptr + (1<<63) may be less
10669 * than pkt_end, but that's because it's also less than pkt.
10670 */
10671 return;
10672
fb2a311a
DB
10673 new_range = dst_reg->off;
10674 if (range_right_open)
2fa7d94a 10675 new_range++;
fb2a311a
DB
10676
10677 /* Examples for register markings:
2d2be8ca 10678 *
fb2a311a 10679 * pkt_data in dst register:
2d2be8ca
DB
10680 *
10681 * r2 = r3;
10682 * r2 += 8;
10683 * if (r2 > pkt_end) goto <handle exception>
10684 * <access okay>
10685 *
b4e432f1
DB
10686 * r2 = r3;
10687 * r2 += 8;
10688 * if (r2 < pkt_end) goto <access okay>
10689 * <handle exception>
10690 *
2d2be8ca
DB
10691 * Where:
10692 * r2 == dst_reg, pkt_end == src_reg
10693 * r2=pkt(id=n,off=8,r=0)
10694 * r3=pkt(id=n,off=0,r=0)
10695 *
fb2a311a 10696 * pkt_data in src register:
2d2be8ca
DB
10697 *
10698 * r2 = r3;
10699 * r2 += 8;
10700 * if (pkt_end >= r2) goto <access okay>
10701 * <handle exception>
10702 *
b4e432f1
DB
10703 * r2 = r3;
10704 * r2 += 8;
10705 * if (pkt_end <= r2) goto <handle exception>
10706 * <access okay>
10707 *
2d2be8ca
DB
10708 * Where:
10709 * pkt_end == dst_reg, r2 == src_reg
10710 * r2=pkt(id=n,off=8,r=0)
10711 * r3=pkt(id=n,off=0,r=0)
10712 *
10713 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
10714 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
10715 * and [r3, r3 + 8-1) respectively is safe to access depending on
10716 * the check.
969bf05e 10717 */
2d2be8ca 10718
f1174f77
EC
10719 /* If our ids match, then we must have the same max_value. And we
10720 * don't care about the other reg's fixed offset, since if it's too big
10721 * the range won't allow anything.
10722 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
10723 */
b239da34
KKD
10724 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10725 if (reg->type == type && reg->id == dst_reg->id)
10726 /* keep the maximum range already checked */
10727 reg->range = max(reg->range, new_range);
10728 }));
969bf05e
AS
10729}
10730
3f50f132 10731static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 10732{
3f50f132
JF
10733 struct tnum subreg = tnum_subreg(reg->var_off);
10734 s32 sval = (s32)val;
a72dafaf 10735
3f50f132
JF
10736 switch (opcode) {
10737 case BPF_JEQ:
10738 if (tnum_is_const(subreg))
10739 return !!tnum_equals_const(subreg, val);
10740 break;
10741 case BPF_JNE:
10742 if (tnum_is_const(subreg))
10743 return !tnum_equals_const(subreg, val);
10744 break;
10745 case BPF_JSET:
10746 if ((~subreg.mask & subreg.value) & val)
10747 return 1;
10748 if (!((subreg.mask | subreg.value) & val))
10749 return 0;
10750 break;
10751 case BPF_JGT:
10752 if (reg->u32_min_value > val)
10753 return 1;
10754 else if (reg->u32_max_value <= val)
10755 return 0;
10756 break;
10757 case BPF_JSGT:
10758 if (reg->s32_min_value > sval)
10759 return 1;
ee114dd6 10760 else if (reg->s32_max_value <= sval)
3f50f132
JF
10761 return 0;
10762 break;
10763 case BPF_JLT:
10764 if (reg->u32_max_value < val)
10765 return 1;
10766 else if (reg->u32_min_value >= val)
10767 return 0;
10768 break;
10769 case BPF_JSLT:
10770 if (reg->s32_max_value < sval)
10771 return 1;
10772 else if (reg->s32_min_value >= sval)
10773 return 0;
10774 break;
10775 case BPF_JGE:
10776 if (reg->u32_min_value >= val)
10777 return 1;
10778 else if (reg->u32_max_value < val)
10779 return 0;
10780 break;
10781 case BPF_JSGE:
10782 if (reg->s32_min_value >= sval)
10783 return 1;
10784 else if (reg->s32_max_value < sval)
10785 return 0;
10786 break;
10787 case BPF_JLE:
10788 if (reg->u32_max_value <= val)
10789 return 1;
10790 else if (reg->u32_min_value > val)
10791 return 0;
10792 break;
10793 case BPF_JSLE:
10794 if (reg->s32_max_value <= sval)
10795 return 1;
10796 else if (reg->s32_min_value > sval)
10797 return 0;
10798 break;
10799 }
4f7b3e82 10800
3f50f132
JF
10801 return -1;
10802}
092ed096 10803
3f50f132
JF
10804
10805static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
10806{
10807 s64 sval = (s64)val;
a72dafaf 10808
4f7b3e82
AS
10809 switch (opcode) {
10810 case BPF_JEQ:
10811 if (tnum_is_const(reg->var_off))
10812 return !!tnum_equals_const(reg->var_off, val);
10813 break;
10814 case BPF_JNE:
10815 if (tnum_is_const(reg->var_off))
10816 return !tnum_equals_const(reg->var_off, val);
10817 break;
960ea056
JK
10818 case BPF_JSET:
10819 if ((~reg->var_off.mask & reg->var_off.value) & val)
10820 return 1;
10821 if (!((reg->var_off.mask | reg->var_off.value) & val))
10822 return 0;
10823 break;
4f7b3e82
AS
10824 case BPF_JGT:
10825 if (reg->umin_value > val)
10826 return 1;
10827 else if (reg->umax_value <= val)
10828 return 0;
10829 break;
10830 case BPF_JSGT:
a72dafaf 10831 if (reg->smin_value > sval)
4f7b3e82 10832 return 1;
ee114dd6 10833 else if (reg->smax_value <= sval)
4f7b3e82
AS
10834 return 0;
10835 break;
10836 case BPF_JLT:
10837 if (reg->umax_value < val)
10838 return 1;
10839 else if (reg->umin_value >= val)
10840 return 0;
10841 break;
10842 case BPF_JSLT:
a72dafaf 10843 if (reg->smax_value < sval)
4f7b3e82 10844 return 1;
a72dafaf 10845 else if (reg->smin_value >= sval)
4f7b3e82
AS
10846 return 0;
10847 break;
10848 case BPF_JGE:
10849 if (reg->umin_value >= val)
10850 return 1;
10851 else if (reg->umax_value < val)
10852 return 0;
10853 break;
10854 case BPF_JSGE:
a72dafaf 10855 if (reg->smin_value >= sval)
4f7b3e82 10856 return 1;
a72dafaf 10857 else if (reg->smax_value < sval)
4f7b3e82
AS
10858 return 0;
10859 break;
10860 case BPF_JLE:
10861 if (reg->umax_value <= val)
10862 return 1;
10863 else if (reg->umin_value > val)
10864 return 0;
10865 break;
10866 case BPF_JSLE:
a72dafaf 10867 if (reg->smax_value <= sval)
4f7b3e82 10868 return 1;
a72dafaf 10869 else if (reg->smin_value > sval)
4f7b3e82
AS
10870 return 0;
10871 break;
10872 }
10873
10874 return -1;
10875}
10876
3f50f132
JF
10877/* compute branch direction of the expression "if (reg opcode val) goto target;"
10878 * and return:
10879 * 1 - branch will be taken and "goto target" will be executed
10880 * 0 - branch will not be taken and fall-through to next insn
10881 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
10882 * range [0,10]
604dca5e 10883 */
3f50f132
JF
10884static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
10885 bool is_jmp32)
604dca5e 10886{
cac616db
JF
10887 if (__is_pointer_value(false, reg)) {
10888 if (!reg_type_not_null(reg->type))
10889 return -1;
10890
10891 /* If pointer is valid tests against zero will fail so we can
10892 * use this to direct branch taken.
10893 */
10894 if (val != 0)
10895 return -1;
10896
10897 switch (opcode) {
10898 case BPF_JEQ:
10899 return 0;
10900 case BPF_JNE:
10901 return 1;
10902 default:
10903 return -1;
10904 }
10905 }
604dca5e 10906
3f50f132
JF
10907 if (is_jmp32)
10908 return is_branch32_taken(reg, val, opcode);
10909 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
10910}
10911
6d94e741
AS
10912static int flip_opcode(u32 opcode)
10913{
10914 /* How can we transform "a <op> b" into "b <op> a"? */
10915 static const u8 opcode_flip[16] = {
10916 /* these stay the same */
10917 [BPF_JEQ >> 4] = BPF_JEQ,
10918 [BPF_JNE >> 4] = BPF_JNE,
10919 [BPF_JSET >> 4] = BPF_JSET,
10920 /* these swap "lesser" and "greater" (L and G in the opcodes) */
10921 [BPF_JGE >> 4] = BPF_JLE,
10922 [BPF_JGT >> 4] = BPF_JLT,
10923 [BPF_JLE >> 4] = BPF_JGE,
10924 [BPF_JLT >> 4] = BPF_JGT,
10925 [BPF_JSGE >> 4] = BPF_JSLE,
10926 [BPF_JSGT >> 4] = BPF_JSLT,
10927 [BPF_JSLE >> 4] = BPF_JSGE,
10928 [BPF_JSLT >> 4] = BPF_JSGT
10929 };
10930 return opcode_flip[opcode >> 4];
10931}
10932
10933static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
10934 struct bpf_reg_state *src_reg,
10935 u8 opcode)
10936{
10937 struct bpf_reg_state *pkt;
10938
10939 if (src_reg->type == PTR_TO_PACKET_END) {
10940 pkt = dst_reg;
10941 } else if (dst_reg->type == PTR_TO_PACKET_END) {
10942 pkt = src_reg;
10943 opcode = flip_opcode(opcode);
10944 } else {
10945 return -1;
10946 }
10947
10948 if (pkt->range >= 0)
10949 return -1;
10950
10951 switch (opcode) {
10952 case BPF_JLE:
10953 /* pkt <= pkt_end */
10954 fallthrough;
10955 case BPF_JGT:
10956 /* pkt > pkt_end */
10957 if (pkt->range == BEYOND_PKT_END)
10958 /* pkt has at last one extra byte beyond pkt_end */
10959 return opcode == BPF_JGT;
10960 break;
10961 case BPF_JLT:
10962 /* pkt < pkt_end */
10963 fallthrough;
10964 case BPF_JGE:
10965 /* pkt >= pkt_end */
10966 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
10967 return opcode == BPF_JGE;
10968 break;
10969 }
10970 return -1;
10971}
10972
48461135
JB
10973/* Adjusts the register min/max values in the case that the dst_reg is the
10974 * variable register that we are working on, and src_reg is a constant or we're
10975 * simply doing a BPF_K check.
f1174f77 10976 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
10977 */
10978static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
10979 struct bpf_reg_state *false_reg,
10980 u64 val, u32 val32,
092ed096 10981 u8 opcode, bool is_jmp32)
48461135 10982{
3f50f132
JF
10983 struct tnum false_32off = tnum_subreg(false_reg->var_off);
10984 struct tnum false_64off = false_reg->var_off;
10985 struct tnum true_32off = tnum_subreg(true_reg->var_off);
10986 struct tnum true_64off = true_reg->var_off;
10987 s64 sval = (s64)val;
10988 s32 sval32 = (s32)val32;
a72dafaf 10989
f1174f77
EC
10990 /* If the dst_reg is a pointer, we can't learn anything about its
10991 * variable offset from the compare (unless src_reg were a pointer into
10992 * the same object, but we don't bother with that.
10993 * Since false_reg and true_reg have the same type by construction, we
10994 * only need to check one of them for pointerness.
10995 */
10996 if (__is_pointer_value(false, false_reg))
10997 return;
4cabc5b1 10998
48461135 10999 switch (opcode) {
a12ca627
DB
11000 /* JEQ/JNE comparison doesn't change the register equivalence.
11001 *
11002 * r1 = r2;
11003 * if (r1 == 42) goto label;
11004 * ...
11005 * label: // here both r1 and r2 are known to be 42.
11006 *
11007 * Hence when marking register as known preserve it's ID.
11008 */
48461135 11009 case BPF_JEQ:
a12ca627
DB
11010 if (is_jmp32) {
11011 __mark_reg32_known(true_reg, val32);
11012 true_32off = tnum_subreg(true_reg->var_off);
11013 } else {
11014 ___mark_reg_known(true_reg, val);
11015 true_64off = true_reg->var_off;
11016 }
11017 break;
48461135 11018 case BPF_JNE:
a12ca627
DB
11019 if (is_jmp32) {
11020 __mark_reg32_known(false_reg, val32);
11021 false_32off = tnum_subreg(false_reg->var_off);
11022 } else {
11023 ___mark_reg_known(false_reg, val);
11024 false_64off = false_reg->var_off;
11025 }
48461135 11026 break;
960ea056 11027 case BPF_JSET:
3f50f132
JF
11028 if (is_jmp32) {
11029 false_32off = tnum_and(false_32off, tnum_const(~val32));
11030 if (is_power_of_2(val32))
11031 true_32off = tnum_or(true_32off,
11032 tnum_const(val32));
11033 } else {
11034 false_64off = tnum_and(false_64off, tnum_const(~val));
11035 if (is_power_of_2(val))
11036 true_64off = tnum_or(true_64off,
11037 tnum_const(val));
11038 }
960ea056 11039 break;
48461135 11040 case BPF_JGE:
a72dafaf
JW
11041 case BPF_JGT:
11042 {
3f50f132
JF
11043 if (is_jmp32) {
11044 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
11045 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
11046
11047 false_reg->u32_max_value = min(false_reg->u32_max_value,
11048 false_umax);
11049 true_reg->u32_min_value = max(true_reg->u32_min_value,
11050 true_umin);
11051 } else {
11052 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
11053 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
11054
11055 false_reg->umax_value = min(false_reg->umax_value, false_umax);
11056 true_reg->umin_value = max(true_reg->umin_value, true_umin);
11057 }
b03c9f9f 11058 break;
a72dafaf 11059 }
48461135 11060 case BPF_JSGE:
a72dafaf
JW
11061 case BPF_JSGT:
11062 {
3f50f132
JF
11063 if (is_jmp32) {
11064 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
11065 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 11066
3f50f132
JF
11067 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
11068 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
11069 } else {
11070 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
11071 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
11072
11073 false_reg->smax_value = min(false_reg->smax_value, false_smax);
11074 true_reg->smin_value = max(true_reg->smin_value, true_smin);
11075 }
48461135 11076 break;
a72dafaf 11077 }
b4e432f1 11078 case BPF_JLE:
a72dafaf
JW
11079 case BPF_JLT:
11080 {
3f50f132
JF
11081 if (is_jmp32) {
11082 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
11083 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
11084
11085 false_reg->u32_min_value = max(false_reg->u32_min_value,
11086 false_umin);
11087 true_reg->u32_max_value = min(true_reg->u32_max_value,
11088 true_umax);
11089 } else {
11090 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
11091 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
11092
11093 false_reg->umin_value = max(false_reg->umin_value, false_umin);
11094 true_reg->umax_value = min(true_reg->umax_value, true_umax);
11095 }
b4e432f1 11096 break;
a72dafaf 11097 }
b4e432f1 11098 case BPF_JSLE:
a72dafaf
JW
11099 case BPF_JSLT:
11100 {
3f50f132
JF
11101 if (is_jmp32) {
11102 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
11103 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 11104
3f50f132
JF
11105 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
11106 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
11107 } else {
11108 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
11109 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
11110
11111 false_reg->smin_value = max(false_reg->smin_value, false_smin);
11112 true_reg->smax_value = min(true_reg->smax_value, true_smax);
11113 }
b4e432f1 11114 break;
a72dafaf 11115 }
48461135 11116 default:
0fc31b10 11117 return;
48461135
JB
11118 }
11119
3f50f132
JF
11120 if (is_jmp32) {
11121 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
11122 tnum_subreg(false_32off));
11123 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
11124 tnum_subreg(true_32off));
11125 __reg_combine_32_into_64(false_reg);
11126 __reg_combine_32_into_64(true_reg);
11127 } else {
11128 false_reg->var_off = false_64off;
11129 true_reg->var_off = true_64off;
11130 __reg_combine_64_into_32(false_reg);
11131 __reg_combine_64_into_32(true_reg);
11132 }
48461135
JB
11133}
11134
f1174f77
EC
11135/* Same as above, but for the case that dst_reg holds a constant and src_reg is
11136 * the variable reg.
48461135
JB
11137 */
11138static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
11139 struct bpf_reg_state *false_reg,
11140 u64 val, u32 val32,
092ed096 11141 u8 opcode, bool is_jmp32)
48461135 11142{
6d94e741 11143 opcode = flip_opcode(opcode);
0fc31b10
JH
11144 /* This uses zero as "not present in table"; luckily the zero opcode,
11145 * BPF_JA, can't get here.
b03c9f9f 11146 */
0fc31b10 11147 if (opcode)
3f50f132 11148 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
11149}
11150
11151/* Regs are known to be equal, so intersect their min/max/var_off */
11152static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
11153 struct bpf_reg_state *dst_reg)
11154{
b03c9f9f
EC
11155 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
11156 dst_reg->umin_value);
11157 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
11158 dst_reg->umax_value);
11159 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
11160 dst_reg->smin_value);
11161 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
11162 dst_reg->smax_value);
f1174f77
EC
11163 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
11164 dst_reg->var_off);
3844d153
DB
11165 reg_bounds_sync(src_reg);
11166 reg_bounds_sync(dst_reg);
f1174f77
EC
11167}
11168
11169static void reg_combine_min_max(struct bpf_reg_state *true_src,
11170 struct bpf_reg_state *true_dst,
11171 struct bpf_reg_state *false_src,
11172 struct bpf_reg_state *false_dst,
11173 u8 opcode)
11174{
11175 switch (opcode) {
11176 case BPF_JEQ:
11177 __reg_combine_min_max(true_src, true_dst);
11178 break;
11179 case BPF_JNE:
11180 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 11181 break;
4cabc5b1 11182 }
48461135
JB
11183}
11184
fd978bf7
JS
11185static void mark_ptr_or_null_reg(struct bpf_func_state *state,
11186 struct bpf_reg_state *reg, u32 id,
840b9615 11187 bool is_null)
57a09bf0 11188{
c25b2ae1 11189 if (type_may_be_null(reg->type) && reg->id == id &&
93c230e3 11190 !WARN_ON_ONCE(!reg->id)) {
df57f38a
KKD
11191 /* Old offset (both fixed and variable parts) should have been
11192 * known-zero, because we don't allow pointer arithmetic on
11193 * pointers that might be NULL. If we see this happening, don't
11194 * convert the register.
11195 *
11196 * But in some cases, some helpers that return local kptrs
11197 * advance offset for the returned pointer. In those cases, it
11198 * is fine to expect to see reg->off.
11199 */
11200 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
11201 return;
11202 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off))
e60b0d12 11203 return;
f1174f77
EC
11204 if (is_null) {
11205 reg->type = SCALAR_VALUE;
1b986589
MKL
11206 /* We don't need id and ref_obj_id from this point
11207 * onwards anymore, thus we should better reset it,
11208 * so that state pruning has chances to take effect.
11209 */
11210 reg->id = 0;
11211 reg->ref_obj_id = 0;
4ddb7416
DB
11212
11213 return;
11214 }
11215
11216 mark_ptr_not_null_reg(reg);
11217
11218 if (!reg_may_point_to_spin_lock(reg)) {
1b986589 11219 /* For not-NULL ptr, reg->ref_obj_id will be reset
b239da34 11220 * in release_reference().
1b986589
MKL
11221 *
11222 * reg->id is still used by spin_lock ptr. Other
11223 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
11224 */
11225 reg->id = 0;
56f668df 11226 }
57a09bf0
TG
11227 }
11228}
11229
11230/* The logic is similar to find_good_pkt_pointers(), both could eventually
11231 * be folded together at some point.
11232 */
840b9615
JS
11233static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
11234 bool is_null)
57a09bf0 11235{
f4d7e40a 11236 struct bpf_func_state *state = vstate->frame[vstate->curframe];
b239da34 11237 struct bpf_reg_state *regs = state->regs, *reg;
1b986589 11238 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 11239 u32 id = regs[regno].id;
57a09bf0 11240
1b986589
MKL
11241 if (ref_obj_id && ref_obj_id == id && is_null)
11242 /* regs[regno] is in the " == NULL" branch.
11243 * No one could have freed the reference state before
11244 * doing the NULL check.
11245 */
11246 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 11247
b239da34
KKD
11248 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11249 mark_ptr_or_null_reg(state, reg, id, is_null);
11250 }));
57a09bf0
TG
11251}
11252
5beca081
DB
11253static bool try_match_pkt_pointers(const struct bpf_insn *insn,
11254 struct bpf_reg_state *dst_reg,
11255 struct bpf_reg_state *src_reg,
11256 struct bpf_verifier_state *this_branch,
11257 struct bpf_verifier_state *other_branch)
11258{
11259 if (BPF_SRC(insn->code) != BPF_X)
11260 return false;
11261
092ed096
JW
11262 /* Pointers are always 64-bit. */
11263 if (BPF_CLASS(insn->code) == BPF_JMP32)
11264 return false;
11265
5beca081
DB
11266 switch (BPF_OP(insn->code)) {
11267 case BPF_JGT:
11268 if ((dst_reg->type == PTR_TO_PACKET &&
11269 src_reg->type == PTR_TO_PACKET_END) ||
11270 (dst_reg->type == PTR_TO_PACKET_META &&
11271 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11272 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
11273 find_good_pkt_pointers(this_branch, dst_reg,
11274 dst_reg->type, false);
6d94e741 11275 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
11276 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11277 src_reg->type == PTR_TO_PACKET) ||
11278 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11279 src_reg->type == PTR_TO_PACKET_META)) {
11280 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
11281 find_good_pkt_pointers(other_branch, src_reg,
11282 src_reg->type, true);
6d94e741 11283 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
11284 } else {
11285 return false;
11286 }
11287 break;
11288 case BPF_JLT:
11289 if ((dst_reg->type == PTR_TO_PACKET &&
11290 src_reg->type == PTR_TO_PACKET_END) ||
11291 (dst_reg->type == PTR_TO_PACKET_META &&
11292 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11293 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
11294 find_good_pkt_pointers(other_branch, dst_reg,
11295 dst_reg->type, true);
6d94e741 11296 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
11297 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11298 src_reg->type == PTR_TO_PACKET) ||
11299 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11300 src_reg->type == PTR_TO_PACKET_META)) {
11301 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
11302 find_good_pkt_pointers(this_branch, src_reg,
11303 src_reg->type, false);
6d94e741 11304 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
11305 } else {
11306 return false;
11307 }
11308 break;
11309 case BPF_JGE:
11310 if ((dst_reg->type == PTR_TO_PACKET &&
11311 src_reg->type == PTR_TO_PACKET_END) ||
11312 (dst_reg->type == PTR_TO_PACKET_META &&
11313 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11314 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
11315 find_good_pkt_pointers(this_branch, dst_reg,
11316 dst_reg->type, true);
6d94e741 11317 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
11318 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11319 src_reg->type == PTR_TO_PACKET) ||
11320 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11321 src_reg->type == PTR_TO_PACKET_META)) {
11322 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
11323 find_good_pkt_pointers(other_branch, src_reg,
11324 src_reg->type, false);
6d94e741 11325 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
11326 } else {
11327 return false;
11328 }
11329 break;
11330 case BPF_JLE:
11331 if ((dst_reg->type == PTR_TO_PACKET &&
11332 src_reg->type == PTR_TO_PACKET_END) ||
11333 (dst_reg->type == PTR_TO_PACKET_META &&
11334 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
11335 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
11336 find_good_pkt_pointers(other_branch, dst_reg,
11337 dst_reg->type, false);
6d94e741 11338 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
11339 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
11340 src_reg->type == PTR_TO_PACKET) ||
11341 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
11342 src_reg->type == PTR_TO_PACKET_META)) {
11343 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
11344 find_good_pkt_pointers(this_branch, src_reg,
11345 src_reg->type, true);
6d94e741 11346 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
11347 } else {
11348 return false;
11349 }
11350 break;
11351 default:
11352 return false;
11353 }
11354
11355 return true;
11356}
11357
75748837
AS
11358static void find_equal_scalars(struct bpf_verifier_state *vstate,
11359 struct bpf_reg_state *known_reg)
11360{
11361 struct bpf_func_state *state;
11362 struct bpf_reg_state *reg;
75748837 11363
b239da34
KKD
11364 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
11365 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
11366 *reg = *known_reg;
11367 }));
75748837
AS
11368}
11369
58e2af8b 11370static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
11371 struct bpf_insn *insn, int *insn_idx)
11372{
f4d7e40a
AS
11373 struct bpf_verifier_state *this_branch = env->cur_state;
11374 struct bpf_verifier_state *other_branch;
11375 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 11376 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
befae758 11377 struct bpf_reg_state *eq_branch_regs;
17a52670 11378 u8 opcode = BPF_OP(insn->code);
092ed096 11379 bool is_jmp32;
fb8d251e 11380 int pred = -1;
17a52670
AS
11381 int err;
11382
092ed096
JW
11383 /* Only conditional jumps are expected to reach here. */
11384 if (opcode == BPF_JA || opcode > BPF_JSLE) {
11385 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
11386 return -EINVAL;
11387 }
11388
11389 if (BPF_SRC(insn->code) == BPF_X) {
11390 if (insn->imm != 0) {
092ed096 11391 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
11392 return -EINVAL;
11393 }
11394
11395 /* check src1 operand */
dc503a8a 11396 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
11397 if (err)
11398 return err;
1be7f75d
AS
11399
11400 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 11401 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
11402 insn->src_reg);
11403 return -EACCES;
11404 }
fb8d251e 11405 src_reg = &regs[insn->src_reg];
17a52670
AS
11406 } else {
11407 if (insn->src_reg != BPF_REG_0) {
092ed096 11408 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
11409 return -EINVAL;
11410 }
11411 }
11412
11413 /* check src2 operand */
dc503a8a 11414 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
11415 if (err)
11416 return err;
11417
1a0dc1ac 11418 dst_reg = &regs[insn->dst_reg];
092ed096 11419 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 11420
3f50f132
JF
11421 if (BPF_SRC(insn->code) == BPF_K) {
11422 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
11423 } else if (src_reg->type == SCALAR_VALUE &&
11424 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
11425 pred = is_branch_taken(dst_reg,
11426 tnum_subreg(src_reg->var_off).value,
11427 opcode,
11428 is_jmp32);
11429 } else if (src_reg->type == SCALAR_VALUE &&
11430 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
11431 pred = is_branch_taken(dst_reg,
11432 src_reg->var_off.value,
11433 opcode,
11434 is_jmp32);
6d94e741
AS
11435 } else if (reg_is_pkt_pointer_any(dst_reg) &&
11436 reg_is_pkt_pointer_any(src_reg) &&
11437 !is_jmp32) {
11438 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
11439 }
11440
b5dc0163 11441 if (pred >= 0) {
cac616db
JF
11442 /* If we get here with a dst_reg pointer type it is because
11443 * above is_branch_taken() special cased the 0 comparison.
11444 */
11445 if (!__is_pointer_value(false, dst_reg))
11446 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
11447 if (BPF_SRC(insn->code) == BPF_X && !err &&
11448 !__is_pointer_value(false, src_reg))
b5dc0163
AS
11449 err = mark_chain_precision(env, insn->src_reg);
11450 if (err)
11451 return err;
11452 }
9183671a 11453
fb8d251e 11454 if (pred == 1) {
9183671a
DB
11455 /* Only follow the goto, ignore fall-through. If needed, push
11456 * the fall-through branch for simulation under speculative
11457 * execution.
11458 */
11459 if (!env->bypass_spec_v1 &&
11460 !sanitize_speculative_path(env, insn, *insn_idx + 1,
11461 *insn_idx))
11462 return -EFAULT;
fb8d251e
AS
11463 *insn_idx += insn->off;
11464 return 0;
11465 } else if (pred == 0) {
9183671a
DB
11466 /* Only follow the fall-through branch, since that's where the
11467 * program will go. If needed, push the goto branch for
11468 * simulation under speculative execution.
fb8d251e 11469 */
9183671a
DB
11470 if (!env->bypass_spec_v1 &&
11471 !sanitize_speculative_path(env, insn,
11472 *insn_idx + insn->off + 1,
11473 *insn_idx))
11474 return -EFAULT;
fb8d251e 11475 return 0;
17a52670
AS
11476 }
11477
979d63d5
DB
11478 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
11479 false);
17a52670
AS
11480 if (!other_branch)
11481 return -EFAULT;
f4d7e40a 11482 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 11483
48461135
JB
11484 /* detect if we are comparing against a constant value so we can adjust
11485 * our min/max values for our dst register.
f1174f77 11486 * this is only legit if both are scalars (or pointers to the same
befae758
EZ
11487 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
11488 * because otherwise the different base pointers mean the offsets aren't
f1174f77 11489 * comparable.
48461135
JB
11490 */
11491 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 11492 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 11493
f1174f77 11494 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
11495 src_reg->type == SCALAR_VALUE) {
11496 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
11497 (is_jmp32 &&
11498 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 11499 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 11500 dst_reg,
3f50f132
JF
11501 src_reg->var_off.value,
11502 tnum_subreg(src_reg->var_off).value,
092ed096
JW
11503 opcode, is_jmp32);
11504 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
11505 (is_jmp32 &&
11506 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 11507 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 11508 src_reg,
3f50f132
JF
11509 dst_reg->var_off.value,
11510 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
11511 opcode, is_jmp32);
11512 else if (!is_jmp32 &&
11513 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 11514 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
11515 reg_combine_min_max(&other_branch_regs[insn->src_reg],
11516 &other_branch_regs[insn->dst_reg],
092ed096 11517 src_reg, dst_reg, opcode);
e688c3db
AS
11518 if (src_reg->id &&
11519 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
11520 find_equal_scalars(this_branch, src_reg);
11521 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
11522 }
11523
f1174f77
EC
11524 }
11525 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 11526 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
11527 dst_reg, insn->imm, (u32)insn->imm,
11528 opcode, is_jmp32);
48461135
JB
11529 }
11530
e688c3db
AS
11531 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
11532 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
11533 find_equal_scalars(this_branch, dst_reg);
11534 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
11535 }
11536
befae758
EZ
11537 /* if one pointer register is compared to another pointer
11538 * register check if PTR_MAYBE_NULL could be lifted.
11539 * E.g. register A - maybe null
11540 * register B - not null
11541 * for JNE A, B, ... - A is not null in the false branch;
11542 * for JEQ A, B, ... - A is not null in the true branch.
11543 */
11544 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
11545 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
11546 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type)) {
11547 eq_branch_regs = NULL;
11548 switch (opcode) {
11549 case BPF_JEQ:
11550 eq_branch_regs = other_branch_regs;
11551 break;
11552 case BPF_JNE:
11553 eq_branch_regs = regs;
11554 break;
11555 default:
11556 /* do nothing */
11557 break;
11558 }
11559 if (eq_branch_regs) {
11560 if (type_may_be_null(src_reg->type))
11561 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
11562 else
11563 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
11564 }
11565 }
11566
092ed096
JW
11567 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
11568 * NOTE: these optimizations below are related with pointer comparison
11569 * which will never be JMP32.
11570 */
11571 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 11572 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
c25b2ae1 11573 type_may_be_null(dst_reg->type)) {
840b9615 11574 /* Mark all identical registers in each branch as either
57a09bf0
TG
11575 * safe or unknown depending R == 0 or R != 0 conditional.
11576 */
840b9615
JS
11577 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
11578 opcode == BPF_JNE);
11579 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
11580 opcode == BPF_JEQ);
5beca081
DB
11581 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
11582 this_branch, other_branch) &&
11583 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
11584 verbose(env, "R%d pointer comparison prohibited\n",
11585 insn->dst_reg);
1be7f75d 11586 return -EACCES;
17a52670 11587 }
06ee7115 11588 if (env->log.level & BPF_LOG_LEVEL)
2e576648 11589 print_insn_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
11590 return 0;
11591}
11592
17a52670 11593/* verify BPF_LD_IMM64 instruction */
58e2af8b 11594static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 11595{
d8eca5bb 11596 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 11597 struct bpf_reg_state *regs = cur_regs(env);
4976b718 11598 struct bpf_reg_state *dst_reg;
d8eca5bb 11599 struct bpf_map *map;
17a52670
AS
11600 int err;
11601
11602 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 11603 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
11604 return -EINVAL;
11605 }
11606 if (insn->off != 0) {
61bd5218 11607 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
11608 return -EINVAL;
11609 }
11610
dc503a8a 11611 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
11612 if (err)
11613 return err;
11614
4976b718 11615 dst_reg = &regs[insn->dst_reg];
6b173873 11616 if (insn->src_reg == 0) {
6b173873
JK
11617 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
11618
4976b718 11619 dst_reg->type = SCALAR_VALUE;
b03c9f9f 11620 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 11621 return 0;
6b173873 11622 }
17a52670 11623
d400a6cf
DB
11624 /* All special src_reg cases are listed below. From this point onwards
11625 * we either succeed and assign a corresponding dst_reg->type after
11626 * zeroing the offset, or fail and reject the program.
11627 */
11628 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 11629
d400a6cf 11630 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
4976b718 11631 dst_reg->type = aux->btf_var.reg_type;
34d3a78c 11632 switch (base_type(dst_reg->type)) {
4976b718
HL
11633 case PTR_TO_MEM:
11634 dst_reg->mem_size = aux->btf_var.mem_size;
11635 break;
11636 case PTR_TO_BTF_ID:
22dc4a0f 11637 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
11638 dst_reg->btf_id = aux->btf_var.btf_id;
11639 break;
11640 default:
11641 verbose(env, "bpf verifier is misconfigured\n");
11642 return -EFAULT;
11643 }
11644 return 0;
11645 }
11646
69c087ba
YS
11647 if (insn->src_reg == BPF_PSEUDO_FUNC) {
11648 struct bpf_prog_aux *aux = env->prog->aux;
3990ed4c
MKL
11649 u32 subprogno = find_subprog(env,
11650 env->insn_idx + insn->imm + 1);
69c087ba
YS
11651
11652 if (!aux->func_info) {
11653 verbose(env, "missing btf func_info\n");
11654 return -EINVAL;
11655 }
11656 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
11657 verbose(env, "callback function not static\n");
11658 return -EINVAL;
11659 }
11660
11661 dst_reg->type = PTR_TO_FUNC;
11662 dst_reg->subprogno = subprogno;
11663 return 0;
11664 }
11665
d8eca5bb 11666 map = env->used_maps[aux->map_index];
4976b718 11667 dst_reg->map_ptr = map;
d8eca5bb 11668
387544bf
AS
11669 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
11670 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
4976b718
HL
11671 dst_reg->type = PTR_TO_MAP_VALUE;
11672 dst_reg->off = aux->map_off;
d0d78c1d
KKD
11673 WARN_ON_ONCE(map->max_entries != 1);
11674 /* We want reg->id to be same (0) as map_value is not distinct */
387544bf
AS
11675 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
11676 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
4976b718 11677 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
11678 } else {
11679 verbose(env, "bpf verifier is misconfigured\n");
11680 return -EINVAL;
11681 }
17a52670 11682
17a52670
AS
11683 return 0;
11684}
11685
96be4325
DB
11686static bool may_access_skb(enum bpf_prog_type type)
11687{
11688 switch (type) {
11689 case BPF_PROG_TYPE_SOCKET_FILTER:
11690 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 11691 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
11692 return true;
11693 default:
11694 return false;
11695 }
11696}
11697
ddd872bc
AS
11698/* verify safety of LD_ABS|LD_IND instructions:
11699 * - they can only appear in the programs where ctx == skb
11700 * - since they are wrappers of function calls, they scratch R1-R5 registers,
11701 * preserve R6-R9, and store return value into R0
11702 *
11703 * Implicit input:
11704 * ctx == skb == R6 == CTX
11705 *
11706 * Explicit input:
11707 * SRC == any register
11708 * IMM == 32-bit immediate
11709 *
11710 * Output:
11711 * R0 - 8/16/32-bit skb data converted to cpu endianness
11712 */
58e2af8b 11713static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 11714{
638f5b90 11715 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 11716 static const int ctx_reg = BPF_REG_6;
ddd872bc 11717 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
11718 int i, err;
11719
7e40781c 11720 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 11721 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
11722 return -EINVAL;
11723 }
11724
e0cea7ce
DB
11725 if (!env->ops->gen_ld_abs) {
11726 verbose(env, "bpf verifier is misconfigured\n");
11727 return -EINVAL;
11728 }
11729
ddd872bc 11730 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 11731 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 11732 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 11733 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
11734 return -EINVAL;
11735 }
11736
11737 /* check whether implicit source operand (register R6) is readable */
6d4f151a 11738 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
11739 if (err)
11740 return err;
11741
fd978bf7
JS
11742 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
11743 * gen_ld_abs() may terminate the program at runtime, leading to
11744 * reference leak.
11745 */
11746 err = check_reference_leak(env);
11747 if (err) {
11748 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
11749 return err;
11750 }
11751
d0d78c1d 11752 if (env->cur_state->active_lock.ptr) {
d83525ca
AS
11753 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
11754 return -EINVAL;
11755 }
11756
6d4f151a 11757 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
11758 verbose(env,
11759 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
11760 return -EINVAL;
11761 }
11762
11763 if (mode == BPF_IND) {
11764 /* check explicit source operand */
dc503a8a 11765 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
11766 if (err)
11767 return err;
11768 }
11769
be80a1d3 11770 err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
6d4f151a
DB
11771 if (err < 0)
11772 return err;
11773
ddd872bc 11774 /* reset caller saved regs to unreadable */
dc503a8a 11775 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 11776 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
11777 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11778 }
ddd872bc
AS
11779
11780 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
11781 * the value fetched from the packet.
11782 * Already marked as written above.
ddd872bc 11783 */
61bd5218 11784 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
11785 /* ld_abs load up to 32-bit skb data. */
11786 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
11787 return 0;
11788}
11789
390ee7e2
AS
11790static int check_return_code(struct bpf_verifier_env *env)
11791{
5cf1e914 11792 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 11793 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
11794 struct bpf_reg_state *reg;
11795 struct tnum range = tnum_range(0, 1);
7e40781c 11796 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 11797 int err;
bfc6bb74
AS
11798 struct bpf_func_state *frame = env->cur_state->frame[0];
11799 const bool is_subprog = frame->subprogno;
27ae7997 11800
9e4e01df 11801 /* LSM and struct_ops func-ptr's return type could be "void" */
d1a6edec
SF
11802 if (!is_subprog) {
11803 switch (prog_type) {
11804 case BPF_PROG_TYPE_LSM:
11805 if (prog->expected_attach_type == BPF_LSM_CGROUP)
11806 /* See below, can be 0 or 0-1 depending on hook. */
11807 break;
11808 fallthrough;
11809 case BPF_PROG_TYPE_STRUCT_OPS:
11810 if (!prog->aux->attach_func_proto->type)
11811 return 0;
11812 break;
11813 default:
11814 break;
11815 }
11816 }
27ae7997 11817
8fb33b60 11818 /* eBPF calling convention is such that R0 is used
27ae7997
MKL
11819 * to return the value from eBPF program.
11820 * Make sure that it's readable at this time
11821 * of bpf_exit, which means that program wrote
11822 * something into it earlier
11823 */
11824 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
11825 if (err)
11826 return err;
11827
11828 if (is_pointer_value(env, BPF_REG_0)) {
11829 verbose(env, "R0 leaks addr as return value\n");
11830 return -EACCES;
11831 }
390ee7e2 11832
f782e2c3 11833 reg = cur_regs(env) + BPF_REG_0;
bfc6bb74
AS
11834
11835 if (frame->in_async_callback_fn) {
11836 /* enforce return zero from async callbacks like timer */
11837 if (reg->type != SCALAR_VALUE) {
11838 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
c25b2ae1 11839 reg_type_str(env, reg->type));
bfc6bb74
AS
11840 return -EINVAL;
11841 }
11842
11843 if (!tnum_in(tnum_const(0), reg->var_off)) {
11844 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
11845 return -EINVAL;
11846 }
11847 return 0;
11848 }
11849
f782e2c3
DB
11850 if (is_subprog) {
11851 if (reg->type != SCALAR_VALUE) {
11852 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
c25b2ae1 11853 reg_type_str(env, reg->type));
f782e2c3
DB
11854 return -EINVAL;
11855 }
11856 return 0;
11857 }
11858
7e40781c 11859 switch (prog_type) {
983695fa
DB
11860 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
11861 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
11862 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
11863 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
11864 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
11865 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
11866 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 11867 range = tnum_range(1, 1);
77241217
SF
11868 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
11869 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
11870 range = tnum_range(0, 3);
ed4ed404 11871 break;
390ee7e2 11872 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 11873 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
11874 range = tnum_range(0, 3);
11875 enforce_attach_type_range = tnum_range(2, 3);
11876 }
ed4ed404 11877 break;
390ee7e2
AS
11878 case BPF_PROG_TYPE_CGROUP_SOCK:
11879 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 11880 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 11881 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 11882 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 11883 break;
15ab09bd
AS
11884 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11885 if (!env->prog->aux->attach_btf_id)
11886 return 0;
11887 range = tnum_const(0);
11888 break;
15d83c4d 11889 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
11890 switch (env->prog->expected_attach_type) {
11891 case BPF_TRACE_FENTRY:
11892 case BPF_TRACE_FEXIT:
11893 range = tnum_const(0);
11894 break;
11895 case BPF_TRACE_RAW_TP:
11896 case BPF_MODIFY_RETURN:
15d83c4d 11897 return 0;
2ec0616e
DB
11898 case BPF_TRACE_ITER:
11899 break;
e92888c7
YS
11900 default:
11901 return -ENOTSUPP;
11902 }
15d83c4d 11903 break;
e9ddbb77
JS
11904 case BPF_PROG_TYPE_SK_LOOKUP:
11905 range = tnum_range(SK_DROP, SK_PASS);
11906 break;
69fd337a
SF
11907
11908 case BPF_PROG_TYPE_LSM:
11909 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
11910 /* Regular BPF_PROG_TYPE_LSM programs can return
11911 * any value.
11912 */
11913 return 0;
11914 }
11915 if (!env->prog->aux->attach_func_proto->type) {
11916 /* Make sure programs that attach to void
11917 * hooks don't try to modify return value.
11918 */
11919 range = tnum_range(1, 1);
11920 }
11921 break;
11922
e92888c7
YS
11923 case BPF_PROG_TYPE_EXT:
11924 /* freplace program can return anything as its return value
11925 * depends on the to-be-replaced kernel func or bpf program.
11926 */
390ee7e2
AS
11927 default:
11928 return 0;
11929 }
11930
390ee7e2 11931 if (reg->type != SCALAR_VALUE) {
61bd5218 11932 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
c25b2ae1 11933 reg_type_str(env, reg->type));
390ee7e2
AS
11934 return -EINVAL;
11935 }
11936
11937 if (!tnum_in(range, reg->var_off)) {
bc2591d6 11938 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
69fd337a 11939 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
d1a6edec 11940 prog_type == BPF_PROG_TYPE_LSM &&
69fd337a
SF
11941 !prog->aux->attach_func_proto->type)
11942 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
390ee7e2
AS
11943 return -EINVAL;
11944 }
5cf1e914 11945
11946 if (!tnum_is_unknown(enforce_attach_type_range) &&
11947 tnum_in(enforce_attach_type_range, reg->var_off))
11948 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
11949 return 0;
11950}
11951
475fb78f
AS
11952/* non-recursive DFS pseudo code
11953 * 1 procedure DFS-iterative(G,v):
11954 * 2 label v as discovered
11955 * 3 let S be a stack
11956 * 4 S.push(v)
11957 * 5 while S is not empty
b6d20799 11958 * 6 t <- S.peek()
475fb78f
AS
11959 * 7 if t is what we're looking for:
11960 * 8 return t
11961 * 9 for all edges e in G.adjacentEdges(t) do
11962 * 10 if edge e is already labelled
11963 * 11 continue with the next edge
11964 * 12 w <- G.adjacentVertex(t,e)
11965 * 13 if vertex w is not discovered and not explored
11966 * 14 label e as tree-edge
11967 * 15 label w as discovered
11968 * 16 S.push(w)
11969 * 17 continue at 5
11970 * 18 else if vertex w is discovered
11971 * 19 label e as back-edge
11972 * 20 else
11973 * 21 // vertex w is explored
11974 * 22 label e as forward- or cross-edge
11975 * 23 label t as explored
11976 * 24 S.pop()
11977 *
11978 * convention:
11979 * 0x10 - discovered
11980 * 0x11 - discovered and fall-through edge labelled
11981 * 0x12 - discovered and fall-through and branch edges labelled
11982 * 0x20 - explored
11983 */
11984
11985enum {
11986 DISCOVERED = 0x10,
11987 EXPLORED = 0x20,
11988 FALLTHROUGH = 1,
11989 BRANCH = 2,
11990};
11991
dc2a4ebc
AS
11992static u32 state_htab_size(struct bpf_verifier_env *env)
11993{
11994 return env->prog->len;
11995}
11996
5d839021
AS
11997static struct bpf_verifier_state_list **explored_state(
11998 struct bpf_verifier_env *env,
11999 int idx)
12000{
dc2a4ebc
AS
12001 struct bpf_verifier_state *cur = env->cur_state;
12002 struct bpf_func_state *state = cur->frame[cur->curframe];
12003
12004 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
12005}
12006
12007static void init_explored_state(struct bpf_verifier_env *env, int idx)
12008{
a8f500af 12009 env->insn_aux_data[idx].prune_point = true;
5d839021 12010}
f1bca824 12011
59e2e27d
WAF
12012enum {
12013 DONE_EXPLORING = 0,
12014 KEEP_EXPLORING = 1,
12015};
12016
475fb78f
AS
12017/* t, w, e - match pseudo-code above:
12018 * t - index of current instruction
12019 * w - next instruction
12020 * e - edge
12021 */
2589726d
AS
12022static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
12023 bool loop_ok)
475fb78f 12024{
7df737e9
AS
12025 int *insn_stack = env->cfg.insn_stack;
12026 int *insn_state = env->cfg.insn_state;
12027
475fb78f 12028 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 12029 return DONE_EXPLORING;
475fb78f
AS
12030
12031 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 12032 return DONE_EXPLORING;
475fb78f
AS
12033
12034 if (w < 0 || w >= env->prog->len) {
d9762e84 12035 verbose_linfo(env, t, "%d: ", t);
61bd5218 12036 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
12037 return -EINVAL;
12038 }
12039
f1bca824
AS
12040 if (e == BRANCH)
12041 /* mark branch target for state pruning */
5d839021 12042 init_explored_state(env, w);
f1bca824 12043
475fb78f
AS
12044 if (insn_state[w] == 0) {
12045 /* tree-edge */
12046 insn_state[t] = DISCOVERED | e;
12047 insn_state[w] = DISCOVERED;
7df737e9 12048 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 12049 return -E2BIG;
7df737e9 12050 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 12051 return KEEP_EXPLORING;
475fb78f 12052 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 12053 if (loop_ok && env->bpf_capable)
59e2e27d 12054 return DONE_EXPLORING;
d9762e84
MKL
12055 verbose_linfo(env, t, "%d: ", t);
12056 verbose_linfo(env, w, "%d: ", w);
61bd5218 12057 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
12058 return -EINVAL;
12059 } else if (insn_state[w] == EXPLORED) {
12060 /* forward- or cross-edge */
12061 insn_state[t] = DISCOVERED | e;
12062 } else {
61bd5218 12063 verbose(env, "insn state internal bug\n");
475fb78f
AS
12064 return -EFAULT;
12065 }
59e2e27d
WAF
12066 return DONE_EXPLORING;
12067}
12068
efdb22de
YS
12069static int visit_func_call_insn(int t, int insn_cnt,
12070 struct bpf_insn *insns,
12071 struct bpf_verifier_env *env,
12072 bool visit_callee)
12073{
12074 int ret;
12075
12076 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
12077 if (ret)
12078 return ret;
12079
12080 if (t + 1 < insn_cnt)
12081 init_explored_state(env, t + 1);
12082 if (visit_callee) {
12083 init_explored_state(env, t);
86fc6ee6
AS
12084 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
12085 /* It's ok to allow recursion from CFG point of
12086 * view. __check_func_call() will do the actual
12087 * check.
12088 */
12089 bpf_pseudo_func(insns + t));
efdb22de
YS
12090 }
12091 return ret;
12092}
12093
59e2e27d
WAF
12094/* Visits the instruction at index t and returns one of the following:
12095 * < 0 - an error occurred
12096 * DONE_EXPLORING - the instruction was fully explored
12097 * KEEP_EXPLORING - there is still work to be done before it is fully explored
12098 */
12099static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
12100{
12101 struct bpf_insn *insns = env->prog->insnsi;
12102 int ret;
12103
69c087ba
YS
12104 if (bpf_pseudo_func(insns + t))
12105 return visit_func_call_insn(t, insn_cnt, insns, env, true);
12106
59e2e27d
WAF
12107 /* All non-branch instructions have a single fall-through edge. */
12108 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
12109 BPF_CLASS(insns[t].code) != BPF_JMP32)
12110 return push_insn(t, t + 1, FALLTHROUGH, env, false);
12111
12112 switch (BPF_OP(insns[t].code)) {
12113 case BPF_EXIT:
12114 return DONE_EXPLORING;
12115
12116 case BPF_CALL:
bfc6bb74
AS
12117 if (insns[t].imm == BPF_FUNC_timer_set_callback)
12118 /* Mark this call insn to trigger is_state_visited() check
12119 * before call itself is processed by __check_func_call().
12120 * Otherwise new async state will be pushed for further
12121 * exploration.
12122 */
12123 init_explored_state(env, t);
efdb22de
YS
12124 return visit_func_call_insn(t, insn_cnt, insns, env,
12125 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
12126
12127 case BPF_JA:
12128 if (BPF_SRC(insns[t].code) != BPF_K)
12129 return -EINVAL;
12130
12131 /* unconditional jump with single edge */
12132 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
12133 true);
12134 if (ret)
12135 return ret;
12136
12137 /* unconditional jmp is not a good pruning point,
12138 * but it's marked, since backtracking needs
12139 * to record jmp history in is_state_visited().
12140 */
12141 init_explored_state(env, t + insns[t].off + 1);
12142 /* tell verifier to check for equivalent states
12143 * after every call and jump
12144 */
12145 if (t + 1 < insn_cnt)
12146 init_explored_state(env, t + 1);
12147
12148 return ret;
12149
12150 default:
12151 /* conditional jump with two edges */
12152 init_explored_state(env, t);
12153 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
12154 if (ret)
12155 return ret;
12156
12157 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
12158 }
475fb78f
AS
12159}
12160
12161/* non-recursive depth-first-search to detect loops in BPF program
12162 * loop == back-edge in directed graph
12163 */
58e2af8b 12164static int check_cfg(struct bpf_verifier_env *env)
475fb78f 12165{
475fb78f 12166 int insn_cnt = env->prog->len;
7df737e9 12167 int *insn_stack, *insn_state;
475fb78f 12168 int ret = 0;
59e2e27d 12169 int i;
475fb78f 12170
7df737e9 12171 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
12172 if (!insn_state)
12173 return -ENOMEM;
12174
7df737e9 12175 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 12176 if (!insn_stack) {
71dde681 12177 kvfree(insn_state);
475fb78f
AS
12178 return -ENOMEM;
12179 }
12180
12181 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
12182 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 12183 env->cfg.cur_stack = 1;
475fb78f 12184
59e2e27d
WAF
12185 while (env->cfg.cur_stack > 0) {
12186 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 12187
59e2e27d
WAF
12188 ret = visit_insn(t, insn_cnt, env);
12189 switch (ret) {
12190 case DONE_EXPLORING:
12191 insn_state[t] = EXPLORED;
12192 env->cfg.cur_stack--;
12193 break;
12194 case KEEP_EXPLORING:
12195 break;
12196 default:
12197 if (ret > 0) {
12198 verbose(env, "visit_insn internal bug\n");
12199 ret = -EFAULT;
475fb78f 12200 }
475fb78f 12201 goto err_free;
59e2e27d 12202 }
475fb78f
AS
12203 }
12204
59e2e27d 12205 if (env->cfg.cur_stack < 0) {
61bd5218 12206 verbose(env, "pop stack internal bug\n");
475fb78f
AS
12207 ret = -EFAULT;
12208 goto err_free;
12209 }
475fb78f 12210
475fb78f
AS
12211 for (i = 0; i < insn_cnt; i++) {
12212 if (insn_state[i] != EXPLORED) {
61bd5218 12213 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
12214 ret = -EINVAL;
12215 goto err_free;
12216 }
12217 }
12218 ret = 0; /* cfg looks good */
12219
12220err_free:
71dde681
AS
12221 kvfree(insn_state);
12222 kvfree(insn_stack);
7df737e9 12223 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
12224 return ret;
12225}
12226
09b28d76
AS
12227static int check_abnormal_return(struct bpf_verifier_env *env)
12228{
12229 int i;
12230
12231 for (i = 1; i < env->subprog_cnt; i++) {
12232 if (env->subprog_info[i].has_ld_abs) {
12233 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
12234 return -EINVAL;
12235 }
12236 if (env->subprog_info[i].has_tail_call) {
12237 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
12238 return -EINVAL;
12239 }
12240 }
12241 return 0;
12242}
12243
838e9690
YS
12244/* The minimum supported BTF func info size */
12245#define MIN_BPF_FUNCINFO_SIZE 8
12246#define MAX_FUNCINFO_REC_SIZE 252
12247
c454a46b
MKL
12248static int check_btf_func(struct bpf_verifier_env *env,
12249 const union bpf_attr *attr,
af2ac3e1 12250 bpfptr_t uattr)
838e9690 12251{
09b28d76 12252 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 12253 u32 i, nfuncs, urec_size, min_size;
838e9690 12254 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 12255 struct bpf_func_info *krecord;
8c1b6e69 12256 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
12257 struct bpf_prog *prog;
12258 const struct btf *btf;
af2ac3e1 12259 bpfptr_t urecord;
d0b2818e 12260 u32 prev_offset = 0;
09b28d76 12261 bool scalar_return;
e7ed83d6 12262 int ret = -ENOMEM;
838e9690
YS
12263
12264 nfuncs = attr->func_info_cnt;
09b28d76
AS
12265 if (!nfuncs) {
12266 if (check_abnormal_return(env))
12267 return -EINVAL;
838e9690 12268 return 0;
09b28d76 12269 }
838e9690
YS
12270
12271 if (nfuncs != env->subprog_cnt) {
12272 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
12273 return -EINVAL;
12274 }
12275
12276 urec_size = attr->func_info_rec_size;
12277 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
12278 urec_size > MAX_FUNCINFO_REC_SIZE ||
12279 urec_size % sizeof(u32)) {
12280 verbose(env, "invalid func info rec size %u\n", urec_size);
12281 return -EINVAL;
12282 }
12283
c454a46b
MKL
12284 prog = env->prog;
12285 btf = prog->aux->btf;
838e9690 12286
af2ac3e1 12287 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
838e9690
YS
12288 min_size = min_t(u32, krec_size, urec_size);
12289
ba64e7d8 12290 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
12291 if (!krecord)
12292 return -ENOMEM;
8c1b6e69
AS
12293 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
12294 if (!info_aux)
12295 goto err_free;
ba64e7d8 12296
838e9690
YS
12297 for (i = 0; i < nfuncs; i++) {
12298 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
12299 if (ret) {
12300 if (ret == -E2BIG) {
12301 verbose(env, "nonzero tailing record in func info");
12302 /* set the size kernel expects so loader can zero
12303 * out the rest of the record.
12304 */
af2ac3e1
AS
12305 if (copy_to_bpfptr_offset(uattr,
12306 offsetof(union bpf_attr, func_info_rec_size),
12307 &min_size, sizeof(min_size)))
838e9690
YS
12308 ret = -EFAULT;
12309 }
c454a46b 12310 goto err_free;
838e9690
YS
12311 }
12312
af2ac3e1 12313 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
838e9690 12314 ret = -EFAULT;
c454a46b 12315 goto err_free;
838e9690
YS
12316 }
12317
d30d42e0 12318 /* check insn_off */
09b28d76 12319 ret = -EINVAL;
838e9690 12320 if (i == 0) {
d30d42e0 12321 if (krecord[i].insn_off) {
838e9690 12322 verbose(env,
d30d42e0
MKL
12323 "nonzero insn_off %u for the first func info record",
12324 krecord[i].insn_off);
c454a46b 12325 goto err_free;
838e9690 12326 }
d30d42e0 12327 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
12328 verbose(env,
12329 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 12330 krecord[i].insn_off, prev_offset);
c454a46b 12331 goto err_free;
838e9690
YS
12332 }
12333
d30d42e0 12334 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 12335 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 12336 goto err_free;
838e9690
YS
12337 }
12338
12339 /* check type_id */
ba64e7d8 12340 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 12341 if (!type || !btf_type_is_func(type)) {
838e9690 12342 verbose(env, "invalid type id %d in func info",
ba64e7d8 12343 krecord[i].type_id);
c454a46b 12344 goto err_free;
838e9690 12345 }
51c39bb1 12346 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
12347
12348 func_proto = btf_type_by_id(btf, type->type);
12349 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
12350 /* btf_func_check() already verified it during BTF load */
12351 goto err_free;
12352 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
12353 scalar_return =
6089fb32 12354 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
09b28d76
AS
12355 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
12356 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
12357 goto err_free;
12358 }
12359 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
12360 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
12361 goto err_free;
12362 }
12363
d30d42e0 12364 prev_offset = krecord[i].insn_off;
af2ac3e1 12365 bpfptr_add(&urecord, urec_size);
838e9690
YS
12366 }
12367
ba64e7d8
YS
12368 prog->aux->func_info = krecord;
12369 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 12370 prog->aux->func_info_aux = info_aux;
838e9690
YS
12371 return 0;
12372
c454a46b 12373err_free:
ba64e7d8 12374 kvfree(krecord);
8c1b6e69 12375 kfree(info_aux);
838e9690
YS
12376 return ret;
12377}
12378
ba64e7d8
YS
12379static void adjust_btf_func(struct bpf_verifier_env *env)
12380{
8c1b6e69 12381 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
12382 int i;
12383
8c1b6e69 12384 if (!aux->func_info)
ba64e7d8
YS
12385 return;
12386
12387 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 12388 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
12389}
12390
1b773d00 12391#define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
c454a46b
MKL
12392#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
12393
12394static int check_btf_line(struct bpf_verifier_env *env,
12395 const union bpf_attr *attr,
af2ac3e1 12396 bpfptr_t uattr)
c454a46b
MKL
12397{
12398 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
12399 struct bpf_subprog_info *sub;
12400 struct bpf_line_info *linfo;
12401 struct bpf_prog *prog;
12402 const struct btf *btf;
af2ac3e1 12403 bpfptr_t ulinfo;
c454a46b
MKL
12404 int err;
12405
12406 nr_linfo = attr->line_info_cnt;
12407 if (!nr_linfo)
12408 return 0;
0e6491b5
BC
12409 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
12410 return -EINVAL;
c454a46b
MKL
12411
12412 rec_size = attr->line_info_rec_size;
12413 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
12414 rec_size > MAX_LINEINFO_REC_SIZE ||
12415 rec_size & (sizeof(u32) - 1))
12416 return -EINVAL;
12417
12418 /* Need to zero it in case the userspace may
12419 * pass in a smaller bpf_line_info object.
12420 */
12421 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
12422 GFP_KERNEL | __GFP_NOWARN);
12423 if (!linfo)
12424 return -ENOMEM;
12425
12426 prog = env->prog;
12427 btf = prog->aux->btf;
12428
12429 s = 0;
12430 sub = env->subprog_info;
af2ac3e1 12431 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
c454a46b
MKL
12432 expected_size = sizeof(struct bpf_line_info);
12433 ncopy = min_t(u32, expected_size, rec_size);
12434 for (i = 0; i < nr_linfo; i++) {
12435 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
12436 if (err) {
12437 if (err == -E2BIG) {
12438 verbose(env, "nonzero tailing record in line_info");
af2ac3e1
AS
12439 if (copy_to_bpfptr_offset(uattr,
12440 offsetof(union bpf_attr, line_info_rec_size),
12441 &expected_size, sizeof(expected_size)))
c454a46b
MKL
12442 err = -EFAULT;
12443 }
12444 goto err_free;
12445 }
12446
af2ac3e1 12447 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
c454a46b
MKL
12448 err = -EFAULT;
12449 goto err_free;
12450 }
12451
12452 /*
12453 * Check insn_off to ensure
12454 * 1) strictly increasing AND
12455 * 2) bounded by prog->len
12456 *
12457 * The linfo[0].insn_off == 0 check logically falls into
12458 * the later "missing bpf_line_info for func..." case
12459 * because the first linfo[0].insn_off must be the
12460 * first sub also and the first sub must have
12461 * subprog_info[0].start == 0.
12462 */
12463 if ((i && linfo[i].insn_off <= prev_offset) ||
12464 linfo[i].insn_off >= prog->len) {
12465 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
12466 i, linfo[i].insn_off, prev_offset,
12467 prog->len);
12468 err = -EINVAL;
12469 goto err_free;
12470 }
12471
fdbaa0be
MKL
12472 if (!prog->insnsi[linfo[i].insn_off].code) {
12473 verbose(env,
12474 "Invalid insn code at line_info[%u].insn_off\n",
12475 i);
12476 err = -EINVAL;
12477 goto err_free;
12478 }
12479
23127b33
MKL
12480 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
12481 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
12482 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
12483 err = -EINVAL;
12484 goto err_free;
12485 }
12486
12487 if (s != env->subprog_cnt) {
12488 if (linfo[i].insn_off == sub[s].start) {
12489 sub[s].linfo_idx = i;
12490 s++;
12491 } else if (sub[s].start < linfo[i].insn_off) {
12492 verbose(env, "missing bpf_line_info for func#%u\n", s);
12493 err = -EINVAL;
12494 goto err_free;
12495 }
12496 }
12497
12498 prev_offset = linfo[i].insn_off;
af2ac3e1 12499 bpfptr_add(&ulinfo, rec_size);
c454a46b
MKL
12500 }
12501
12502 if (s != env->subprog_cnt) {
12503 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
12504 env->subprog_cnt - s, s);
12505 err = -EINVAL;
12506 goto err_free;
12507 }
12508
12509 prog->aux->linfo = linfo;
12510 prog->aux->nr_linfo = nr_linfo;
12511
12512 return 0;
12513
12514err_free:
12515 kvfree(linfo);
12516 return err;
12517}
12518
fbd94c7a
AS
12519#define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
12520#define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
12521
12522static int check_core_relo(struct bpf_verifier_env *env,
12523 const union bpf_attr *attr,
12524 bpfptr_t uattr)
12525{
12526 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
12527 struct bpf_core_relo core_relo = {};
12528 struct bpf_prog *prog = env->prog;
12529 const struct btf *btf = prog->aux->btf;
12530 struct bpf_core_ctx ctx = {
12531 .log = &env->log,
12532 .btf = btf,
12533 };
12534 bpfptr_t u_core_relo;
12535 int err;
12536
12537 nr_core_relo = attr->core_relo_cnt;
12538 if (!nr_core_relo)
12539 return 0;
12540 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
12541 return -EINVAL;
12542
12543 rec_size = attr->core_relo_rec_size;
12544 if (rec_size < MIN_CORE_RELO_SIZE ||
12545 rec_size > MAX_CORE_RELO_SIZE ||
12546 rec_size % sizeof(u32))
12547 return -EINVAL;
12548
12549 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
12550 expected_size = sizeof(struct bpf_core_relo);
12551 ncopy = min_t(u32, expected_size, rec_size);
12552
12553 /* Unlike func_info and line_info, copy and apply each CO-RE
12554 * relocation record one at a time.
12555 */
12556 for (i = 0; i < nr_core_relo; i++) {
12557 /* future proofing when sizeof(bpf_core_relo) changes */
12558 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
12559 if (err) {
12560 if (err == -E2BIG) {
12561 verbose(env, "nonzero tailing record in core_relo");
12562 if (copy_to_bpfptr_offset(uattr,
12563 offsetof(union bpf_attr, core_relo_rec_size),
12564 &expected_size, sizeof(expected_size)))
12565 err = -EFAULT;
12566 }
12567 break;
12568 }
12569
12570 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
12571 err = -EFAULT;
12572 break;
12573 }
12574
12575 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
12576 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
12577 i, core_relo.insn_off, prog->len);
12578 err = -EINVAL;
12579 break;
12580 }
12581
12582 err = bpf_core_apply(&ctx, &core_relo, i,
12583 &prog->insnsi[core_relo.insn_off / 8]);
12584 if (err)
12585 break;
12586 bpfptr_add(&u_core_relo, rec_size);
12587 }
12588 return err;
12589}
12590
c454a46b
MKL
12591static int check_btf_info(struct bpf_verifier_env *env,
12592 const union bpf_attr *attr,
af2ac3e1 12593 bpfptr_t uattr)
c454a46b
MKL
12594{
12595 struct btf *btf;
12596 int err;
12597
09b28d76
AS
12598 if (!attr->func_info_cnt && !attr->line_info_cnt) {
12599 if (check_abnormal_return(env))
12600 return -EINVAL;
c454a46b 12601 return 0;
09b28d76 12602 }
c454a46b
MKL
12603
12604 btf = btf_get_by_fd(attr->prog_btf_fd);
12605 if (IS_ERR(btf))
12606 return PTR_ERR(btf);
350a5c4d
AS
12607 if (btf_is_kernel(btf)) {
12608 btf_put(btf);
12609 return -EACCES;
12610 }
c454a46b
MKL
12611 env->prog->aux->btf = btf;
12612
12613 err = check_btf_func(env, attr, uattr);
12614 if (err)
12615 return err;
12616
12617 err = check_btf_line(env, attr, uattr);
12618 if (err)
12619 return err;
12620
fbd94c7a
AS
12621 err = check_core_relo(env, attr, uattr);
12622 if (err)
12623 return err;
12624
c454a46b 12625 return 0;
ba64e7d8
YS
12626}
12627
f1174f77
EC
12628/* check %cur's range satisfies %old's */
12629static bool range_within(struct bpf_reg_state *old,
12630 struct bpf_reg_state *cur)
12631{
b03c9f9f
EC
12632 return old->umin_value <= cur->umin_value &&
12633 old->umax_value >= cur->umax_value &&
12634 old->smin_value <= cur->smin_value &&
fd675184
DB
12635 old->smax_value >= cur->smax_value &&
12636 old->u32_min_value <= cur->u32_min_value &&
12637 old->u32_max_value >= cur->u32_max_value &&
12638 old->s32_min_value <= cur->s32_min_value &&
12639 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
12640}
12641
f1174f77
EC
12642/* If in the old state two registers had the same id, then they need to have
12643 * the same id in the new state as well. But that id could be different from
12644 * the old state, so we need to track the mapping from old to new ids.
12645 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
12646 * regs with old id 5 must also have new id 9 for the new state to be safe. But
12647 * regs with a different old id could still have new id 9, we don't care about
12648 * that.
12649 * So we look through our idmap to see if this old id has been seen before. If
12650 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 12651 */
c9e73e3d 12652static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
969bf05e 12653{
f1174f77 12654 unsigned int i;
969bf05e 12655
c9e73e3d 12656 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
f1174f77
EC
12657 if (!idmap[i].old) {
12658 /* Reached an empty slot; haven't seen this id before */
12659 idmap[i].old = old_id;
12660 idmap[i].cur = cur_id;
12661 return true;
12662 }
12663 if (idmap[i].old == old_id)
12664 return idmap[i].cur == cur_id;
12665 }
12666 /* We ran out of idmap slots, which should be impossible */
12667 WARN_ON_ONCE(1);
12668 return false;
12669}
12670
9242b5f5
AS
12671static void clean_func_state(struct bpf_verifier_env *env,
12672 struct bpf_func_state *st)
12673{
12674 enum bpf_reg_liveness live;
12675 int i, j;
12676
12677 for (i = 0; i < BPF_REG_FP; i++) {
12678 live = st->regs[i].live;
12679 /* liveness must not touch this register anymore */
12680 st->regs[i].live |= REG_LIVE_DONE;
12681 if (!(live & REG_LIVE_READ))
12682 /* since the register is unused, clear its state
12683 * to make further comparison simpler
12684 */
f54c7898 12685 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
12686 }
12687
12688 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
12689 live = st->stack[i].spilled_ptr.live;
12690 /* liveness must not touch this stack slot anymore */
12691 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
12692 if (!(live & REG_LIVE_READ)) {
f54c7898 12693 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
12694 for (j = 0; j < BPF_REG_SIZE; j++)
12695 st->stack[i].slot_type[j] = STACK_INVALID;
12696 }
12697 }
12698}
12699
12700static void clean_verifier_state(struct bpf_verifier_env *env,
12701 struct bpf_verifier_state *st)
12702{
12703 int i;
12704
12705 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
12706 /* all regs in this state in all frames were already marked */
12707 return;
12708
12709 for (i = 0; i <= st->curframe; i++)
12710 clean_func_state(env, st->frame[i]);
12711}
12712
12713/* the parentage chains form a tree.
12714 * the verifier states are added to state lists at given insn and
12715 * pushed into state stack for future exploration.
12716 * when the verifier reaches bpf_exit insn some of the verifer states
12717 * stored in the state lists have their final liveness state already,
12718 * but a lot of states will get revised from liveness point of view when
12719 * the verifier explores other branches.
12720 * Example:
12721 * 1: r0 = 1
12722 * 2: if r1 == 100 goto pc+1
12723 * 3: r0 = 2
12724 * 4: exit
12725 * when the verifier reaches exit insn the register r0 in the state list of
12726 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
12727 * of insn 2 and goes exploring further. At the insn 4 it will walk the
12728 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
12729 *
12730 * Since the verifier pushes the branch states as it sees them while exploring
12731 * the program the condition of walking the branch instruction for the second
12732 * time means that all states below this branch were already explored and
8fb33b60 12733 * their final liveness marks are already propagated.
9242b5f5
AS
12734 * Hence when the verifier completes the search of state list in is_state_visited()
12735 * we can call this clean_live_states() function to mark all liveness states
12736 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
12737 * will not be used.
12738 * This function also clears the registers and stack for states that !READ
12739 * to simplify state merging.
12740 *
12741 * Important note here that walking the same branch instruction in the callee
12742 * doesn't meant that the states are DONE. The verifier has to compare
12743 * the callsites
12744 */
12745static void clean_live_states(struct bpf_verifier_env *env, int insn,
12746 struct bpf_verifier_state *cur)
12747{
12748 struct bpf_verifier_state_list *sl;
12749 int i;
12750
5d839021 12751 sl = *explored_state(env, insn);
a8f500af 12752 while (sl) {
2589726d
AS
12753 if (sl->state.branches)
12754 goto next;
dc2a4ebc
AS
12755 if (sl->state.insn_idx != insn ||
12756 sl->state.curframe != cur->curframe)
9242b5f5
AS
12757 goto next;
12758 for (i = 0; i <= cur->curframe; i++)
12759 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
12760 goto next;
12761 clean_verifier_state(env, &sl->state);
12762next:
12763 sl = sl->next;
12764 }
12765}
12766
f1174f77 12767/* Returns true if (rold safe implies rcur safe) */
e042aa53
DB
12768static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
12769 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
f1174f77 12770{
f4d7e40a
AS
12771 bool equal;
12772
dc503a8a
EC
12773 if (!(rold->live & REG_LIVE_READ))
12774 /* explored state didn't use this */
12775 return true;
12776
679c782d 12777 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
12778
12779 if (rold->type == PTR_TO_STACK)
12780 /* two stack pointers are equal only if they're pointing to
12781 * the same stack frame, since fp-8 in foo != fp-8 in bar
12782 */
12783 return equal && rold->frameno == rcur->frameno;
12784
12785 if (equal)
969bf05e
AS
12786 return true;
12787
f1174f77
EC
12788 if (rold->type == NOT_INIT)
12789 /* explored state can't have used this */
969bf05e 12790 return true;
f1174f77
EC
12791 if (rcur->type == NOT_INIT)
12792 return false;
c25b2ae1 12793 switch (base_type(rold->type)) {
f1174f77 12794 case SCALAR_VALUE:
e042aa53
DB
12795 if (env->explore_alu_limits)
12796 return false;
f1174f77 12797 if (rcur->type == SCALAR_VALUE) {
f63181b6 12798 if (!rold->precise)
b5dc0163 12799 return true;
f1174f77
EC
12800 /* new val must satisfy old val knowledge */
12801 return range_within(rold, rcur) &&
12802 tnum_in(rold->var_off, rcur->var_off);
12803 } else {
179d1c56
JH
12804 /* We're trying to use a pointer in place of a scalar.
12805 * Even if the scalar was unbounded, this could lead to
12806 * pointer leaks because scalars are allowed to leak
12807 * while pointers are not. We could make this safe in
12808 * special cases if root is calling us, but it's
12809 * probably not worth the hassle.
f1174f77 12810 */
179d1c56 12811 return false;
f1174f77 12812 }
69c087ba 12813 case PTR_TO_MAP_KEY:
f1174f77 12814 case PTR_TO_MAP_VALUE:
c25b2ae1
HL
12815 /* a PTR_TO_MAP_VALUE could be safe to use as a
12816 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
12817 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
12818 * checked, doing so could have affected others with the same
12819 * id, and we can't check for that because we lost the id when
12820 * we converted to a PTR_TO_MAP_VALUE.
12821 */
12822 if (type_may_be_null(rold->type)) {
12823 if (!type_may_be_null(rcur->type))
12824 return false;
12825 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
12826 return false;
12827 /* Check our ids match any regs they're supposed to */
12828 return check_ids(rold->id, rcur->id, idmap);
12829 }
12830
1b688a19
EC
12831 /* If the new min/max/var_off satisfy the old ones and
12832 * everything else matches, we are OK.
d83525ca
AS
12833 * 'id' is not compared, since it's only used for maps with
12834 * bpf_spin_lock inside map element and in such cases if
12835 * the rest of the prog is valid for one map element then
12836 * it's valid for all map elements regardless of the key
12837 * used in bpf_map_lookup()
1b688a19
EC
12838 */
12839 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
12840 range_within(rold, rcur) &&
12841 tnum_in(rold->var_off, rcur->var_off);
de8f3a83 12842 case PTR_TO_PACKET_META:
f1174f77 12843 case PTR_TO_PACKET:
de8f3a83 12844 if (rcur->type != rold->type)
f1174f77
EC
12845 return false;
12846 /* We must have at least as much range as the old ptr
12847 * did, so that any accesses which were safe before are
12848 * still safe. This is true even if old range < old off,
12849 * since someone could have accessed through (ptr - k), or
12850 * even done ptr -= k in a register, to get a safe access.
12851 */
12852 if (rold->range > rcur->range)
12853 return false;
12854 /* If the offsets don't match, we can't trust our alignment;
12855 * nor can we be sure that we won't fall out of range.
12856 */
12857 if (rold->off != rcur->off)
12858 return false;
12859 /* id relations must be preserved */
12860 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
12861 return false;
12862 /* new val must satisfy old val knowledge */
12863 return range_within(rold, rcur) &&
12864 tnum_in(rold->var_off, rcur->var_off);
12865 case PTR_TO_CTX:
12866 case CONST_PTR_TO_MAP:
f1174f77 12867 case PTR_TO_PACKET_END:
d58e468b 12868 case PTR_TO_FLOW_KEYS:
c64b7983 12869 case PTR_TO_SOCKET:
46f8bc92 12870 case PTR_TO_SOCK_COMMON:
655a51e5 12871 case PTR_TO_TCP_SOCK:
fada7fdc 12872 case PTR_TO_XDP_SOCK:
f1174f77
EC
12873 /* Only valid matches are exact, which memcmp() above
12874 * would have accepted
12875 */
12876 default:
12877 /* Don't know what's going on, just say it's not safe */
12878 return false;
12879 }
969bf05e 12880
f1174f77
EC
12881 /* Shouldn't get here; if we do, say it's not safe */
12882 WARN_ON_ONCE(1);
969bf05e
AS
12883 return false;
12884}
12885
e042aa53
DB
12886static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
12887 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
638f5b90
AS
12888{
12889 int i, spi;
12890
638f5b90
AS
12891 /* walk slots of the explored stack and ignore any additional
12892 * slots in the current stack, since explored(safe) state
12893 * didn't use them
12894 */
12895 for (i = 0; i < old->allocated_stack; i++) {
12896 spi = i / BPF_REG_SIZE;
12897
b233920c
AS
12898 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
12899 i += BPF_REG_SIZE - 1;
cc2b14d5 12900 /* explored state didn't use this */
fd05e57b 12901 continue;
b233920c 12902 }
cc2b14d5 12903
638f5b90
AS
12904 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
12905 continue;
19e2dbb7
AS
12906
12907 /* explored stack has more populated slots than current stack
12908 * and these slots were used
12909 */
12910 if (i >= cur->allocated_stack)
12911 return false;
12912
cc2b14d5
AS
12913 /* if old state was safe with misc data in the stack
12914 * it will be safe with zero-initialized stack.
12915 * The opposite is not true
12916 */
12917 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
12918 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
12919 continue;
638f5b90
AS
12920 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
12921 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
12922 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 12923 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
12924 * this verifier states are not equivalent,
12925 * return false to continue verification of this path
12926 */
12927 return false;
27113c59 12928 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
638f5b90 12929 continue;
27113c59 12930 if (!is_spilled_reg(&old->stack[spi]))
638f5b90 12931 continue;
e042aa53
DB
12932 if (!regsafe(env, &old->stack[spi].spilled_ptr,
12933 &cur->stack[spi].spilled_ptr, idmap))
638f5b90
AS
12934 /* when explored and current stack slot are both storing
12935 * spilled registers, check that stored pointers types
12936 * are the same as well.
12937 * Ex: explored safe path could have stored
12938 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
12939 * but current path has stored:
12940 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
12941 * such verifier states are not equivalent.
12942 * return false to continue verification of this path
12943 */
12944 return false;
12945 }
12946 return true;
12947}
12948
fd978bf7
JS
12949static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
12950{
12951 if (old->acquired_refs != cur->acquired_refs)
12952 return false;
12953 return !memcmp(old->refs, cur->refs,
12954 sizeof(*old->refs) * old->acquired_refs);
12955}
12956
f1bca824
AS
12957/* compare two verifier states
12958 *
12959 * all states stored in state_list are known to be valid, since
12960 * verifier reached 'bpf_exit' instruction through them
12961 *
12962 * this function is called when verifier exploring different branches of
12963 * execution popped from the state stack. If it sees an old state that has
12964 * more strict register state and more strict stack state then this execution
12965 * branch doesn't need to be explored further, since verifier already
12966 * concluded that more strict state leads to valid finish.
12967 *
12968 * Therefore two states are equivalent if register state is more conservative
12969 * and explored stack state is more conservative than the current one.
12970 * Example:
12971 * explored current
12972 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
12973 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
12974 *
12975 * In other words if current stack state (one being explored) has more
12976 * valid slots than old one that already passed validation, it means
12977 * the verifier can stop exploring and conclude that current state is valid too
12978 *
12979 * Similarly with registers. If explored state has register type as invalid
12980 * whereas register type in current state is meaningful, it means that
12981 * the current state will reach 'bpf_exit' instruction safely
12982 */
c9e73e3d 12983static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
f4d7e40a 12984 struct bpf_func_state *cur)
f1bca824
AS
12985{
12986 int i;
12987
c9e73e3d
LB
12988 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
12989 for (i = 0; i < MAX_BPF_REG; i++)
e042aa53
DB
12990 if (!regsafe(env, &old->regs[i], &cur->regs[i],
12991 env->idmap_scratch))
c9e73e3d 12992 return false;
f1bca824 12993
e042aa53 12994 if (!stacksafe(env, old, cur, env->idmap_scratch))
c9e73e3d 12995 return false;
fd978bf7
JS
12996
12997 if (!refsafe(old, cur))
c9e73e3d
LB
12998 return false;
12999
13000 return true;
f1bca824
AS
13001}
13002
f4d7e40a
AS
13003static bool states_equal(struct bpf_verifier_env *env,
13004 struct bpf_verifier_state *old,
13005 struct bpf_verifier_state *cur)
13006{
13007 int i;
13008
13009 if (old->curframe != cur->curframe)
13010 return false;
13011
979d63d5
DB
13012 /* Verification state from speculative execution simulation
13013 * must never prune a non-speculative execution one.
13014 */
13015 if (old->speculative && !cur->speculative)
13016 return false;
13017
d0d78c1d
KKD
13018 if (old->active_lock.ptr != cur->active_lock.ptr ||
13019 old->active_lock.id != cur->active_lock.id)
d83525ca
AS
13020 return false;
13021
f4d7e40a
AS
13022 /* for states to be equal callsites have to be the same
13023 * and all frame states need to be equivalent
13024 */
13025 for (i = 0; i <= old->curframe; i++) {
13026 if (old->frame[i]->callsite != cur->frame[i]->callsite)
13027 return false;
c9e73e3d 13028 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
f4d7e40a
AS
13029 return false;
13030 }
13031 return true;
13032}
13033
5327ed3d
JW
13034/* Return 0 if no propagation happened. Return negative error code if error
13035 * happened. Otherwise, return the propagated bit.
13036 */
55e7f3b5
JW
13037static int propagate_liveness_reg(struct bpf_verifier_env *env,
13038 struct bpf_reg_state *reg,
13039 struct bpf_reg_state *parent_reg)
13040{
5327ed3d
JW
13041 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
13042 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
13043 int err;
13044
5327ed3d
JW
13045 /* When comes here, read flags of PARENT_REG or REG could be any of
13046 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
13047 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
13048 */
13049 if (parent_flag == REG_LIVE_READ64 ||
13050 /* Or if there is no read flag from REG. */
13051 !flag ||
13052 /* Or if the read flag from REG is the same as PARENT_REG. */
13053 parent_flag == flag)
55e7f3b5
JW
13054 return 0;
13055
5327ed3d 13056 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
13057 if (err)
13058 return err;
13059
5327ed3d 13060 return flag;
55e7f3b5
JW
13061}
13062
8e9cd9ce 13063/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
13064 * straight-line code between a state and its parent. When we arrive at an
13065 * equivalent state (jump target or such) we didn't arrive by the straight-line
13066 * code, so read marks in the state must propagate to the parent regardless
13067 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 13068 * in mark_reg_read() is for.
8e9cd9ce 13069 */
f4d7e40a
AS
13070static int propagate_liveness(struct bpf_verifier_env *env,
13071 const struct bpf_verifier_state *vstate,
13072 struct bpf_verifier_state *vparent)
dc503a8a 13073{
3f8cafa4 13074 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 13075 struct bpf_func_state *state, *parent;
3f8cafa4 13076 int i, frame, err = 0;
dc503a8a 13077
f4d7e40a
AS
13078 if (vparent->curframe != vstate->curframe) {
13079 WARN(1, "propagate_live: parent frame %d current frame %d\n",
13080 vparent->curframe, vstate->curframe);
13081 return -EFAULT;
13082 }
dc503a8a
EC
13083 /* Propagate read liveness of registers... */
13084 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 13085 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
13086 parent = vparent->frame[frame];
13087 state = vstate->frame[frame];
13088 parent_reg = parent->regs;
13089 state_reg = state->regs;
83d16312
JK
13090 /* We don't need to worry about FP liveness, it's read-only */
13091 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
13092 err = propagate_liveness_reg(env, &state_reg[i],
13093 &parent_reg[i]);
5327ed3d 13094 if (err < 0)
3f8cafa4 13095 return err;
5327ed3d
JW
13096 if (err == REG_LIVE_READ64)
13097 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 13098 }
f4d7e40a 13099
1b04aee7 13100 /* Propagate stack slots. */
f4d7e40a
AS
13101 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
13102 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
13103 parent_reg = &parent->stack[i].spilled_ptr;
13104 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
13105 err = propagate_liveness_reg(env, state_reg,
13106 parent_reg);
5327ed3d 13107 if (err < 0)
3f8cafa4 13108 return err;
dc503a8a
EC
13109 }
13110 }
5327ed3d 13111 return 0;
dc503a8a
EC
13112}
13113
a3ce685d
AS
13114/* find precise scalars in the previous equivalent state and
13115 * propagate them into the current state
13116 */
13117static int propagate_precision(struct bpf_verifier_env *env,
13118 const struct bpf_verifier_state *old)
13119{
13120 struct bpf_reg_state *state_reg;
13121 struct bpf_func_state *state;
529409ea 13122 int i, err = 0, fr;
a3ce685d 13123
529409ea
AN
13124 for (fr = old->curframe; fr >= 0; fr--) {
13125 state = old->frame[fr];
13126 state_reg = state->regs;
13127 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
13128 if (state_reg->type != SCALAR_VALUE ||
13129 !state_reg->precise)
13130 continue;
13131 if (env->log.level & BPF_LOG_LEVEL2)
13132 verbose(env, "frame %d: propagating r%d\n", i, fr);
13133 err = mark_chain_precision_frame(env, fr, i);
13134 if (err < 0)
13135 return err;
13136 }
a3ce685d 13137
529409ea
AN
13138 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
13139 if (!is_spilled_reg(&state->stack[i]))
13140 continue;
13141 state_reg = &state->stack[i].spilled_ptr;
13142 if (state_reg->type != SCALAR_VALUE ||
13143 !state_reg->precise)
13144 continue;
13145 if (env->log.level & BPF_LOG_LEVEL2)
13146 verbose(env, "frame %d: propagating fp%d\n",
13147 (-i - 1) * BPF_REG_SIZE, fr);
13148 err = mark_chain_precision_stack_frame(env, fr, i);
13149 if (err < 0)
13150 return err;
13151 }
a3ce685d
AS
13152 }
13153 return 0;
13154}
13155
2589726d
AS
13156static bool states_maybe_looping(struct bpf_verifier_state *old,
13157 struct bpf_verifier_state *cur)
13158{
13159 struct bpf_func_state *fold, *fcur;
13160 int i, fr = cur->curframe;
13161
13162 if (old->curframe != fr)
13163 return false;
13164
13165 fold = old->frame[fr];
13166 fcur = cur->frame[fr];
13167 for (i = 0; i < MAX_BPF_REG; i++)
13168 if (memcmp(&fold->regs[i], &fcur->regs[i],
13169 offsetof(struct bpf_reg_state, parent)))
13170 return false;
13171 return true;
13172}
13173
13174
58e2af8b 13175static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 13176{
58e2af8b 13177 struct bpf_verifier_state_list *new_sl;
9f4686c4 13178 struct bpf_verifier_state_list *sl, **pprev;
679c782d 13179 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 13180 int i, j, err, states_cnt = 0;
10d274e8 13181 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 13182
b5dc0163 13183 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 13184 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
13185 /* this 'insn_idx' instruction wasn't marked, so we will not
13186 * be doing state search here
13187 */
13188 return 0;
13189
2589726d
AS
13190 /* bpf progs typically have pruning point every 4 instructions
13191 * http://vger.kernel.org/bpfconf2019.html#session-1
13192 * Do not add new state for future pruning if the verifier hasn't seen
13193 * at least 2 jumps and at least 8 instructions.
13194 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
13195 * In tests that amounts to up to 50% reduction into total verifier
13196 * memory consumption and 20% verifier time speedup.
13197 */
13198 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
13199 env->insn_processed - env->prev_insn_processed >= 8)
13200 add_new_state = true;
13201
a8f500af
AS
13202 pprev = explored_state(env, insn_idx);
13203 sl = *pprev;
13204
9242b5f5
AS
13205 clean_live_states(env, insn_idx, cur);
13206
a8f500af 13207 while (sl) {
dc2a4ebc
AS
13208 states_cnt++;
13209 if (sl->state.insn_idx != insn_idx)
13210 goto next;
bfc6bb74 13211
2589726d 13212 if (sl->state.branches) {
bfc6bb74
AS
13213 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
13214
13215 if (frame->in_async_callback_fn &&
13216 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
13217 /* Different async_entry_cnt means that the verifier is
13218 * processing another entry into async callback.
13219 * Seeing the same state is not an indication of infinite
13220 * loop or infinite recursion.
13221 * But finding the same state doesn't mean that it's safe
13222 * to stop processing the current state. The previous state
13223 * hasn't yet reached bpf_exit, since state.branches > 0.
13224 * Checking in_async_callback_fn alone is not enough either.
13225 * Since the verifier still needs to catch infinite loops
13226 * inside async callbacks.
13227 */
13228 } else if (states_maybe_looping(&sl->state, cur) &&
13229 states_equal(env, &sl->state, cur)) {
2589726d
AS
13230 verbose_linfo(env, insn_idx, "; ");
13231 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
13232 return -EINVAL;
13233 }
13234 /* if the verifier is processing a loop, avoid adding new state
13235 * too often, since different loop iterations have distinct
13236 * states and may not help future pruning.
13237 * This threshold shouldn't be too low to make sure that
13238 * a loop with large bound will be rejected quickly.
13239 * The most abusive loop will be:
13240 * r1 += 1
13241 * if r1 < 1000000 goto pc-2
13242 * 1M insn_procssed limit / 100 == 10k peak states.
13243 * This threshold shouldn't be too high either, since states
13244 * at the end of the loop are likely to be useful in pruning.
13245 */
13246 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
13247 env->insn_processed - env->prev_insn_processed < 100)
13248 add_new_state = false;
13249 goto miss;
13250 }
638f5b90 13251 if (states_equal(env, &sl->state, cur)) {
9f4686c4 13252 sl->hit_cnt++;
f1bca824 13253 /* reached equivalent register/stack state,
dc503a8a
EC
13254 * prune the search.
13255 * Registers read by the continuation are read by us.
8e9cd9ce
EC
13256 * If we have any write marks in env->cur_state, they
13257 * will prevent corresponding reads in the continuation
13258 * from reaching our parent (an explored_state). Our
13259 * own state will get the read marks recorded, but
13260 * they'll be immediately forgotten as we're pruning
13261 * this state and will pop a new one.
f1bca824 13262 */
f4d7e40a 13263 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
13264
13265 /* if previous state reached the exit with precision and
13266 * current state is equivalent to it (except precsion marks)
13267 * the precision needs to be propagated back in
13268 * the current state.
13269 */
13270 err = err ? : push_jmp_history(env, cur);
13271 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
13272 if (err)
13273 return err;
f1bca824 13274 return 1;
dc503a8a 13275 }
2589726d
AS
13276miss:
13277 /* when new state is not going to be added do not increase miss count.
13278 * Otherwise several loop iterations will remove the state
13279 * recorded earlier. The goal of these heuristics is to have
13280 * states from some iterations of the loop (some in the beginning
13281 * and some at the end) to help pruning.
13282 */
13283 if (add_new_state)
13284 sl->miss_cnt++;
9f4686c4
AS
13285 /* heuristic to determine whether this state is beneficial
13286 * to keep checking from state equivalence point of view.
13287 * Higher numbers increase max_states_per_insn and verification time,
13288 * but do not meaningfully decrease insn_processed.
13289 */
13290 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
13291 /* the state is unlikely to be useful. Remove it to
13292 * speed up verification
13293 */
13294 *pprev = sl->next;
13295 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
13296 u32 br = sl->state.branches;
13297
13298 WARN_ONCE(br,
13299 "BUG live_done but branches_to_explore %d\n",
13300 br);
9f4686c4
AS
13301 free_verifier_state(&sl->state, false);
13302 kfree(sl);
13303 env->peak_states--;
13304 } else {
13305 /* cannot free this state, since parentage chain may
13306 * walk it later. Add it for free_list instead to
13307 * be freed at the end of verification
13308 */
13309 sl->next = env->free_list;
13310 env->free_list = sl;
13311 }
13312 sl = *pprev;
13313 continue;
13314 }
dc2a4ebc 13315next:
9f4686c4
AS
13316 pprev = &sl->next;
13317 sl = *pprev;
f1bca824
AS
13318 }
13319
06ee7115
AS
13320 if (env->max_states_per_insn < states_cnt)
13321 env->max_states_per_insn = states_cnt;
13322
2c78ee89 13323 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 13324 return push_jmp_history(env, cur);
ceefbc96 13325
2589726d 13326 if (!add_new_state)
b5dc0163 13327 return push_jmp_history(env, cur);
ceefbc96 13328
2589726d
AS
13329 /* There were no equivalent states, remember the current one.
13330 * Technically the current state is not proven to be safe yet,
f4d7e40a 13331 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 13332 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 13333 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
13334 * again on the way to bpf_exit.
13335 * When looping the sl->state.branches will be > 0 and this state
13336 * will not be considered for equivalence until branches == 0.
f1bca824 13337 */
638f5b90 13338 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
13339 if (!new_sl)
13340 return -ENOMEM;
06ee7115
AS
13341 env->total_states++;
13342 env->peak_states++;
2589726d
AS
13343 env->prev_jmps_processed = env->jmps_processed;
13344 env->prev_insn_processed = env->insn_processed;
f1bca824 13345
7a830b53
AN
13346 /* forget precise markings we inherited, see __mark_chain_precision */
13347 if (env->bpf_capable)
13348 mark_all_scalars_imprecise(env, cur);
13349
f1bca824 13350 /* add new state to the head of linked list */
679c782d
EC
13351 new = &new_sl->state;
13352 err = copy_verifier_state(new, cur);
1969db47 13353 if (err) {
679c782d 13354 free_verifier_state(new, false);
1969db47
AS
13355 kfree(new_sl);
13356 return err;
13357 }
dc2a4ebc 13358 new->insn_idx = insn_idx;
2589726d
AS
13359 WARN_ONCE(new->branches != 1,
13360 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 13361
2589726d 13362 cur->parent = new;
b5dc0163
AS
13363 cur->first_insn_idx = insn_idx;
13364 clear_jmp_history(cur);
5d839021
AS
13365 new_sl->next = *explored_state(env, insn_idx);
13366 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
13367 /* connect new state to parentage chain. Current frame needs all
13368 * registers connected. Only r6 - r9 of the callers are alive (pushed
13369 * to the stack implicitly by JITs) so in callers' frames connect just
13370 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
13371 * the state of the call instruction (with WRITTEN set), and r0 comes
13372 * from callee with its full parentage chain, anyway.
13373 */
8e9cd9ce
EC
13374 /* clear write marks in current state: the writes we did are not writes
13375 * our child did, so they don't screen off its reads from us.
13376 * (There are no read marks in current state, because reads always mark
13377 * their parent and current state never has children yet. Only
13378 * explored_states can get read marks.)
13379 */
eea1c227
AS
13380 for (j = 0; j <= cur->curframe; j++) {
13381 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
13382 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
13383 for (i = 0; i < BPF_REG_FP; i++)
13384 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
13385 }
f4d7e40a
AS
13386
13387 /* all stack frames are accessible from callee, clear them all */
13388 for (j = 0; j <= cur->curframe; j++) {
13389 struct bpf_func_state *frame = cur->frame[j];
679c782d 13390 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 13391
679c782d 13392 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 13393 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
13394 frame->stack[i].spilled_ptr.parent =
13395 &newframe->stack[i].spilled_ptr;
13396 }
f4d7e40a 13397 }
f1bca824
AS
13398 return 0;
13399}
13400
c64b7983
JS
13401/* Return true if it's OK to have the same insn return a different type. */
13402static bool reg_type_mismatch_ok(enum bpf_reg_type type)
13403{
c25b2ae1 13404 switch (base_type(type)) {
c64b7983
JS
13405 case PTR_TO_CTX:
13406 case PTR_TO_SOCKET:
46f8bc92 13407 case PTR_TO_SOCK_COMMON:
655a51e5 13408 case PTR_TO_TCP_SOCK:
fada7fdc 13409 case PTR_TO_XDP_SOCK:
2a02759e 13410 case PTR_TO_BTF_ID:
c64b7983
JS
13411 return false;
13412 default:
13413 return true;
13414 }
13415}
13416
13417/* If an instruction was previously used with particular pointer types, then we
13418 * need to be careful to avoid cases such as the below, where it may be ok
13419 * for one branch accessing the pointer, but not ok for the other branch:
13420 *
13421 * R1 = sock_ptr
13422 * goto X;
13423 * ...
13424 * R1 = some_other_valid_ptr;
13425 * goto X;
13426 * ...
13427 * R2 = *(u32 *)(R1 + 0);
13428 */
13429static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
13430{
13431 return src != prev && (!reg_type_mismatch_ok(src) ||
13432 !reg_type_mismatch_ok(prev));
13433}
13434
58e2af8b 13435static int do_check(struct bpf_verifier_env *env)
17a52670 13436{
6f8a57cc 13437 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 13438 struct bpf_verifier_state *state = env->cur_state;
17a52670 13439 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 13440 struct bpf_reg_state *regs;
06ee7115 13441 int insn_cnt = env->prog->len;
17a52670 13442 bool do_print_state = false;
b5dc0163 13443 int prev_insn_idx = -1;
17a52670 13444
17a52670
AS
13445 for (;;) {
13446 struct bpf_insn *insn;
13447 u8 class;
13448 int err;
13449
b5dc0163 13450 env->prev_insn_idx = prev_insn_idx;
c08435ec 13451 if (env->insn_idx >= insn_cnt) {
61bd5218 13452 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 13453 env->insn_idx, insn_cnt);
17a52670
AS
13454 return -EFAULT;
13455 }
13456
c08435ec 13457 insn = &insns[env->insn_idx];
17a52670
AS
13458 class = BPF_CLASS(insn->code);
13459
06ee7115 13460 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
13461 verbose(env,
13462 "BPF program is too large. Processed %d insn\n",
06ee7115 13463 env->insn_processed);
17a52670
AS
13464 return -E2BIG;
13465 }
13466
c08435ec 13467 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
13468 if (err < 0)
13469 return err;
13470 if (err == 1) {
13471 /* found equivalent state, can prune the search */
06ee7115 13472 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 13473 if (do_print_state)
979d63d5
DB
13474 verbose(env, "\nfrom %d to %d%s: safe\n",
13475 env->prev_insn_idx, env->insn_idx,
13476 env->cur_state->speculative ?
13477 " (speculative execution)" : "");
f1bca824 13478 else
c08435ec 13479 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
13480 }
13481 goto process_bpf_exit;
13482 }
13483
c3494801
AS
13484 if (signal_pending(current))
13485 return -EAGAIN;
13486
3c2ce60b
DB
13487 if (need_resched())
13488 cond_resched();
13489
2e576648
CL
13490 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
13491 verbose(env, "\nfrom %d to %d%s:",
13492 env->prev_insn_idx, env->insn_idx,
13493 env->cur_state->speculative ?
13494 " (speculative execution)" : "");
13495 print_verifier_state(env, state->frame[state->curframe], true);
17a52670
AS
13496 do_print_state = false;
13497 }
13498
06ee7115 13499 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 13500 const struct bpf_insn_cbs cbs = {
e6ac2450 13501 .cb_call = disasm_kfunc_name,
7105e828 13502 .cb_print = verbose,
abe08840 13503 .private_data = env,
7105e828
DB
13504 };
13505
2e576648
CL
13506 if (verifier_state_scratched(env))
13507 print_insn_state(env, state->frame[state->curframe]);
13508
c08435ec 13509 verbose_linfo(env, env->insn_idx, "; ");
2e576648 13510 env->prev_log_len = env->log.len_used;
c08435ec 13511 verbose(env, "%d: ", env->insn_idx);
abe08840 13512 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2e576648
CL
13513 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
13514 env->prev_log_len = env->log.len_used;
17a52670
AS
13515 }
13516
cae1927c 13517 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
13518 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
13519 env->prev_insn_idx);
cae1927c
JK
13520 if (err)
13521 return err;
13522 }
13a27dfc 13523
638f5b90 13524 regs = cur_regs(env);
fe9a5ca7 13525 sanitize_mark_insn_seen(env);
b5dc0163 13526 prev_insn_idx = env->insn_idx;
fd978bf7 13527
17a52670 13528 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 13529 err = check_alu_op(env, insn);
17a52670
AS
13530 if (err)
13531 return err;
13532
13533 } else if (class == BPF_LDX) {
3df126f3 13534 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
13535
13536 /* check for reserved fields is already done */
13537
17a52670 13538 /* check src operand */
dc503a8a 13539 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13540 if (err)
13541 return err;
13542
dc503a8a 13543 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
13544 if (err)
13545 return err;
13546
725f9dcd
AS
13547 src_reg_type = regs[insn->src_reg].type;
13548
17a52670
AS
13549 /* check that memory (src_reg + off) is readable,
13550 * the state of dst_reg will be updated by this func
13551 */
c08435ec
DB
13552 err = check_mem_access(env, env->insn_idx, insn->src_reg,
13553 insn->off, BPF_SIZE(insn->code),
13554 BPF_READ, insn->dst_reg, false);
17a52670
AS
13555 if (err)
13556 return err;
13557
c08435ec 13558 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
13559
13560 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
13561 /* saw a valid insn
13562 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 13563 * save type to validate intersecting paths
9bac3d6d 13564 */
3df126f3 13565 *prev_src_type = src_reg_type;
9bac3d6d 13566
c64b7983 13567 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
13568 /* ABuser program is trying to use the same insn
13569 * dst_reg = *(u32*) (src_reg + off)
13570 * with different pointer types:
13571 * src_reg == ctx in one branch and
13572 * src_reg == stack|map in some other branch.
13573 * Reject it.
13574 */
61bd5218 13575 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
13576 return -EINVAL;
13577 }
13578
17a52670 13579 } else if (class == BPF_STX) {
3df126f3 13580 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 13581
91c960b0
BJ
13582 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
13583 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
13584 if (err)
13585 return err;
c08435ec 13586 env->insn_idx++;
17a52670
AS
13587 continue;
13588 }
13589
5ca419f2
BJ
13590 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
13591 verbose(env, "BPF_STX uses reserved fields\n");
13592 return -EINVAL;
13593 }
13594
17a52670 13595 /* check src1 operand */
dc503a8a 13596 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
13597 if (err)
13598 return err;
13599 /* check src2 operand */
dc503a8a 13600 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13601 if (err)
13602 return err;
13603
d691f9e8
AS
13604 dst_reg_type = regs[insn->dst_reg].type;
13605
17a52670 13606 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
13607 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13608 insn->off, BPF_SIZE(insn->code),
13609 BPF_WRITE, insn->src_reg, false);
17a52670
AS
13610 if (err)
13611 return err;
13612
c08435ec 13613 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
13614
13615 if (*prev_dst_type == NOT_INIT) {
13616 *prev_dst_type = dst_reg_type;
c64b7983 13617 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 13618 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
13619 return -EINVAL;
13620 }
13621
17a52670
AS
13622 } else if (class == BPF_ST) {
13623 if (BPF_MODE(insn->code) != BPF_MEM ||
13624 insn->src_reg != BPF_REG_0) {
61bd5218 13625 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
13626 return -EINVAL;
13627 }
13628 /* check src operand */
dc503a8a 13629 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
13630 if (err)
13631 return err;
13632
f37a8cb8 13633 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 13634 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f 13635 insn->dst_reg,
c25b2ae1 13636 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
f37a8cb8
DB
13637 return -EACCES;
13638 }
13639
17a52670 13640 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
13641 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
13642 insn->off, BPF_SIZE(insn->code),
13643 BPF_WRITE, -1, false);
17a52670
AS
13644 if (err)
13645 return err;
13646
092ed096 13647 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
13648 u8 opcode = BPF_OP(insn->code);
13649
2589726d 13650 env->jmps_processed++;
17a52670
AS
13651 if (opcode == BPF_CALL) {
13652 if (BPF_SRC(insn->code) != BPF_K ||
2357672c
KKD
13653 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
13654 && insn->off != 0) ||
f4d7e40a 13655 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
13656 insn->src_reg != BPF_PSEUDO_CALL &&
13657 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
13658 insn->dst_reg != BPF_REG_0 ||
13659 class == BPF_JMP32) {
61bd5218 13660 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
13661 return -EINVAL;
13662 }
13663
8cab76ec
KKD
13664 if (env->cur_state->active_lock.ptr) {
13665 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
13666 (insn->src_reg == BPF_PSEUDO_CALL) ||
13667 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
13668 (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) {
13669 verbose(env, "function calls are not allowed while holding a lock\n");
13670 return -EINVAL;
13671 }
d83525ca 13672 }
f4d7e40a 13673 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 13674 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450 13675 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
5c073f26 13676 err = check_kfunc_call(env, insn, &env->insn_idx);
f4d7e40a 13677 else
69c087ba 13678 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
13679 if (err)
13680 return err;
17a52670
AS
13681 } else if (opcode == BPF_JA) {
13682 if (BPF_SRC(insn->code) != BPF_K ||
13683 insn->imm != 0 ||
13684 insn->src_reg != BPF_REG_0 ||
092ed096
JW
13685 insn->dst_reg != BPF_REG_0 ||
13686 class == BPF_JMP32) {
61bd5218 13687 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
13688 return -EINVAL;
13689 }
13690
c08435ec 13691 env->insn_idx += insn->off + 1;
17a52670
AS
13692 continue;
13693
13694 } else if (opcode == BPF_EXIT) {
13695 if (BPF_SRC(insn->code) != BPF_K ||
13696 insn->imm != 0 ||
13697 insn->src_reg != BPF_REG_0 ||
092ed096
JW
13698 insn->dst_reg != BPF_REG_0 ||
13699 class == BPF_JMP32) {
61bd5218 13700 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
13701 return -EINVAL;
13702 }
13703
d0d78c1d 13704 if (env->cur_state->active_lock.ptr) {
d83525ca
AS
13705 verbose(env, "bpf_spin_unlock is missing\n");
13706 return -EINVAL;
13707 }
13708
9d9d00ac
KKD
13709 /* We must do check_reference_leak here before
13710 * prepare_func_exit to handle the case when
13711 * state->curframe > 0, it may be a callback
13712 * function, for which reference_state must
13713 * match caller reference state when it exits.
13714 */
13715 err = check_reference_leak(env);
13716 if (err)
13717 return err;
13718
f4d7e40a
AS
13719 if (state->curframe) {
13720 /* exit from nested function */
c08435ec 13721 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
13722 if (err)
13723 return err;
13724 do_print_state = true;
13725 continue;
13726 }
13727
390ee7e2
AS
13728 err = check_return_code(env);
13729 if (err)
13730 return err;
f1bca824 13731process_bpf_exit:
0f55f9ed 13732 mark_verifier_state_scratched(env);
2589726d 13733 update_branch_counts(env, env->cur_state);
b5dc0163 13734 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 13735 &env->insn_idx, pop_log);
638f5b90
AS
13736 if (err < 0) {
13737 if (err != -ENOENT)
13738 return err;
17a52670
AS
13739 break;
13740 } else {
13741 do_print_state = true;
13742 continue;
13743 }
13744 } else {
c08435ec 13745 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
13746 if (err)
13747 return err;
13748 }
13749 } else if (class == BPF_LD) {
13750 u8 mode = BPF_MODE(insn->code);
13751
13752 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
13753 err = check_ld_abs(env, insn);
13754 if (err)
13755 return err;
13756
17a52670
AS
13757 } else if (mode == BPF_IMM) {
13758 err = check_ld_imm(env, insn);
13759 if (err)
13760 return err;
13761
c08435ec 13762 env->insn_idx++;
fe9a5ca7 13763 sanitize_mark_insn_seen(env);
17a52670 13764 } else {
61bd5218 13765 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
13766 return -EINVAL;
13767 }
13768 } else {
61bd5218 13769 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
13770 return -EINVAL;
13771 }
13772
c08435ec 13773 env->insn_idx++;
17a52670
AS
13774 }
13775
13776 return 0;
13777}
13778
541c3bad
AN
13779static int find_btf_percpu_datasec(struct btf *btf)
13780{
13781 const struct btf_type *t;
13782 const char *tname;
13783 int i, n;
13784
13785 /*
13786 * Both vmlinux and module each have their own ".data..percpu"
13787 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
13788 * types to look at only module's own BTF types.
13789 */
13790 n = btf_nr_types(btf);
13791 if (btf_is_module(btf))
13792 i = btf_nr_types(btf_vmlinux);
13793 else
13794 i = 1;
13795
13796 for(; i < n; i++) {
13797 t = btf_type_by_id(btf, i);
13798 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
13799 continue;
13800
13801 tname = btf_name_by_offset(btf, t->name_off);
13802 if (!strcmp(tname, ".data..percpu"))
13803 return i;
13804 }
13805
13806 return -ENOENT;
13807}
13808
4976b718
HL
13809/* replace pseudo btf_id with kernel symbol address */
13810static int check_pseudo_btf_id(struct bpf_verifier_env *env,
13811 struct bpf_insn *insn,
13812 struct bpf_insn_aux_data *aux)
13813{
eaa6bcb7
HL
13814 const struct btf_var_secinfo *vsi;
13815 const struct btf_type *datasec;
541c3bad 13816 struct btf_mod_pair *btf_mod;
4976b718
HL
13817 const struct btf_type *t;
13818 const char *sym_name;
eaa6bcb7 13819 bool percpu = false;
f16e6313 13820 u32 type, id = insn->imm;
541c3bad 13821 struct btf *btf;
f16e6313 13822 s32 datasec_id;
4976b718 13823 u64 addr;
541c3bad 13824 int i, btf_fd, err;
4976b718 13825
541c3bad
AN
13826 btf_fd = insn[1].imm;
13827 if (btf_fd) {
13828 btf = btf_get_by_fd(btf_fd);
13829 if (IS_ERR(btf)) {
13830 verbose(env, "invalid module BTF object FD specified.\n");
13831 return -EINVAL;
13832 }
13833 } else {
13834 if (!btf_vmlinux) {
13835 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
13836 return -EINVAL;
13837 }
13838 btf = btf_vmlinux;
13839 btf_get(btf);
4976b718
HL
13840 }
13841
541c3bad 13842 t = btf_type_by_id(btf, id);
4976b718
HL
13843 if (!t) {
13844 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
13845 err = -ENOENT;
13846 goto err_put;
4976b718
HL
13847 }
13848
13849 if (!btf_type_is_var(t)) {
541c3bad
AN
13850 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
13851 err = -EINVAL;
13852 goto err_put;
4976b718
HL
13853 }
13854
541c3bad 13855 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
13856 addr = kallsyms_lookup_name(sym_name);
13857 if (!addr) {
13858 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
13859 sym_name);
541c3bad
AN
13860 err = -ENOENT;
13861 goto err_put;
4976b718
HL
13862 }
13863
541c3bad 13864 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 13865 if (datasec_id > 0) {
541c3bad 13866 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
13867 for_each_vsi(i, datasec, vsi) {
13868 if (vsi->type == id) {
13869 percpu = true;
13870 break;
13871 }
13872 }
13873 }
13874
4976b718
HL
13875 insn[0].imm = (u32)addr;
13876 insn[1].imm = addr >> 32;
13877
13878 type = t->type;
541c3bad 13879 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7 13880 if (percpu) {
5844101a 13881 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
541c3bad 13882 aux->btf_var.btf = btf;
eaa6bcb7
HL
13883 aux->btf_var.btf_id = type;
13884 } else if (!btf_type_is_struct(t)) {
4976b718
HL
13885 const struct btf_type *ret;
13886 const char *tname;
13887 u32 tsize;
13888
13889 /* resolve the type size of ksym. */
541c3bad 13890 ret = btf_resolve_size(btf, t, &tsize);
4976b718 13891 if (IS_ERR(ret)) {
541c3bad 13892 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
13893 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
13894 tname, PTR_ERR(ret));
541c3bad
AN
13895 err = -EINVAL;
13896 goto err_put;
4976b718 13897 }
34d3a78c 13898 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
4976b718
HL
13899 aux->btf_var.mem_size = tsize;
13900 } else {
13901 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 13902 aux->btf_var.btf = btf;
4976b718
HL
13903 aux->btf_var.btf_id = type;
13904 }
541c3bad
AN
13905
13906 /* check whether we recorded this BTF (and maybe module) already */
13907 for (i = 0; i < env->used_btf_cnt; i++) {
13908 if (env->used_btfs[i].btf == btf) {
13909 btf_put(btf);
13910 return 0;
13911 }
13912 }
13913
13914 if (env->used_btf_cnt >= MAX_USED_BTFS) {
13915 err = -E2BIG;
13916 goto err_put;
13917 }
13918
13919 btf_mod = &env->used_btfs[env->used_btf_cnt];
13920 btf_mod->btf = btf;
13921 btf_mod->module = NULL;
13922
13923 /* if we reference variables from kernel module, bump its refcount */
13924 if (btf_is_module(btf)) {
13925 btf_mod->module = btf_try_get_module(btf);
13926 if (!btf_mod->module) {
13927 err = -ENXIO;
13928 goto err_put;
13929 }
13930 }
13931
13932 env->used_btf_cnt++;
13933
4976b718 13934 return 0;
541c3bad
AN
13935err_put:
13936 btf_put(btf);
13937 return err;
4976b718
HL
13938}
13939
d83525ca
AS
13940static bool is_tracing_prog_type(enum bpf_prog_type type)
13941{
13942 switch (type) {
13943 case BPF_PROG_TYPE_KPROBE:
13944 case BPF_PROG_TYPE_TRACEPOINT:
13945 case BPF_PROG_TYPE_PERF_EVENT:
13946 case BPF_PROG_TYPE_RAW_TRACEPOINT:
5002615a 13947 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
d83525ca
AS
13948 return true;
13949 default:
13950 return false;
13951 }
13952}
13953
61bd5218
JK
13954static int check_map_prog_compatibility(struct bpf_verifier_env *env,
13955 struct bpf_map *map,
fdc15d38
AS
13956 struct bpf_prog *prog)
13957
13958{
7e40781c 13959 enum bpf_prog_type prog_type = resolve_prog_type(prog);
a3884572 13960
f0c5941f
KKD
13961 if (btf_record_has_field(map->record, BPF_LIST_HEAD)) {
13962 if (is_tracing_prog_type(prog_type)) {
13963 verbose(env, "tracing progs cannot use bpf_list_head yet\n");
13964 return -EINVAL;
13965 }
13966 }
13967
db559117 13968 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
9e7a4d98
KS
13969 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
13970 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
13971 return -EINVAL;
13972 }
13973
13974 if (is_tracing_prog_type(prog_type)) {
13975 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
13976 return -EINVAL;
13977 }
13978
13979 if (prog->aux->sleepable) {
13980 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
13981 return -EINVAL;
13982 }
d83525ca
AS
13983 }
13984
db559117 13985 if (btf_record_has_field(map->record, BPF_TIMER)) {
5e0bc308
DB
13986 if (is_tracing_prog_type(prog_type)) {
13987 verbose(env, "tracing progs cannot use bpf_timer yet\n");
13988 return -EINVAL;
13989 }
13990 }
13991
a3884572 13992 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 13993 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
13994 verbose(env, "offload device mismatch between prog and map\n");
13995 return -EINVAL;
13996 }
13997
85d33df3
MKL
13998 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
13999 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
14000 return -EINVAL;
14001 }
14002
1e6c62a8
AS
14003 if (prog->aux->sleepable)
14004 switch (map->map_type) {
14005 case BPF_MAP_TYPE_HASH:
14006 case BPF_MAP_TYPE_LRU_HASH:
14007 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
14008 case BPF_MAP_TYPE_PERCPU_HASH:
14009 case BPF_MAP_TYPE_PERCPU_ARRAY:
14010 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
14011 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
14012 case BPF_MAP_TYPE_HASH_OF_MAPS:
ba90c2cc 14013 case BPF_MAP_TYPE_RINGBUF:
583c1f42 14014 case BPF_MAP_TYPE_USER_RINGBUF:
0fe4b381
KS
14015 case BPF_MAP_TYPE_INODE_STORAGE:
14016 case BPF_MAP_TYPE_SK_STORAGE:
14017 case BPF_MAP_TYPE_TASK_STORAGE:
ba90c2cc 14018 break;
1e6c62a8
AS
14019 default:
14020 verbose(env,
ba90c2cc 14021 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
14022 return -EINVAL;
14023 }
14024
fdc15d38
AS
14025 return 0;
14026}
14027
b741f163
RG
14028static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
14029{
14030 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
14031 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
14032}
14033
4976b718
HL
14034/* find and rewrite pseudo imm in ld_imm64 instructions:
14035 *
14036 * 1. if it accesses map FD, replace it with actual map pointer.
14037 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
14038 *
14039 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 14040 */
4976b718 14041static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
14042{
14043 struct bpf_insn *insn = env->prog->insnsi;
14044 int insn_cnt = env->prog->len;
fdc15d38 14045 int i, j, err;
0246e64d 14046
f1f7714e 14047 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
14048 if (err)
14049 return err;
14050
0246e64d 14051 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 14052 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 14053 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 14054 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
14055 return -EINVAL;
14056 }
14057
0246e64d 14058 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 14059 struct bpf_insn_aux_data *aux;
0246e64d
AS
14060 struct bpf_map *map;
14061 struct fd f;
d8eca5bb 14062 u64 addr;
387544bf 14063 u32 fd;
0246e64d
AS
14064
14065 if (i == insn_cnt - 1 || insn[1].code != 0 ||
14066 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
14067 insn[1].off != 0) {
61bd5218 14068 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
14069 return -EINVAL;
14070 }
14071
d8eca5bb 14072 if (insn[0].src_reg == 0)
0246e64d
AS
14073 /* valid generic load 64-bit imm */
14074 goto next_insn;
14075
4976b718
HL
14076 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
14077 aux = &env->insn_aux_data[i];
14078 err = check_pseudo_btf_id(env, insn, aux);
14079 if (err)
14080 return err;
14081 goto next_insn;
14082 }
14083
69c087ba
YS
14084 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
14085 aux = &env->insn_aux_data[i];
14086 aux->ptr_type = PTR_TO_FUNC;
14087 goto next_insn;
14088 }
14089
d8eca5bb
DB
14090 /* In final convert_pseudo_ld_imm64() step, this is
14091 * converted into regular 64-bit imm load insn.
14092 */
387544bf
AS
14093 switch (insn[0].src_reg) {
14094 case BPF_PSEUDO_MAP_VALUE:
14095 case BPF_PSEUDO_MAP_IDX_VALUE:
14096 break;
14097 case BPF_PSEUDO_MAP_FD:
14098 case BPF_PSEUDO_MAP_IDX:
14099 if (insn[1].imm == 0)
14100 break;
14101 fallthrough;
14102 default:
14103 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
14104 return -EINVAL;
14105 }
14106
387544bf
AS
14107 switch (insn[0].src_reg) {
14108 case BPF_PSEUDO_MAP_IDX_VALUE:
14109 case BPF_PSEUDO_MAP_IDX:
14110 if (bpfptr_is_null(env->fd_array)) {
14111 verbose(env, "fd_idx without fd_array is invalid\n");
14112 return -EPROTO;
14113 }
14114 if (copy_from_bpfptr_offset(&fd, env->fd_array,
14115 insn[0].imm * sizeof(fd),
14116 sizeof(fd)))
14117 return -EFAULT;
14118 break;
14119 default:
14120 fd = insn[0].imm;
14121 break;
14122 }
14123
14124 f = fdget(fd);
c2101297 14125 map = __bpf_map_get(f);
0246e64d 14126 if (IS_ERR(map)) {
61bd5218 14127 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 14128 insn[0].imm);
0246e64d
AS
14129 return PTR_ERR(map);
14130 }
14131
61bd5218 14132 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
14133 if (err) {
14134 fdput(f);
14135 return err;
14136 }
14137
d8eca5bb 14138 aux = &env->insn_aux_data[i];
387544bf
AS
14139 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
14140 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
d8eca5bb
DB
14141 addr = (unsigned long)map;
14142 } else {
14143 u32 off = insn[1].imm;
14144
14145 if (off >= BPF_MAX_VAR_OFF) {
14146 verbose(env, "direct value offset of %u is not allowed\n", off);
14147 fdput(f);
14148 return -EINVAL;
14149 }
14150
14151 if (!map->ops->map_direct_value_addr) {
14152 verbose(env, "no direct value access support for this map type\n");
14153 fdput(f);
14154 return -EINVAL;
14155 }
14156
14157 err = map->ops->map_direct_value_addr(map, &addr, off);
14158 if (err) {
14159 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
14160 map->value_size, off);
14161 fdput(f);
14162 return err;
14163 }
14164
14165 aux->map_off = off;
14166 addr += off;
14167 }
14168
14169 insn[0].imm = (u32)addr;
14170 insn[1].imm = addr >> 32;
0246e64d
AS
14171
14172 /* check whether we recorded this map already */
d8eca5bb 14173 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 14174 if (env->used_maps[j] == map) {
d8eca5bb 14175 aux->map_index = j;
0246e64d
AS
14176 fdput(f);
14177 goto next_insn;
14178 }
d8eca5bb 14179 }
0246e64d
AS
14180
14181 if (env->used_map_cnt >= MAX_USED_MAPS) {
14182 fdput(f);
14183 return -E2BIG;
14184 }
14185
0246e64d
AS
14186 /* hold the map. If the program is rejected by verifier,
14187 * the map will be released by release_maps() or it
14188 * will be used by the valid program until it's unloaded
ab7f5bf0 14189 * and all maps are released in free_used_maps()
0246e64d 14190 */
1e0bd5a0 14191 bpf_map_inc(map);
d8eca5bb
DB
14192
14193 aux->map_index = env->used_map_cnt;
92117d84
AS
14194 env->used_maps[env->used_map_cnt++] = map;
14195
b741f163 14196 if (bpf_map_is_cgroup_storage(map) &&
e4730423 14197 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 14198 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
14199 fdput(f);
14200 return -EBUSY;
14201 }
14202
0246e64d
AS
14203 fdput(f);
14204next_insn:
14205 insn++;
14206 i++;
5e581dad
DB
14207 continue;
14208 }
14209
14210 /* Basic sanity check before we invest more work here. */
14211 if (!bpf_opcode_in_insntable(insn->code)) {
14212 verbose(env, "unknown opcode %02x\n", insn->code);
14213 return -EINVAL;
0246e64d
AS
14214 }
14215 }
14216
14217 /* now all pseudo BPF_LD_IMM64 instructions load valid
14218 * 'struct bpf_map *' into a register instead of user map_fd.
14219 * These pointers will be used later by verifier to validate map access.
14220 */
14221 return 0;
14222}
14223
14224/* drop refcnt of maps used by the rejected program */
58e2af8b 14225static void release_maps(struct bpf_verifier_env *env)
0246e64d 14226{
a2ea0746
DB
14227 __bpf_free_used_maps(env->prog->aux, env->used_maps,
14228 env->used_map_cnt);
0246e64d
AS
14229}
14230
541c3bad
AN
14231/* drop refcnt of maps used by the rejected program */
14232static void release_btfs(struct bpf_verifier_env *env)
14233{
14234 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
14235 env->used_btf_cnt);
14236}
14237
0246e64d 14238/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 14239static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
14240{
14241 struct bpf_insn *insn = env->prog->insnsi;
14242 int insn_cnt = env->prog->len;
14243 int i;
14244
69c087ba
YS
14245 for (i = 0; i < insn_cnt; i++, insn++) {
14246 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
14247 continue;
14248 if (insn->src_reg == BPF_PSEUDO_FUNC)
14249 continue;
14250 insn->src_reg = 0;
14251 }
0246e64d
AS
14252}
14253
8041902d
AS
14254/* single env->prog->insni[off] instruction was replaced with the range
14255 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
14256 * [0, off) and [off, end) to new locations, so the patched range stays zero
14257 */
75f0fc7b
HF
14258static void adjust_insn_aux_data(struct bpf_verifier_env *env,
14259 struct bpf_insn_aux_data *new_data,
14260 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d 14261{
75f0fc7b 14262 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
b325fbca 14263 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 14264 u32 old_seen = old_data[off].seen;
b325fbca 14265 u32 prog_len;
c131187d 14266 int i;
8041902d 14267
b325fbca
JW
14268 /* aux info at OFF always needs adjustment, no matter fast path
14269 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
14270 * original insn at old prog.
14271 */
14272 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
14273
8041902d 14274 if (cnt == 1)
75f0fc7b 14275 return;
b325fbca 14276 prog_len = new_prog->len;
75f0fc7b 14277
8041902d
AS
14278 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
14279 memcpy(new_data + off + cnt - 1, old_data + off,
14280 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 14281 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
14282 /* Expand insni[off]'s seen count to the patched range. */
14283 new_data[i].seen = old_seen;
b325fbca
JW
14284 new_data[i].zext_dst = insn_has_def32(env, insn + i);
14285 }
8041902d
AS
14286 env->insn_aux_data = new_data;
14287 vfree(old_data);
8041902d
AS
14288}
14289
cc8b0b92
AS
14290static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
14291{
14292 int i;
14293
14294 if (len == 1)
14295 return;
4cb3d99c
JW
14296 /* NOTE: fake 'exit' subprog should be updated as well. */
14297 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 14298 if (env->subprog_info[i].start <= off)
cc8b0b92 14299 continue;
9c8105bd 14300 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
14301 }
14302}
14303
7506d211 14304static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
a748c697
MF
14305{
14306 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
14307 int i, sz = prog->aux->size_poke_tab;
14308 struct bpf_jit_poke_descriptor *desc;
14309
14310 for (i = 0; i < sz; i++) {
14311 desc = &tab[i];
7506d211
JF
14312 if (desc->insn_idx <= off)
14313 continue;
a748c697
MF
14314 desc->insn_idx += len - 1;
14315 }
14316}
14317
8041902d
AS
14318static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
14319 const struct bpf_insn *patch, u32 len)
14320{
14321 struct bpf_prog *new_prog;
75f0fc7b
HF
14322 struct bpf_insn_aux_data *new_data = NULL;
14323
14324 if (len > 1) {
14325 new_data = vzalloc(array_size(env->prog->len + len - 1,
14326 sizeof(struct bpf_insn_aux_data)));
14327 if (!new_data)
14328 return NULL;
14329 }
8041902d
AS
14330
14331 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
14332 if (IS_ERR(new_prog)) {
14333 if (PTR_ERR(new_prog) == -ERANGE)
14334 verbose(env,
14335 "insn %d cannot be patched due to 16-bit range\n",
14336 env->insn_aux_data[off].orig_idx);
75f0fc7b 14337 vfree(new_data);
8041902d 14338 return NULL;
4f73379e 14339 }
75f0fc7b 14340 adjust_insn_aux_data(env, new_data, new_prog, off, len);
cc8b0b92 14341 adjust_subprog_starts(env, off, len);
7506d211 14342 adjust_poke_descs(new_prog, off, len);
8041902d
AS
14343 return new_prog;
14344}
14345
52875a04
JK
14346static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
14347 u32 off, u32 cnt)
14348{
14349 int i, j;
14350
14351 /* find first prog starting at or after off (first to remove) */
14352 for (i = 0; i < env->subprog_cnt; i++)
14353 if (env->subprog_info[i].start >= off)
14354 break;
14355 /* find first prog starting at or after off + cnt (first to stay) */
14356 for (j = i; j < env->subprog_cnt; j++)
14357 if (env->subprog_info[j].start >= off + cnt)
14358 break;
14359 /* if j doesn't start exactly at off + cnt, we are just removing
14360 * the front of previous prog
14361 */
14362 if (env->subprog_info[j].start != off + cnt)
14363 j--;
14364
14365 if (j > i) {
14366 struct bpf_prog_aux *aux = env->prog->aux;
14367 int move;
14368
14369 /* move fake 'exit' subprog as well */
14370 move = env->subprog_cnt + 1 - j;
14371
14372 memmove(env->subprog_info + i,
14373 env->subprog_info + j,
14374 sizeof(*env->subprog_info) * move);
14375 env->subprog_cnt -= j - i;
14376
14377 /* remove func_info */
14378 if (aux->func_info) {
14379 move = aux->func_info_cnt - j;
14380
14381 memmove(aux->func_info + i,
14382 aux->func_info + j,
14383 sizeof(*aux->func_info) * move);
14384 aux->func_info_cnt -= j - i;
14385 /* func_info->insn_off is set after all code rewrites,
14386 * in adjust_btf_func() - no need to adjust
14387 */
14388 }
14389 } else {
14390 /* convert i from "first prog to remove" to "first to adjust" */
14391 if (env->subprog_info[i].start == off)
14392 i++;
14393 }
14394
14395 /* update fake 'exit' subprog as well */
14396 for (; i <= env->subprog_cnt; i++)
14397 env->subprog_info[i].start -= cnt;
14398
14399 return 0;
14400}
14401
14402static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
14403 u32 cnt)
14404{
14405 struct bpf_prog *prog = env->prog;
14406 u32 i, l_off, l_cnt, nr_linfo;
14407 struct bpf_line_info *linfo;
14408
14409 nr_linfo = prog->aux->nr_linfo;
14410 if (!nr_linfo)
14411 return 0;
14412
14413 linfo = prog->aux->linfo;
14414
14415 /* find first line info to remove, count lines to be removed */
14416 for (i = 0; i < nr_linfo; i++)
14417 if (linfo[i].insn_off >= off)
14418 break;
14419
14420 l_off = i;
14421 l_cnt = 0;
14422 for (; i < nr_linfo; i++)
14423 if (linfo[i].insn_off < off + cnt)
14424 l_cnt++;
14425 else
14426 break;
14427
14428 /* First live insn doesn't match first live linfo, it needs to "inherit"
14429 * last removed linfo. prog is already modified, so prog->len == off
14430 * means no live instructions after (tail of the program was removed).
14431 */
14432 if (prog->len != off && l_cnt &&
14433 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
14434 l_cnt--;
14435 linfo[--i].insn_off = off + cnt;
14436 }
14437
14438 /* remove the line info which refer to the removed instructions */
14439 if (l_cnt) {
14440 memmove(linfo + l_off, linfo + i,
14441 sizeof(*linfo) * (nr_linfo - i));
14442
14443 prog->aux->nr_linfo -= l_cnt;
14444 nr_linfo = prog->aux->nr_linfo;
14445 }
14446
14447 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
14448 for (i = l_off; i < nr_linfo; i++)
14449 linfo[i].insn_off -= cnt;
14450
14451 /* fix up all subprogs (incl. 'exit') which start >= off */
14452 for (i = 0; i <= env->subprog_cnt; i++)
14453 if (env->subprog_info[i].linfo_idx > l_off) {
14454 /* program may have started in the removed region but
14455 * may not be fully removed
14456 */
14457 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
14458 env->subprog_info[i].linfo_idx -= l_cnt;
14459 else
14460 env->subprog_info[i].linfo_idx = l_off;
14461 }
14462
14463 return 0;
14464}
14465
14466static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
14467{
14468 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14469 unsigned int orig_prog_len = env->prog->len;
14470 int err;
14471
08ca90af
JK
14472 if (bpf_prog_is_dev_bound(env->prog->aux))
14473 bpf_prog_offload_remove_insns(env, off, cnt);
14474
52875a04
JK
14475 err = bpf_remove_insns(env->prog, off, cnt);
14476 if (err)
14477 return err;
14478
14479 err = adjust_subprog_starts_after_remove(env, off, cnt);
14480 if (err)
14481 return err;
14482
14483 err = bpf_adj_linfo_after_remove(env, off, cnt);
14484 if (err)
14485 return err;
14486
14487 memmove(aux_data + off, aux_data + off + cnt,
14488 sizeof(*aux_data) * (orig_prog_len - off - cnt));
14489
14490 return 0;
14491}
14492
2a5418a1
DB
14493/* The verifier does more data flow analysis than llvm and will not
14494 * explore branches that are dead at run time. Malicious programs can
14495 * have dead code too. Therefore replace all dead at-run-time code
14496 * with 'ja -1'.
14497 *
14498 * Just nops are not optimal, e.g. if they would sit at the end of the
14499 * program and through another bug we would manage to jump there, then
14500 * we'd execute beyond program memory otherwise. Returning exception
14501 * code also wouldn't work since we can have subprogs where the dead
14502 * code could be located.
c131187d
AS
14503 */
14504static void sanitize_dead_code(struct bpf_verifier_env *env)
14505{
14506 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 14507 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
14508 struct bpf_insn *insn = env->prog->insnsi;
14509 const int insn_cnt = env->prog->len;
14510 int i;
14511
14512 for (i = 0; i < insn_cnt; i++) {
14513 if (aux_data[i].seen)
14514 continue;
2a5418a1 14515 memcpy(insn + i, &trap, sizeof(trap));
45c709f8 14516 aux_data[i].zext_dst = false;
c131187d
AS
14517 }
14518}
14519
e2ae4ca2
JK
14520static bool insn_is_cond_jump(u8 code)
14521{
14522 u8 op;
14523
092ed096
JW
14524 if (BPF_CLASS(code) == BPF_JMP32)
14525 return true;
14526
e2ae4ca2
JK
14527 if (BPF_CLASS(code) != BPF_JMP)
14528 return false;
14529
14530 op = BPF_OP(code);
14531 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
14532}
14533
14534static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
14535{
14536 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14537 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14538 struct bpf_insn *insn = env->prog->insnsi;
14539 const int insn_cnt = env->prog->len;
14540 int i;
14541
14542 for (i = 0; i < insn_cnt; i++, insn++) {
14543 if (!insn_is_cond_jump(insn->code))
14544 continue;
14545
14546 if (!aux_data[i + 1].seen)
14547 ja.off = insn->off;
14548 else if (!aux_data[i + 1 + insn->off].seen)
14549 ja.off = 0;
14550 else
14551 continue;
14552
08ca90af
JK
14553 if (bpf_prog_is_dev_bound(env->prog->aux))
14554 bpf_prog_offload_replace_insn(env, i, &ja);
14555
e2ae4ca2
JK
14556 memcpy(insn, &ja, sizeof(ja));
14557 }
14558}
14559
52875a04
JK
14560static int opt_remove_dead_code(struct bpf_verifier_env *env)
14561{
14562 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
14563 int insn_cnt = env->prog->len;
14564 int i, err;
14565
14566 for (i = 0; i < insn_cnt; i++) {
14567 int j;
14568
14569 j = 0;
14570 while (i + j < insn_cnt && !aux_data[i + j].seen)
14571 j++;
14572 if (!j)
14573 continue;
14574
14575 err = verifier_remove_insns(env, i, j);
14576 if (err)
14577 return err;
14578 insn_cnt = env->prog->len;
14579 }
14580
14581 return 0;
14582}
14583
a1b14abc
JK
14584static int opt_remove_nops(struct bpf_verifier_env *env)
14585{
14586 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
14587 struct bpf_insn *insn = env->prog->insnsi;
14588 int insn_cnt = env->prog->len;
14589 int i, err;
14590
14591 for (i = 0; i < insn_cnt; i++) {
14592 if (memcmp(&insn[i], &ja, sizeof(ja)))
14593 continue;
14594
14595 err = verifier_remove_insns(env, i, 1);
14596 if (err)
14597 return err;
14598 insn_cnt--;
14599 i--;
14600 }
14601
14602 return 0;
14603}
14604
d6c2308c
JW
14605static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
14606 const union bpf_attr *attr)
a4b1d3c1 14607{
d6c2308c 14608 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 14609 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 14610 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 14611 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 14612 struct bpf_prog *new_prog;
d6c2308c 14613 bool rnd_hi32;
a4b1d3c1 14614
d6c2308c 14615 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 14616 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
14617 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
14618 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
14619 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
14620 for (i = 0; i < len; i++) {
14621 int adj_idx = i + delta;
14622 struct bpf_insn insn;
83a28819 14623 int load_reg;
a4b1d3c1 14624
d6c2308c 14625 insn = insns[adj_idx];
83a28819 14626 load_reg = insn_def_regno(&insn);
d6c2308c
JW
14627 if (!aux[adj_idx].zext_dst) {
14628 u8 code, class;
14629 u32 imm_rnd;
14630
14631 if (!rnd_hi32)
14632 continue;
14633
14634 code = insn.code;
14635 class = BPF_CLASS(code);
83a28819 14636 if (load_reg == -1)
d6c2308c
JW
14637 continue;
14638
14639 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
14640 * BPF_STX + SRC_OP, so it is safe to pass NULL
14641 * here.
d6c2308c 14642 */
83a28819 14643 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
14644 if (class == BPF_LD &&
14645 BPF_MODE(code) == BPF_IMM)
14646 i++;
14647 continue;
14648 }
14649
14650 /* ctx load could be transformed into wider load. */
14651 if (class == BPF_LDX &&
14652 aux[adj_idx].ptr_type == PTR_TO_CTX)
14653 continue;
14654
a251c17a 14655 imm_rnd = get_random_u32();
d6c2308c
JW
14656 rnd_hi32_patch[0] = insn;
14657 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 14658 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
14659 patch = rnd_hi32_patch;
14660 patch_len = 4;
14661 goto apply_patch_buffer;
14662 }
14663
39491867
BJ
14664 /* Add in an zero-extend instruction if a) the JIT has requested
14665 * it or b) it's a CMPXCHG.
14666 *
14667 * The latter is because: BPF_CMPXCHG always loads a value into
14668 * R0, therefore always zero-extends. However some archs'
14669 * equivalent instruction only does this load when the
14670 * comparison is successful. This detail of CMPXCHG is
14671 * orthogonal to the general zero-extension behaviour of the
14672 * CPU, so it's treated independently of bpf_jit_needs_zext.
14673 */
14674 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
14675 continue;
14676
83a28819
IL
14677 if (WARN_ON(load_reg == -1)) {
14678 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
14679 return -EFAULT;
b2e37a71
IL
14680 }
14681
a4b1d3c1 14682 zext_patch[0] = insn;
b2e37a71
IL
14683 zext_patch[1].dst_reg = load_reg;
14684 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
14685 patch = zext_patch;
14686 patch_len = 2;
14687apply_patch_buffer:
14688 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
14689 if (!new_prog)
14690 return -ENOMEM;
14691 env->prog = new_prog;
14692 insns = new_prog->insnsi;
14693 aux = env->insn_aux_data;
d6c2308c 14694 delta += patch_len - 1;
a4b1d3c1
JW
14695 }
14696
14697 return 0;
14698}
14699
c64b7983
JS
14700/* convert load instructions that access fields of a context type into a
14701 * sequence of instructions that access fields of the underlying structure:
14702 * struct __sk_buff -> struct sk_buff
14703 * struct bpf_sock_ops -> struct sock
9bac3d6d 14704 */
58e2af8b 14705static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 14706{
00176a34 14707 const struct bpf_verifier_ops *ops = env->ops;
f96da094 14708 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 14709 const int insn_cnt = env->prog->len;
36bbef52 14710 struct bpf_insn insn_buf[16], *insn;
46f53a65 14711 u32 target_size, size_default, off;
9bac3d6d 14712 struct bpf_prog *new_prog;
d691f9e8 14713 enum bpf_access_type type;
f96da094 14714 bool is_narrower_load;
9bac3d6d 14715
b09928b9
DB
14716 if (ops->gen_prologue || env->seen_direct_write) {
14717 if (!ops->gen_prologue) {
14718 verbose(env, "bpf verifier is misconfigured\n");
14719 return -EINVAL;
14720 }
36bbef52
DB
14721 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
14722 env->prog);
14723 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 14724 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
14725 return -EINVAL;
14726 } else if (cnt) {
8041902d 14727 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
14728 if (!new_prog)
14729 return -ENOMEM;
8041902d 14730
36bbef52 14731 env->prog = new_prog;
3df126f3 14732 delta += cnt - 1;
36bbef52
DB
14733 }
14734 }
14735
c64b7983 14736 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
14737 return 0;
14738
3df126f3 14739 insn = env->prog->insnsi + delta;
36bbef52 14740
9bac3d6d 14741 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983 14742 bpf_convert_ctx_access_t convert_ctx_access;
2039f26f 14743 bool ctx_access;
c64b7983 14744
62c7989b
DB
14745 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
14746 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
14747 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
2039f26f 14748 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
d691f9e8 14749 type = BPF_READ;
2039f26f
DB
14750 ctx_access = true;
14751 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
14752 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
14753 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
14754 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
14755 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
14756 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
14757 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
14758 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
d691f9e8 14759 type = BPF_WRITE;
2039f26f
DB
14760 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
14761 } else {
9bac3d6d 14762 continue;
2039f26f 14763 }
9bac3d6d 14764
af86ca4e 14765 if (type == BPF_WRITE &&
2039f26f 14766 env->insn_aux_data[i + delta].sanitize_stack_spill) {
af86ca4e 14767 struct bpf_insn patch[] = {
af86ca4e 14768 *insn,
2039f26f 14769 BPF_ST_NOSPEC(),
af86ca4e
AS
14770 };
14771
14772 cnt = ARRAY_SIZE(patch);
14773 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
14774 if (!new_prog)
14775 return -ENOMEM;
14776
14777 delta += cnt - 1;
14778 env->prog = new_prog;
14779 insn = new_prog->insnsi + i + delta;
14780 continue;
14781 }
14782
2039f26f
DB
14783 if (!ctx_access)
14784 continue;
14785
6efe152d 14786 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
c64b7983
JS
14787 case PTR_TO_CTX:
14788 if (!ops->convert_ctx_access)
14789 continue;
14790 convert_ctx_access = ops->convert_ctx_access;
14791 break;
14792 case PTR_TO_SOCKET:
46f8bc92 14793 case PTR_TO_SOCK_COMMON:
c64b7983
JS
14794 convert_ctx_access = bpf_sock_convert_ctx_access;
14795 break;
655a51e5
MKL
14796 case PTR_TO_TCP_SOCK:
14797 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
14798 break;
fada7fdc
JL
14799 case PTR_TO_XDP_SOCK:
14800 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
14801 break;
2a02759e 14802 case PTR_TO_BTF_ID:
6efe152d 14803 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
3f00c523 14804 case PTR_TO_BTF_ID | PTR_TRUSTED:
282de143
KKD
14805 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
14806 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
14807 * be said once it is marked PTR_UNTRUSTED, hence we must handle
14808 * any faults for loads into such types. BPF_WRITE is disallowed
14809 * for this case.
14810 */
14811 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
3f00c523
DV
14812 case PTR_TO_BTF_ID | PTR_UNTRUSTED | PTR_TRUSTED:
14813 case PTR_TO_BTF_ID | PTR_UNTRUSTED | MEM_ALLOC | PTR_TRUSTED:
27ae7997
MKL
14814 if (type == BPF_READ) {
14815 insn->code = BPF_LDX | BPF_PROBE_MEM |
14816 BPF_SIZE((insn)->code);
14817 env->prog->aux->num_exentries++;
2a02759e 14818 }
2a02759e 14819 continue;
c64b7983 14820 default:
9bac3d6d 14821 continue;
c64b7983 14822 }
9bac3d6d 14823
31fd8581 14824 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 14825 size = BPF_LDST_BYTES(insn);
31fd8581
YS
14826
14827 /* If the read access is a narrower load of the field,
14828 * convert to a 4/8-byte load, to minimum program type specific
14829 * convert_ctx_access changes. If conversion is successful,
14830 * we will apply proper mask to the result.
14831 */
f96da094 14832 is_narrower_load = size < ctx_field_size;
46f53a65
AI
14833 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
14834 off = insn->off;
31fd8581 14835 if (is_narrower_load) {
f96da094
DB
14836 u8 size_code;
14837
14838 if (type == BPF_WRITE) {
61bd5218 14839 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
14840 return -EINVAL;
14841 }
31fd8581 14842
f96da094 14843 size_code = BPF_H;
31fd8581
YS
14844 if (ctx_field_size == 4)
14845 size_code = BPF_W;
14846 else if (ctx_field_size == 8)
14847 size_code = BPF_DW;
f96da094 14848
bc23105c 14849 insn->off = off & ~(size_default - 1);
31fd8581
YS
14850 insn->code = BPF_LDX | BPF_MEM | size_code;
14851 }
f96da094
DB
14852
14853 target_size = 0;
c64b7983
JS
14854 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
14855 &target_size);
f96da094
DB
14856 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
14857 (ctx_field_size && !target_size)) {
61bd5218 14858 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
14859 return -EINVAL;
14860 }
f96da094
DB
14861
14862 if (is_narrower_load && size < target_size) {
d895a0f1
IL
14863 u8 shift = bpf_ctx_narrow_access_offset(
14864 off, size, size_default) * 8;
d7af7e49
AI
14865 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
14866 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
14867 return -EINVAL;
14868 }
46f53a65
AI
14869 if (ctx_field_size <= 4) {
14870 if (shift)
14871 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
14872 insn->dst_reg,
14873 shift);
31fd8581 14874 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 14875 (1 << size * 8) - 1);
46f53a65
AI
14876 } else {
14877 if (shift)
14878 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
14879 insn->dst_reg,
14880 shift);
31fd8581 14881 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 14882 (1ULL << size * 8) - 1);
46f53a65 14883 }
31fd8581 14884 }
9bac3d6d 14885
8041902d 14886 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
14887 if (!new_prog)
14888 return -ENOMEM;
14889
3df126f3 14890 delta += cnt - 1;
9bac3d6d
AS
14891
14892 /* keep walking new program and skip insns we just inserted */
14893 env->prog = new_prog;
3df126f3 14894 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
14895 }
14896
14897 return 0;
14898}
14899
1c2a088a
AS
14900static int jit_subprogs(struct bpf_verifier_env *env)
14901{
14902 struct bpf_prog *prog = env->prog, **func, *tmp;
14903 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 14904 struct bpf_map *map_ptr;
7105e828 14905 struct bpf_insn *insn;
1c2a088a 14906 void *old_bpf_func;
c4c0bdc0 14907 int err, num_exentries;
1c2a088a 14908
f910cefa 14909 if (env->subprog_cnt <= 1)
1c2a088a
AS
14910 return 0;
14911
7105e828 14912 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
3990ed4c 14913 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
69c087ba 14914 continue;
69c087ba 14915
c7a89784
DB
14916 /* Upon error here we cannot fall back to interpreter but
14917 * need a hard reject of the program. Thus -EFAULT is
14918 * propagated in any case.
14919 */
1c2a088a
AS
14920 subprog = find_subprog(env, i + insn->imm + 1);
14921 if (subprog < 0) {
14922 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
14923 i + insn->imm + 1);
14924 return -EFAULT;
14925 }
14926 /* temporarily remember subprog id inside insn instead of
14927 * aux_data, since next loop will split up all insns into funcs
14928 */
f910cefa 14929 insn->off = subprog;
1c2a088a
AS
14930 /* remember original imm in case JIT fails and fallback
14931 * to interpreter will be needed
14932 */
14933 env->insn_aux_data[i].call_imm = insn->imm;
14934 /* point imm to __bpf_call_base+1 from JITs point of view */
14935 insn->imm = 1;
3990ed4c
MKL
14936 if (bpf_pseudo_func(insn))
14937 /* jit (e.g. x86_64) may emit fewer instructions
14938 * if it learns a u32 imm is the same as a u64 imm.
14939 * Force a non zero here.
14940 */
14941 insn[1].imm = 1;
1c2a088a
AS
14942 }
14943
c454a46b
MKL
14944 err = bpf_prog_alloc_jited_linfo(prog);
14945 if (err)
14946 goto out_undo_insn;
14947
14948 err = -ENOMEM;
6396bb22 14949 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 14950 if (!func)
c7a89784 14951 goto out_undo_insn;
1c2a088a 14952
f910cefa 14953 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 14954 subprog_start = subprog_end;
4cb3d99c 14955 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
14956
14957 len = subprog_end - subprog_start;
fb7dd8bc 14958 /* bpf_prog_run() doesn't call subprogs directly,
492ecee8
AS
14959 * hence main prog stats include the runtime of subprogs.
14960 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 14961 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
14962 */
14963 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
14964 if (!func[i])
14965 goto out_free;
14966 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
14967 len * sizeof(struct bpf_insn));
4f74d809 14968 func[i]->type = prog->type;
1c2a088a 14969 func[i]->len = len;
4f74d809
DB
14970 if (bpf_prog_calc_tag(func[i]))
14971 goto out_free;
1c2a088a 14972 func[i]->is_func = 1;
ba64e7d8 14973 func[i]->aux->func_idx = i;
f263a814 14974 /* Below members will be freed only at prog->aux */
ba64e7d8
YS
14975 func[i]->aux->btf = prog->aux->btf;
14976 func[i]->aux->func_info = prog->aux->func_info;
9c7c48d6 14977 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
f263a814
JF
14978 func[i]->aux->poke_tab = prog->aux->poke_tab;
14979 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
ba64e7d8 14980
a748c697 14981 for (j = 0; j < prog->aux->size_poke_tab; j++) {
f263a814 14982 struct bpf_jit_poke_descriptor *poke;
a748c697 14983
f263a814
JF
14984 poke = &prog->aux->poke_tab[j];
14985 if (poke->insn_idx < subprog_end &&
14986 poke->insn_idx >= subprog_start)
14987 poke->aux = func[i]->aux;
a748c697
MF
14988 }
14989
1c2a088a 14990 func[i]->aux->name[0] = 'F';
9c8105bd 14991 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 14992 func[i]->jit_requested = 1;
d2a3b7c5 14993 func[i]->blinding_requested = prog->blinding_requested;
e6ac2450 14994 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
2357672c 14995 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
c454a46b
MKL
14996 func[i]->aux->linfo = prog->aux->linfo;
14997 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
14998 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
14999 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
15000 num_exentries = 0;
15001 insn = func[i]->insnsi;
15002 for (j = 0; j < func[i]->len; j++, insn++) {
15003 if (BPF_CLASS(insn->code) == BPF_LDX &&
15004 BPF_MODE(insn->code) == BPF_PROBE_MEM)
15005 num_exentries++;
15006 }
15007 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 15008 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
15009 func[i] = bpf_int_jit_compile(func[i]);
15010 if (!func[i]->jited) {
15011 err = -ENOTSUPP;
15012 goto out_free;
15013 }
15014 cond_resched();
15015 }
a748c697 15016
1c2a088a
AS
15017 /* at this point all bpf functions were successfully JITed
15018 * now populate all bpf_calls with correct addresses and
15019 * run last pass of JIT
15020 */
f910cefa 15021 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
15022 insn = func[i]->insnsi;
15023 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba 15024 if (bpf_pseudo_func(insn)) {
3990ed4c 15025 subprog = insn->off;
69c087ba
YS
15026 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
15027 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
15028 continue;
15029 }
23a2d70c 15030 if (!bpf_pseudo_call(insn))
1c2a088a
AS
15031 continue;
15032 subprog = insn->off;
3d717fad 15033 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
1c2a088a 15034 }
2162fed4
SD
15035
15036 /* we use the aux data to keep a list of the start addresses
15037 * of the JITed images for each function in the program
15038 *
15039 * for some architectures, such as powerpc64, the imm field
15040 * might not be large enough to hold the offset of the start
15041 * address of the callee's JITed image from __bpf_call_base
15042 *
15043 * in such cases, we can lookup the start address of a callee
15044 * by using its subprog id, available from the off field of
15045 * the call instruction, as an index for this list
15046 */
15047 func[i]->aux->func = func;
15048 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 15049 }
f910cefa 15050 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
15051 old_bpf_func = func[i]->bpf_func;
15052 tmp = bpf_int_jit_compile(func[i]);
15053 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
15054 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 15055 err = -ENOTSUPP;
1c2a088a
AS
15056 goto out_free;
15057 }
15058 cond_resched();
15059 }
15060
15061 /* finally lock prog and jit images for all functions and
15062 * populate kallsysm
15063 */
f910cefa 15064 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
15065 bpf_prog_lock_ro(func[i]);
15066 bpf_prog_kallsyms_add(func[i]);
15067 }
7105e828
DB
15068
15069 /* Last step: make now unused interpreter insns from main
15070 * prog consistent for later dump requests, so they can
15071 * later look the same as if they were interpreted only.
15072 */
15073 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
15074 if (bpf_pseudo_func(insn)) {
15075 insn[0].imm = env->insn_aux_data[i].call_imm;
3990ed4c
MKL
15076 insn[1].imm = insn->off;
15077 insn->off = 0;
69c087ba
YS
15078 continue;
15079 }
23a2d70c 15080 if (!bpf_pseudo_call(insn))
7105e828
DB
15081 continue;
15082 insn->off = env->insn_aux_data[i].call_imm;
15083 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 15084 insn->imm = subprog;
7105e828
DB
15085 }
15086
1c2a088a
AS
15087 prog->jited = 1;
15088 prog->bpf_func = func[0]->bpf_func;
d00c6473 15089 prog->jited_len = func[0]->jited_len;
1c2a088a 15090 prog->aux->func = func;
f910cefa 15091 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 15092 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
15093 return 0;
15094out_free:
f263a814
JF
15095 /* We failed JIT'ing, so at this point we need to unregister poke
15096 * descriptors from subprogs, so that kernel is not attempting to
15097 * patch it anymore as we're freeing the subprog JIT memory.
15098 */
15099 for (i = 0; i < prog->aux->size_poke_tab; i++) {
15100 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15101 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
15102 }
15103 /* At this point we're guaranteed that poke descriptors are not
15104 * live anymore. We can just unlink its descriptor table as it's
15105 * released with the main prog.
15106 */
a748c697
MF
15107 for (i = 0; i < env->subprog_cnt; i++) {
15108 if (!func[i])
15109 continue;
f263a814 15110 func[i]->aux->poke_tab = NULL;
a748c697
MF
15111 bpf_jit_free(func[i]);
15112 }
1c2a088a 15113 kfree(func);
c7a89784 15114out_undo_insn:
1c2a088a
AS
15115 /* cleanup main prog to be interpreted */
15116 prog->jit_requested = 0;
d2a3b7c5 15117 prog->blinding_requested = 0;
1c2a088a 15118 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 15119 if (!bpf_pseudo_call(insn))
1c2a088a
AS
15120 continue;
15121 insn->off = 0;
15122 insn->imm = env->insn_aux_data[i].call_imm;
15123 }
e16301fb 15124 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
15125 return err;
15126}
15127
1ea47e01
AS
15128static int fixup_call_args(struct bpf_verifier_env *env)
15129{
19d28fbd 15130#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
15131 struct bpf_prog *prog = env->prog;
15132 struct bpf_insn *insn = prog->insnsi;
e6ac2450 15133 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 15134 int i, depth;
19d28fbd 15135#endif
e4052d06 15136 int err = 0;
1ea47e01 15137
e4052d06
QM
15138 if (env->prog->jit_requested &&
15139 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
15140 err = jit_subprogs(env);
15141 if (err == 0)
1c2a088a 15142 return 0;
c7a89784
DB
15143 if (err == -EFAULT)
15144 return err;
19d28fbd
DM
15145 }
15146#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
15147 if (has_kfunc_call) {
15148 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
15149 return -EINVAL;
15150 }
e411901c
MF
15151 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
15152 /* When JIT fails the progs with bpf2bpf calls and tail_calls
15153 * have to be rejected, since interpreter doesn't support them yet.
15154 */
15155 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
15156 return -EINVAL;
15157 }
1ea47e01 15158 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
15159 if (bpf_pseudo_func(insn)) {
15160 /* When JIT fails the progs with callback calls
15161 * have to be rejected, since interpreter doesn't support them yet.
15162 */
15163 verbose(env, "callbacks are not allowed in non-JITed programs\n");
15164 return -EINVAL;
15165 }
15166
23a2d70c 15167 if (!bpf_pseudo_call(insn))
1ea47e01
AS
15168 continue;
15169 depth = get_callee_stack_depth(env, insn, i);
15170 if (depth < 0)
15171 return depth;
15172 bpf_patch_call_args(insn, depth);
15173 }
19d28fbd
DM
15174 err = 0;
15175#endif
15176 return err;
1ea47e01
AS
15177}
15178
958cf2e2
KKD
15179static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15180 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
e6ac2450
MKL
15181{
15182 const struct bpf_kfunc_desc *desc;
15183
a5d82727
KKD
15184 if (!insn->imm) {
15185 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
15186 return -EINVAL;
15187 }
15188
e6ac2450
MKL
15189 /* insn->imm has the btf func_id. Replace it with
15190 * an address (relative to __bpf_base_call).
15191 */
2357672c 15192 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
e6ac2450
MKL
15193 if (!desc) {
15194 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
15195 insn->imm);
15196 return -EFAULT;
15197 }
15198
958cf2e2 15199 *cnt = 0;
e6ac2450 15200 insn->imm = desc->imm;
958cf2e2
KKD
15201 if (insn->off)
15202 return 0;
15203 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
15204 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15205 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15206 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
e6ac2450 15207
958cf2e2
KKD
15208 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
15209 insn_buf[1] = addr[0];
15210 insn_buf[2] = addr[1];
15211 insn_buf[3] = *insn;
15212 *cnt = 4;
ac9f0605
KKD
15213 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
15214 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
15215 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
15216
15217 insn_buf[0] = addr[0];
15218 insn_buf[1] = addr[1];
15219 insn_buf[2] = *insn;
15220 *cnt = 3;
a35b9af4
YS
15221 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
15222 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
fd264ca0
YS
15223 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
15224 *cnt = 1;
958cf2e2 15225 }
e6ac2450
MKL
15226 return 0;
15227}
15228
e6ac5933
BJ
15229/* Do various post-verification rewrites in a single program pass.
15230 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 15231 */
e6ac5933 15232static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 15233{
79741b3b 15234 struct bpf_prog *prog = env->prog;
f92c1e18 15235 enum bpf_attach_type eatype = prog->expected_attach_type;
9b99edca 15236 enum bpf_prog_type prog_type = resolve_prog_type(prog);
79741b3b 15237 struct bpf_insn *insn = prog->insnsi;
e245c5c6 15238 const struct bpf_func_proto *fn;
79741b3b 15239 const int insn_cnt = prog->len;
09772d92 15240 const struct bpf_map_ops *ops;
c93552c4 15241 struct bpf_insn_aux_data *aux;
81ed18ab
AS
15242 struct bpf_insn insn_buf[16];
15243 struct bpf_prog *new_prog;
15244 struct bpf_map *map_ptr;
d2e4c1e6 15245 int i, ret, cnt, delta = 0;
e245c5c6 15246
79741b3b 15247 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 15248 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
15249 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
15250 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
15251 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 15252 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 15253 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
15254 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
15255 struct bpf_insn *patchlet;
15256 struct bpf_insn chk_and_div[] = {
9b00f1b7 15257 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
15258 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15259 BPF_JNE | BPF_K, insn->src_reg,
15260 0, 2, 0),
f6b1b3bf
DB
15261 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
15262 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15263 *insn,
15264 };
e88b2c6e 15265 struct bpf_insn chk_and_mod[] = {
9b00f1b7 15266 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
15267 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
15268 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 15269 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 15270 *insn,
9b00f1b7
DB
15271 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
15272 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 15273 };
f6b1b3bf 15274
e88b2c6e
DB
15275 patchlet = isdiv ? chk_and_div : chk_and_mod;
15276 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 15277 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
15278
15279 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
15280 if (!new_prog)
15281 return -ENOMEM;
15282
15283 delta += cnt - 1;
15284 env->prog = prog = new_prog;
15285 insn = new_prog->insnsi + i + delta;
15286 continue;
15287 }
15288
e6ac5933 15289 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
15290 if (BPF_CLASS(insn->code) == BPF_LD &&
15291 (BPF_MODE(insn->code) == BPF_ABS ||
15292 BPF_MODE(insn->code) == BPF_IND)) {
15293 cnt = env->ops->gen_ld_abs(insn, insn_buf);
15294 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
15295 verbose(env, "bpf verifier is misconfigured\n");
15296 return -EINVAL;
15297 }
15298
15299 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15300 if (!new_prog)
15301 return -ENOMEM;
15302
15303 delta += cnt - 1;
15304 env->prog = prog = new_prog;
15305 insn = new_prog->insnsi + i + delta;
15306 continue;
15307 }
15308
e6ac5933 15309 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
15310 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
15311 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
15312 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
15313 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 15314 struct bpf_insn *patch = &insn_buf[0];
801c6058 15315 bool issrc, isneg, isimm;
979d63d5
DB
15316 u32 off_reg;
15317
15318 aux = &env->insn_aux_data[i + delta];
3612af78
DB
15319 if (!aux->alu_state ||
15320 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
15321 continue;
15322
15323 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
15324 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
15325 BPF_ALU_SANITIZE_SRC;
801c6058 15326 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
15327
15328 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
15329 if (isimm) {
15330 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15331 } else {
15332 if (isneg)
15333 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15334 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
15335 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
15336 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
15337 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
15338 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
15339 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
15340 }
b9b34ddb
DB
15341 if (!issrc)
15342 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
15343 insn->src_reg = BPF_REG_AX;
979d63d5
DB
15344 if (isneg)
15345 insn->code = insn->code == code_add ?
15346 code_sub : code_add;
15347 *patch++ = *insn;
801c6058 15348 if (issrc && isneg && !isimm)
979d63d5
DB
15349 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
15350 cnt = patch - insn_buf;
15351
15352 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15353 if (!new_prog)
15354 return -ENOMEM;
15355
15356 delta += cnt - 1;
15357 env->prog = prog = new_prog;
15358 insn = new_prog->insnsi + i + delta;
15359 continue;
15360 }
15361
79741b3b
AS
15362 if (insn->code != (BPF_JMP | BPF_CALL))
15363 continue;
cc8b0b92
AS
15364 if (insn->src_reg == BPF_PSEUDO_CALL)
15365 continue;
e6ac2450 15366 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
958cf2e2 15367 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
e6ac2450
MKL
15368 if (ret)
15369 return ret;
958cf2e2
KKD
15370 if (cnt == 0)
15371 continue;
15372
15373 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15374 if (!new_prog)
15375 return -ENOMEM;
15376
15377 delta += cnt - 1;
15378 env->prog = prog = new_prog;
15379 insn = new_prog->insnsi + i + delta;
e6ac2450
MKL
15380 continue;
15381 }
e245c5c6 15382
79741b3b
AS
15383 if (insn->imm == BPF_FUNC_get_route_realm)
15384 prog->dst_needed = 1;
15385 if (insn->imm == BPF_FUNC_get_prandom_u32)
15386 bpf_user_rnd_init_once();
9802d865
JB
15387 if (insn->imm == BPF_FUNC_override_return)
15388 prog->kprobe_override = 1;
79741b3b 15389 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
15390 /* If we tail call into other programs, we
15391 * cannot make any assumptions since they can
15392 * be replaced dynamically during runtime in
15393 * the program array.
15394 */
15395 prog->cb_access = 1;
e411901c
MF
15396 if (!allow_tail_call_in_subprogs(env))
15397 prog->aux->stack_depth = MAX_BPF_STACK;
15398 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 15399
79741b3b 15400 /* mark bpf_tail_call as different opcode to avoid
8fb33b60 15401 * conditional branch in the interpreter for every normal
79741b3b
AS
15402 * call and to prevent accidental JITing by JIT compiler
15403 * that doesn't support bpf_tail_call yet
e245c5c6 15404 */
79741b3b 15405 insn->imm = 0;
71189fa9 15406 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 15407
c93552c4 15408 aux = &env->insn_aux_data[i + delta];
d2a3b7c5 15409 if (env->bpf_capable && !prog->blinding_requested &&
cc52d914 15410 prog->jit_requested &&
d2e4c1e6
DB
15411 !bpf_map_key_poisoned(aux) &&
15412 !bpf_map_ptr_poisoned(aux) &&
15413 !bpf_map_ptr_unpriv(aux)) {
15414 struct bpf_jit_poke_descriptor desc = {
15415 .reason = BPF_POKE_REASON_TAIL_CALL,
15416 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
15417 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 15418 .insn_idx = i + delta,
d2e4c1e6
DB
15419 };
15420
15421 ret = bpf_jit_add_poke_descriptor(prog, &desc);
15422 if (ret < 0) {
15423 verbose(env, "adding tail call poke descriptor failed\n");
15424 return ret;
15425 }
15426
15427 insn->imm = ret + 1;
15428 continue;
15429 }
15430
c93552c4
DB
15431 if (!bpf_map_ptr_unpriv(aux))
15432 continue;
15433
b2157399
AS
15434 /* instead of changing every JIT dealing with tail_call
15435 * emit two extra insns:
15436 * if (index >= max_entries) goto out;
15437 * index &= array->index_mask;
15438 * to avoid out-of-bounds cpu speculation
15439 */
c93552c4 15440 if (bpf_map_ptr_poisoned(aux)) {
40950343 15441 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
15442 return -EINVAL;
15443 }
c93552c4 15444
d2e4c1e6 15445 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
15446 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
15447 map_ptr->max_entries, 2);
15448 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
15449 container_of(map_ptr,
15450 struct bpf_array,
15451 map)->index_mask);
15452 insn_buf[2] = *insn;
15453 cnt = 3;
15454 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15455 if (!new_prog)
15456 return -ENOMEM;
15457
15458 delta += cnt - 1;
15459 env->prog = prog = new_prog;
15460 insn = new_prog->insnsi + i + delta;
79741b3b
AS
15461 continue;
15462 }
e245c5c6 15463
b00628b1
AS
15464 if (insn->imm == BPF_FUNC_timer_set_callback) {
15465 /* The verifier will process callback_fn as many times as necessary
15466 * with different maps and the register states prepared by
15467 * set_timer_callback_state will be accurate.
15468 *
15469 * The following use case is valid:
15470 * map1 is shared by prog1, prog2, prog3.
15471 * prog1 calls bpf_timer_init for some map1 elements
15472 * prog2 calls bpf_timer_set_callback for some map1 elements.
15473 * Those that were not bpf_timer_init-ed will return -EINVAL.
15474 * prog3 calls bpf_timer_start for some map1 elements.
15475 * Those that were not both bpf_timer_init-ed and
15476 * bpf_timer_set_callback-ed will return -EINVAL.
15477 */
15478 struct bpf_insn ld_addrs[2] = {
15479 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
15480 };
15481
15482 insn_buf[0] = ld_addrs[0];
15483 insn_buf[1] = ld_addrs[1];
15484 insn_buf[2] = *insn;
15485 cnt = 3;
15486
15487 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15488 if (!new_prog)
15489 return -ENOMEM;
15490
15491 delta += cnt - 1;
15492 env->prog = prog = new_prog;
15493 insn = new_prog->insnsi + i + delta;
15494 goto patch_call_imm;
15495 }
15496
b00fa38a
JK
15497 if (insn->imm == BPF_FUNC_task_storage_get ||
15498 insn->imm == BPF_FUNC_sk_storage_get ||
c4bcfb38
YS
15499 insn->imm == BPF_FUNC_inode_storage_get ||
15500 insn->imm == BPF_FUNC_cgrp_storage_get) {
b00fa38a 15501 if (env->prog->aux->sleepable)
d56c9fe6 15502 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
b00fa38a 15503 else
d56c9fe6 15504 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
b00fa38a
JK
15505 insn_buf[1] = *insn;
15506 cnt = 2;
15507
15508 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15509 if (!new_prog)
15510 return -ENOMEM;
15511
15512 delta += cnt - 1;
15513 env->prog = prog = new_prog;
15514 insn = new_prog->insnsi + i + delta;
15515 goto patch_call_imm;
15516 }
15517
89c63074 15518 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
15519 * and other inlining handlers are currently limited to 64 bit
15520 * only.
89c63074 15521 */
60b58afc 15522 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
15523 (insn->imm == BPF_FUNC_map_lookup_elem ||
15524 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
15525 insn->imm == BPF_FUNC_map_delete_elem ||
15526 insn->imm == BPF_FUNC_map_push_elem ||
15527 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f 15528 insn->imm == BPF_FUNC_map_peek_elem ||
0640c77c 15529 insn->imm == BPF_FUNC_redirect_map ||
07343110
FZ
15530 insn->imm == BPF_FUNC_for_each_map_elem ||
15531 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
c93552c4
DB
15532 aux = &env->insn_aux_data[i + delta];
15533 if (bpf_map_ptr_poisoned(aux))
15534 goto patch_call_imm;
15535
d2e4c1e6 15536 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
15537 ops = map_ptr->ops;
15538 if (insn->imm == BPF_FUNC_map_lookup_elem &&
15539 ops->map_gen_lookup) {
15540 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
15541 if (cnt == -EOPNOTSUPP)
15542 goto patch_map_ops_generic;
15543 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
15544 verbose(env, "bpf verifier is misconfigured\n");
15545 return -EINVAL;
15546 }
81ed18ab 15547
09772d92
DB
15548 new_prog = bpf_patch_insn_data(env, i + delta,
15549 insn_buf, cnt);
15550 if (!new_prog)
15551 return -ENOMEM;
81ed18ab 15552
09772d92
DB
15553 delta += cnt - 1;
15554 env->prog = prog = new_prog;
15555 insn = new_prog->insnsi + i + delta;
15556 continue;
15557 }
81ed18ab 15558
09772d92
DB
15559 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
15560 (void *(*)(struct bpf_map *map, void *key))NULL));
15561 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
15562 (int (*)(struct bpf_map *map, void *key))NULL));
15563 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
15564 (int (*)(struct bpf_map *map, void *key, void *value,
15565 u64 flags))NULL));
84430d42
DB
15566 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
15567 (int (*)(struct bpf_map *map, void *value,
15568 u64 flags))NULL));
15569 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
15570 (int (*)(struct bpf_map *map, void *value))NULL));
15571 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
15572 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f 15573 BUILD_BUG_ON(!__same_type(ops->map_redirect,
32637e33 15574 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
0640c77c
AI
15575 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
15576 (int (*)(struct bpf_map *map,
15577 bpf_callback_t callback_fn,
15578 void *callback_ctx,
15579 u64 flags))NULL));
07343110
FZ
15580 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
15581 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
e6a4750f 15582
4a8f87e6 15583patch_map_ops_generic:
09772d92
DB
15584 switch (insn->imm) {
15585 case BPF_FUNC_map_lookup_elem:
3d717fad 15586 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
09772d92
DB
15587 continue;
15588 case BPF_FUNC_map_update_elem:
3d717fad 15589 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
09772d92
DB
15590 continue;
15591 case BPF_FUNC_map_delete_elem:
3d717fad 15592 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
09772d92 15593 continue;
84430d42 15594 case BPF_FUNC_map_push_elem:
3d717fad 15595 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
84430d42
DB
15596 continue;
15597 case BPF_FUNC_map_pop_elem:
3d717fad 15598 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
84430d42
DB
15599 continue;
15600 case BPF_FUNC_map_peek_elem:
3d717fad 15601 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
84430d42 15602 continue;
e6a4750f 15603 case BPF_FUNC_redirect_map:
3d717fad 15604 insn->imm = BPF_CALL_IMM(ops->map_redirect);
e6a4750f 15605 continue;
0640c77c
AI
15606 case BPF_FUNC_for_each_map_elem:
15607 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
e6a4750f 15608 continue;
07343110
FZ
15609 case BPF_FUNC_map_lookup_percpu_elem:
15610 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
15611 continue;
09772d92 15612 }
81ed18ab 15613
09772d92 15614 goto patch_call_imm;
81ed18ab
AS
15615 }
15616
e6ac5933 15617 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
15618 if (prog->jit_requested && BITS_PER_LONG == 64 &&
15619 insn->imm == BPF_FUNC_jiffies64) {
15620 struct bpf_insn ld_jiffies_addr[2] = {
15621 BPF_LD_IMM64(BPF_REG_0,
15622 (unsigned long)&jiffies),
15623 };
15624
15625 insn_buf[0] = ld_jiffies_addr[0];
15626 insn_buf[1] = ld_jiffies_addr[1];
15627 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
15628 BPF_REG_0, 0);
15629 cnt = 3;
15630
15631 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
15632 cnt);
15633 if (!new_prog)
15634 return -ENOMEM;
15635
15636 delta += cnt - 1;
15637 env->prog = prog = new_prog;
15638 insn = new_prog->insnsi + i + delta;
15639 continue;
15640 }
15641
f92c1e18
JO
15642 /* Implement bpf_get_func_arg inline. */
15643 if (prog_type == BPF_PROG_TYPE_TRACING &&
15644 insn->imm == BPF_FUNC_get_func_arg) {
15645 /* Load nr_args from ctx - 8 */
15646 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15647 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
15648 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
15649 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
15650 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
15651 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15652 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
15653 insn_buf[7] = BPF_JMP_A(1);
15654 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
15655 cnt = 9;
15656
15657 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15658 if (!new_prog)
15659 return -ENOMEM;
15660
15661 delta += cnt - 1;
15662 env->prog = prog = new_prog;
15663 insn = new_prog->insnsi + i + delta;
15664 continue;
15665 }
15666
15667 /* Implement bpf_get_func_ret inline. */
15668 if (prog_type == BPF_PROG_TYPE_TRACING &&
15669 insn->imm == BPF_FUNC_get_func_ret) {
15670 if (eatype == BPF_TRACE_FEXIT ||
15671 eatype == BPF_MODIFY_RETURN) {
15672 /* Load nr_args from ctx - 8 */
15673 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15674 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
15675 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
15676 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
15677 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
15678 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
15679 cnt = 6;
15680 } else {
15681 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
15682 cnt = 1;
15683 }
15684
15685 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
15686 if (!new_prog)
15687 return -ENOMEM;
15688
15689 delta += cnt - 1;
15690 env->prog = prog = new_prog;
15691 insn = new_prog->insnsi + i + delta;
15692 continue;
15693 }
15694
15695 /* Implement get_func_arg_cnt inline. */
15696 if (prog_type == BPF_PROG_TYPE_TRACING &&
15697 insn->imm == BPF_FUNC_get_func_arg_cnt) {
15698 /* Load nr_args from ctx - 8 */
15699 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
15700
15701 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15702 if (!new_prog)
15703 return -ENOMEM;
15704
15705 env->prog = prog = new_prog;
15706 insn = new_prog->insnsi + i + delta;
15707 continue;
15708 }
15709
f705ec76 15710 /* Implement bpf_get_func_ip inline. */
9b99edca
JO
15711 if (prog_type == BPF_PROG_TYPE_TRACING &&
15712 insn->imm == BPF_FUNC_get_func_ip) {
f92c1e18
JO
15713 /* Load IP address from ctx - 16 */
15714 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
9b99edca
JO
15715
15716 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
15717 if (!new_prog)
15718 return -ENOMEM;
15719
15720 env->prog = prog = new_prog;
15721 insn = new_prog->insnsi + i + delta;
15722 continue;
15723 }
15724
81ed18ab 15725patch_call_imm:
5e43f899 15726 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
15727 /* all functions that have prototype and verifier allowed
15728 * programs to call them, must be real in-kernel functions
15729 */
15730 if (!fn->func) {
61bd5218
JK
15731 verbose(env,
15732 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
15733 func_id_name(insn->imm), insn->imm);
15734 return -EFAULT;
e245c5c6 15735 }
79741b3b 15736 insn->imm = fn->func - __bpf_call_base;
e245c5c6 15737 }
e245c5c6 15738
d2e4c1e6
DB
15739 /* Since poke tab is now finalized, publish aux to tracker. */
15740 for (i = 0; i < prog->aux->size_poke_tab; i++) {
15741 map_ptr = prog->aux->poke_tab[i].tail_call.map;
15742 if (!map_ptr->ops->map_poke_track ||
15743 !map_ptr->ops->map_poke_untrack ||
15744 !map_ptr->ops->map_poke_run) {
15745 verbose(env, "bpf verifier is misconfigured\n");
15746 return -EINVAL;
15747 }
15748
15749 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
15750 if (ret < 0) {
15751 verbose(env, "tracking tail call prog failed\n");
15752 return ret;
15753 }
15754 }
15755
e6ac2450
MKL
15756 sort_kfunc_descs_by_imm(env->prog);
15757
79741b3b
AS
15758 return 0;
15759}
e245c5c6 15760
1ade2371
EZ
15761static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
15762 int position,
15763 s32 stack_base,
15764 u32 callback_subprogno,
15765 u32 *cnt)
15766{
15767 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
15768 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
15769 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
15770 int reg_loop_max = BPF_REG_6;
15771 int reg_loop_cnt = BPF_REG_7;
15772 int reg_loop_ctx = BPF_REG_8;
15773
15774 struct bpf_prog *new_prog;
15775 u32 callback_start;
15776 u32 call_insn_offset;
15777 s32 callback_offset;
15778
15779 /* This represents an inlined version of bpf_iter.c:bpf_loop,
15780 * be careful to modify this code in sync.
15781 */
15782 struct bpf_insn insn_buf[] = {
15783 /* Return error and jump to the end of the patch if
15784 * expected number of iterations is too big.
15785 */
15786 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
15787 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
15788 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
15789 /* spill R6, R7, R8 to use these as loop vars */
15790 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
15791 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
15792 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
15793 /* initialize loop vars */
15794 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
15795 BPF_MOV32_IMM(reg_loop_cnt, 0),
15796 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
15797 /* loop header,
15798 * if reg_loop_cnt >= reg_loop_max skip the loop body
15799 */
15800 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
15801 /* callback call,
15802 * correct callback offset would be set after patching
15803 */
15804 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
15805 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
15806 BPF_CALL_REL(0),
15807 /* increment loop counter */
15808 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
15809 /* jump to loop header if callback returned 0 */
15810 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
15811 /* return value of bpf_loop,
15812 * set R0 to the number of iterations
15813 */
15814 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
15815 /* restore original values of R6, R7, R8 */
15816 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
15817 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
15818 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
15819 };
15820
15821 *cnt = ARRAY_SIZE(insn_buf);
15822 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
15823 if (!new_prog)
15824 return new_prog;
15825
15826 /* callback start is known only after patching */
15827 callback_start = env->subprog_info[callback_subprogno].start;
15828 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
15829 call_insn_offset = position + 12;
15830 callback_offset = callback_start - call_insn_offset - 1;
fb4e3b33 15831 new_prog->insnsi[call_insn_offset].imm = callback_offset;
1ade2371
EZ
15832
15833 return new_prog;
15834}
15835
15836static bool is_bpf_loop_call(struct bpf_insn *insn)
15837{
15838 return insn->code == (BPF_JMP | BPF_CALL) &&
15839 insn->src_reg == 0 &&
15840 insn->imm == BPF_FUNC_loop;
15841}
15842
15843/* For all sub-programs in the program (including main) check
15844 * insn_aux_data to see if there are bpf_loop calls that require
15845 * inlining. If such calls are found the calls are replaced with a
15846 * sequence of instructions produced by `inline_bpf_loop` function and
15847 * subprog stack_depth is increased by the size of 3 registers.
15848 * This stack space is used to spill values of the R6, R7, R8. These
15849 * registers are used to store the loop bound, counter and context
15850 * variables.
15851 */
15852static int optimize_bpf_loop(struct bpf_verifier_env *env)
15853{
15854 struct bpf_subprog_info *subprogs = env->subprog_info;
15855 int i, cur_subprog = 0, cnt, delta = 0;
15856 struct bpf_insn *insn = env->prog->insnsi;
15857 int insn_cnt = env->prog->len;
15858 u16 stack_depth = subprogs[cur_subprog].stack_depth;
15859 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15860 u16 stack_depth_extra = 0;
15861
15862 for (i = 0; i < insn_cnt; i++, insn++) {
15863 struct bpf_loop_inline_state *inline_state =
15864 &env->insn_aux_data[i + delta].loop_inline_state;
15865
15866 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
15867 struct bpf_prog *new_prog;
15868
15869 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
15870 new_prog = inline_bpf_loop(env,
15871 i + delta,
15872 -(stack_depth + stack_depth_extra),
15873 inline_state->callback_subprogno,
15874 &cnt);
15875 if (!new_prog)
15876 return -ENOMEM;
15877
15878 delta += cnt - 1;
15879 env->prog = new_prog;
15880 insn = new_prog->insnsi + i + delta;
15881 }
15882
15883 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
15884 subprogs[cur_subprog].stack_depth += stack_depth_extra;
15885 cur_subprog++;
15886 stack_depth = subprogs[cur_subprog].stack_depth;
15887 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
15888 stack_depth_extra = 0;
15889 }
15890 }
15891
15892 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
15893
15894 return 0;
15895}
15896
58e2af8b 15897static void free_states(struct bpf_verifier_env *env)
f1bca824 15898{
58e2af8b 15899 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
15900 int i;
15901
9f4686c4
AS
15902 sl = env->free_list;
15903 while (sl) {
15904 sln = sl->next;
15905 free_verifier_state(&sl->state, false);
15906 kfree(sl);
15907 sl = sln;
15908 }
51c39bb1 15909 env->free_list = NULL;
9f4686c4 15910
f1bca824
AS
15911 if (!env->explored_states)
15912 return;
15913
dc2a4ebc 15914 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
15915 sl = env->explored_states[i];
15916
a8f500af
AS
15917 while (sl) {
15918 sln = sl->next;
15919 free_verifier_state(&sl->state, false);
15920 kfree(sl);
15921 sl = sln;
15922 }
51c39bb1 15923 env->explored_states[i] = NULL;
f1bca824 15924 }
51c39bb1 15925}
f1bca824 15926
51c39bb1
AS
15927static int do_check_common(struct bpf_verifier_env *env, int subprog)
15928{
6f8a57cc 15929 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
15930 struct bpf_verifier_state *state;
15931 struct bpf_reg_state *regs;
15932 int ret, i;
15933
15934 env->prev_linfo = NULL;
15935 env->pass_cnt++;
15936
15937 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
15938 if (!state)
15939 return -ENOMEM;
15940 state->curframe = 0;
15941 state->speculative = false;
15942 state->branches = 1;
15943 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
15944 if (!state->frame[0]) {
15945 kfree(state);
15946 return -ENOMEM;
15947 }
15948 env->cur_state = state;
15949 init_func_state(env, state->frame[0],
15950 BPF_MAIN_FUNC /* callsite */,
15951 0 /* frameno */,
15952 subprog);
be2ef816
AN
15953 state->first_insn_idx = env->subprog_info[subprog].start;
15954 state->last_insn_idx = -1;
51c39bb1
AS
15955
15956 regs = state->frame[state->curframe]->regs;
be8704ff 15957 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
15958 ret = btf_prepare_func_args(env, subprog, regs);
15959 if (ret)
15960 goto out;
15961 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
15962 if (regs[i].type == PTR_TO_CTX)
15963 mark_reg_known_zero(env, regs, i);
15964 else if (regs[i].type == SCALAR_VALUE)
15965 mark_reg_unknown(env, regs, i);
cf9f2f8d 15966 else if (base_type(regs[i].type) == PTR_TO_MEM) {
e5069b9c
DB
15967 const u32 mem_size = regs[i].mem_size;
15968
15969 mark_reg_known_zero(env, regs, i);
15970 regs[i].mem_size = mem_size;
15971 regs[i].id = ++env->id_gen;
15972 }
51c39bb1
AS
15973 }
15974 } else {
15975 /* 1st arg to a function */
15976 regs[BPF_REG_1].type = PTR_TO_CTX;
15977 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 15978 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
15979 if (ret == -EFAULT)
15980 /* unlikely verifier bug. abort.
15981 * ret == 0 and ret < 0 are sadly acceptable for
15982 * main() function due to backward compatibility.
15983 * Like socket filter program may be written as:
15984 * int bpf_prog(struct pt_regs *ctx)
15985 * and never dereference that ctx in the program.
15986 * 'struct pt_regs' is a type mismatch for socket
15987 * filter that should be using 'struct __sk_buff'.
15988 */
15989 goto out;
15990 }
15991
15992 ret = do_check(env);
15993out:
f59bbfc2
AS
15994 /* check for NULL is necessary, since cur_state can be freed inside
15995 * do_check() under memory pressure.
15996 */
15997 if (env->cur_state) {
15998 free_verifier_state(env->cur_state, true);
15999 env->cur_state = NULL;
16000 }
6f8a57cc
AN
16001 while (!pop_stack(env, NULL, NULL, false));
16002 if (!ret && pop_log)
16003 bpf_vlog_reset(&env->log, 0);
51c39bb1 16004 free_states(env);
51c39bb1
AS
16005 return ret;
16006}
16007
16008/* Verify all global functions in a BPF program one by one based on their BTF.
16009 * All global functions must pass verification. Otherwise the whole program is rejected.
16010 * Consider:
16011 * int bar(int);
16012 * int foo(int f)
16013 * {
16014 * return bar(f);
16015 * }
16016 * int bar(int b)
16017 * {
16018 * ...
16019 * }
16020 * foo() will be verified first for R1=any_scalar_value. During verification it
16021 * will be assumed that bar() already verified successfully and call to bar()
16022 * from foo() will be checked for type match only. Later bar() will be verified
16023 * independently to check that it's safe for R1=any_scalar_value.
16024 */
16025static int do_check_subprogs(struct bpf_verifier_env *env)
16026{
16027 struct bpf_prog_aux *aux = env->prog->aux;
16028 int i, ret;
16029
16030 if (!aux->func_info)
16031 return 0;
16032
16033 for (i = 1; i < env->subprog_cnt; i++) {
16034 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
16035 continue;
16036 env->insn_idx = env->subprog_info[i].start;
16037 WARN_ON_ONCE(env->insn_idx == 0);
16038 ret = do_check_common(env, i);
16039 if (ret) {
16040 return ret;
16041 } else if (env->log.level & BPF_LOG_LEVEL) {
16042 verbose(env,
16043 "Func#%d is safe for any args that match its prototype\n",
16044 i);
16045 }
16046 }
16047 return 0;
16048}
16049
16050static int do_check_main(struct bpf_verifier_env *env)
16051{
16052 int ret;
16053
16054 env->insn_idx = 0;
16055 ret = do_check_common(env, 0);
16056 if (!ret)
16057 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
16058 return ret;
16059}
16060
16061
06ee7115
AS
16062static void print_verification_stats(struct bpf_verifier_env *env)
16063{
16064 int i;
16065
16066 if (env->log.level & BPF_LOG_STATS) {
16067 verbose(env, "verification time %lld usec\n",
16068 div_u64(env->verification_time, 1000));
16069 verbose(env, "stack depth ");
16070 for (i = 0; i < env->subprog_cnt; i++) {
16071 u32 depth = env->subprog_info[i].stack_depth;
16072
16073 verbose(env, "%d", depth);
16074 if (i + 1 < env->subprog_cnt)
16075 verbose(env, "+");
16076 }
16077 verbose(env, "\n");
16078 }
16079 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
16080 "total_states %d peak_states %d mark_read %d\n",
16081 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
16082 env->max_states_per_insn, env->total_states,
16083 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
16084}
16085
27ae7997
MKL
16086static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
16087{
16088 const struct btf_type *t, *func_proto;
16089 const struct bpf_struct_ops *st_ops;
16090 const struct btf_member *member;
16091 struct bpf_prog *prog = env->prog;
16092 u32 btf_id, member_idx;
16093 const char *mname;
16094
12aa8a94
THJ
16095 if (!prog->gpl_compatible) {
16096 verbose(env, "struct ops programs must have a GPL compatible license\n");
16097 return -EINVAL;
16098 }
16099
27ae7997
MKL
16100 btf_id = prog->aux->attach_btf_id;
16101 st_ops = bpf_struct_ops_find(btf_id);
16102 if (!st_ops) {
16103 verbose(env, "attach_btf_id %u is not a supported struct\n",
16104 btf_id);
16105 return -ENOTSUPP;
16106 }
16107
16108 t = st_ops->type;
16109 member_idx = prog->expected_attach_type;
16110 if (member_idx >= btf_type_vlen(t)) {
16111 verbose(env, "attach to invalid member idx %u of struct %s\n",
16112 member_idx, st_ops->name);
16113 return -EINVAL;
16114 }
16115
16116 member = &btf_type_member(t)[member_idx];
16117 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
16118 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
16119 NULL);
16120 if (!func_proto) {
16121 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
16122 mname, member_idx, st_ops->name);
16123 return -EINVAL;
16124 }
16125
16126 if (st_ops->check_member) {
16127 int err = st_ops->check_member(t, member);
16128
16129 if (err) {
16130 verbose(env, "attach to unsupported member %s of struct %s\n",
16131 mname, st_ops->name);
16132 return err;
16133 }
16134 }
16135
16136 prog->aux->attach_func_proto = func_proto;
16137 prog->aux->attach_func_name = mname;
16138 env->ops = st_ops->verifier_ops;
16139
16140 return 0;
16141}
6ba43b76
KS
16142#define SECURITY_PREFIX "security_"
16143
f7b12b6f 16144static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 16145{
69191754 16146 if (within_error_injection_list(addr) ||
f7b12b6f 16147 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 16148 return 0;
6ba43b76 16149
6ba43b76
KS
16150 return -EINVAL;
16151}
27ae7997 16152
1e6c62a8
AS
16153/* list of non-sleepable functions that are otherwise on
16154 * ALLOW_ERROR_INJECTION list
16155 */
16156BTF_SET_START(btf_non_sleepable_error_inject)
16157/* Three functions below can be called from sleepable and non-sleepable context.
16158 * Assume non-sleepable from bpf safety point of view.
16159 */
9dd3d069 16160BTF_ID(func, __filemap_add_folio)
1e6c62a8
AS
16161BTF_ID(func, should_fail_alloc_page)
16162BTF_ID(func, should_failslab)
16163BTF_SET_END(btf_non_sleepable_error_inject)
16164
16165static int check_non_sleepable_error_inject(u32 btf_id)
16166{
16167 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
16168}
16169
f7b12b6f
THJ
16170int bpf_check_attach_target(struct bpf_verifier_log *log,
16171 const struct bpf_prog *prog,
16172 const struct bpf_prog *tgt_prog,
16173 u32 btf_id,
16174 struct bpf_attach_target_info *tgt_info)
38207291 16175{
be8704ff 16176 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 16177 const char prefix[] = "btf_trace_";
5b92a28a 16178 int ret = 0, subprog = -1, i;
38207291 16179 const struct btf_type *t;
5b92a28a 16180 bool conservative = true;
38207291 16181 const char *tname;
5b92a28a 16182 struct btf *btf;
f7b12b6f 16183 long addr = 0;
38207291 16184
f1b9509c 16185 if (!btf_id) {
efc68158 16186 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
16187 return -EINVAL;
16188 }
22dc4a0f 16189 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 16190 if (!btf) {
efc68158 16191 bpf_log(log,
5b92a28a
AS
16192 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
16193 return -EINVAL;
16194 }
16195 t = btf_type_by_id(btf, btf_id);
f1b9509c 16196 if (!t) {
efc68158 16197 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
16198 return -EINVAL;
16199 }
5b92a28a 16200 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 16201 if (!tname) {
efc68158 16202 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
16203 return -EINVAL;
16204 }
5b92a28a
AS
16205 if (tgt_prog) {
16206 struct bpf_prog_aux *aux = tgt_prog->aux;
16207
16208 for (i = 0; i < aux->func_info_cnt; i++)
16209 if (aux->func_info[i].type_id == btf_id) {
16210 subprog = i;
16211 break;
16212 }
16213 if (subprog == -1) {
efc68158 16214 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
16215 return -EINVAL;
16216 }
16217 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
16218 if (prog_extension) {
16219 if (conservative) {
efc68158 16220 bpf_log(log,
be8704ff
AS
16221 "Cannot replace static functions\n");
16222 return -EINVAL;
16223 }
16224 if (!prog->jit_requested) {
efc68158 16225 bpf_log(log,
be8704ff
AS
16226 "Extension programs should be JITed\n");
16227 return -EINVAL;
16228 }
be8704ff
AS
16229 }
16230 if (!tgt_prog->jited) {
efc68158 16231 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
16232 return -EINVAL;
16233 }
16234 if (tgt_prog->type == prog->type) {
16235 /* Cannot fentry/fexit another fentry/fexit program.
16236 * Cannot attach program extension to another extension.
16237 * It's ok to attach fentry/fexit to extension program.
16238 */
efc68158 16239 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
16240 return -EINVAL;
16241 }
16242 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
16243 prog_extension &&
16244 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
16245 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
16246 /* Program extensions can extend all program types
16247 * except fentry/fexit. The reason is the following.
16248 * The fentry/fexit programs are used for performance
16249 * analysis, stats and can be attached to any program
16250 * type except themselves. When extension program is
16251 * replacing XDP function it is necessary to allow
16252 * performance analysis of all functions. Both original
16253 * XDP program and its program extension. Hence
16254 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
16255 * allowed. If extending of fentry/fexit was allowed it
16256 * would be possible to create long call chain
16257 * fentry->extension->fentry->extension beyond
16258 * reasonable stack size. Hence extending fentry is not
16259 * allowed.
16260 */
efc68158 16261 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
16262 return -EINVAL;
16263 }
5b92a28a 16264 } else {
be8704ff 16265 if (prog_extension) {
efc68158 16266 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
16267 return -EINVAL;
16268 }
5b92a28a 16269 }
f1b9509c
AS
16270
16271 switch (prog->expected_attach_type) {
16272 case BPF_TRACE_RAW_TP:
5b92a28a 16273 if (tgt_prog) {
efc68158 16274 bpf_log(log,
5b92a28a
AS
16275 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
16276 return -EINVAL;
16277 }
38207291 16278 if (!btf_type_is_typedef(t)) {
efc68158 16279 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
16280 btf_id);
16281 return -EINVAL;
16282 }
f1b9509c 16283 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 16284 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
16285 btf_id, tname);
16286 return -EINVAL;
16287 }
16288 tname += sizeof(prefix) - 1;
5b92a28a 16289 t = btf_type_by_id(btf, t->type);
38207291
MKL
16290 if (!btf_type_is_ptr(t))
16291 /* should never happen in valid vmlinux build */
16292 return -EINVAL;
5b92a28a 16293 t = btf_type_by_id(btf, t->type);
38207291
MKL
16294 if (!btf_type_is_func_proto(t))
16295 /* should never happen in valid vmlinux build */
16296 return -EINVAL;
16297
f7b12b6f 16298 break;
15d83c4d
YS
16299 case BPF_TRACE_ITER:
16300 if (!btf_type_is_func(t)) {
efc68158 16301 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
16302 btf_id);
16303 return -EINVAL;
16304 }
16305 t = btf_type_by_id(btf, t->type);
16306 if (!btf_type_is_func_proto(t))
16307 return -EINVAL;
f7b12b6f
THJ
16308 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
16309 if (ret)
16310 return ret;
16311 break;
be8704ff
AS
16312 default:
16313 if (!prog_extension)
16314 return -EINVAL;
df561f66 16315 fallthrough;
ae240823 16316 case BPF_MODIFY_RETURN:
9e4e01df 16317 case BPF_LSM_MAC:
69fd337a 16318 case BPF_LSM_CGROUP:
fec56f58
AS
16319 case BPF_TRACE_FENTRY:
16320 case BPF_TRACE_FEXIT:
16321 if (!btf_type_is_func(t)) {
efc68158 16322 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
16323 btf_id);
16324 return -EINVAL;
16325 }
be8704ff 16326 if (prog_extension &&
efc68158 16327 btf_check_type_match(log, prog, btf, t))
be8704ff 16328 return -EINVAL;
5b92a28a 16329 t = btf_type_by_id(btf, t->type);
fec56f58
AS
16330 if (!btf_type_is_func_proto(t))
16331 return -EINVAL;
f7b12b6f 16332
4a1e7c0c
THJ
16333 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
16334 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
16335 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
16336 return -EINVAL;
16337
f7b12b6f 16338 if (tgt_prog && conservative)
5b92a28a 16339 t = NULL;
f7b12b6f
THJ
16340
16341 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 16342 if (ret < 0)
f7b12b6f
THJ
16343 return ret;
16344
5b92a28a 16345 if (tgt_prog) {
e9eeec58
YS
16346 if (subprog == 0)
16347 addr = (long) tgt_prog->bpf_func;
16348 else
16349 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
16350 } else {
16351 addr = kallsyms_lookup_name(tname);
16352 if (!addr) {
efc68158 16353 bpf_log(log,
5b92a28a
AS
16354 "The address of function %s cannot be found\n",
16355 tname);
f7b12b6f 16356 return -ENOENT;
5b92a28a 16357 }
fec56f58 16358 }
18644cec 16359
1e6c62a8
AS
16360 if (prog->aux->sleepable) {
16361 ret = -EINVAL;
16362 switch (prog->type) {
16363 case BPF_PROG_TYPE_TRACING:
16364 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
16365 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
16366 */
16367 if (!check_non_sleepable_error_inject(btf_id) &&
16368 within_error_injection_list(addr))
16369 ret = 0;
16370 break;
16371 case BPF_PROG_TYPE_LSM:
16372 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
16373 * Only some of them are sleepable.
16374 */
423f1610 16375 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
16376 ret = 0;
16377 break;
16378 default:
16379 break;
16380 }
f7b12b6f
THJ
16381 if (ret) {
16382 bpf_log(log, "%s is not sleepable\n", tname);
16383 return ret;
16384 }
1e6c62a8 16385 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 16386 if (tgt_prog) {
efc68158 16387 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
16388 return -EINVAL;
16389 }
16390 ret = check_attach_modify_return(addr, tname);
16391 if (ret) {
16392 bpf_log(log, "%s() is not modifiable\n", tname);
16393 return ret;
1af9270e 16394 }
18644cec 16395 }
f7b12b6f
THJ
16396
16397 break;
16398 }
16399 tgt_info->tgt_addr = addr;
16400 tgt_info->tgt_name = tname;
16401 tgt_info->tgt_type = t;
16402 return 0;
16403}
16404
35e3815f
JO
16405BTF_SET_START(btf_id_deny)
16406BTF_ID_UNUSED
16407#ifdef CONFIG_SMP
16408BTF_ID(func, migrate_disable)
16409BTF_ID(func, migrate_enable)
16410#endif
16411#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
16412BTF_ID(func, rcu_read_unlock_strict)
16413#endif
16414BTF_SET_END(btf_id_deny)
16415
f7b12b6f
THJ
16416static int check_attach_btf_id(struct bpf_verifier_env *env)
16417{
16418 struct bpf_prog *prog = env->prog;
3aac1ead 16419 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
16420 struct bpf_attach_target_info tgt_info = {};
16421 u32 btf_id = prog->aux->attach_btf_id;
16422 struct bpf_trampoline *tr;
16423 int ret;
16424 u64 key;
16425
79a7f8bd
AS
16426 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
16427 if (prog->aux->sleepable)
16428 /* attach_btf_id checked to be zero already */
16429 return 0;
16430 verbose(env, "Syscall programs can only be sleepable\n");
16431 return -EINVAL;
16432 }
16433
f7b12b6f 16434 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
64ad7556
DK
16435 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
16436 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
f7b12b6f
THJ
16437 return -EINVAL;
16438 }
16439
16440 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
16441 return check_struct_ops_btf_id(env);
16442
16443 if (prog->type != BPF_PROG_TYPE_TRACING &&
16444 prog->type != BPF_PROG_TYPE_LSM &&
16445 prog->type != BPF_PROG_TYPE_EXT)
16446 return 0;
16447
16448 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
16449 if (ret)
fec56f58 16450 return ret;
f7b12b6f
THJ
16451
16452 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
16453 /* to make freplace equivalent to their targets, they need to
16454 * inherit env->ops and expected_attach_type for the rest of the
16455 * verification
16456 */
f7b12b6f
THJ
16457 env->ops = bpf_verifier_ops[tgt_prog->type];
16458 prog->expected_attach_type = tgt_prog->expected_attach_type;
16459 }
16460
16461 /* store info about the attachment target that will be used later */
16462 prog->aux->attach_func_proto = tgt_info.tgt_type;
16463 prog->aux->attach_func_name = tgt_info.tgt_name;
16464
4a1e7c0c
THJ
16465 if (tgt_prog) {
16466 prog->aux->saved_dst_prog_type = tgt_prog->type;
16467 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
16468 }
16469
f7b12b6f
THJ
16470 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
16471 prog->aux->attach_btf_trace = true;
16472 return 0;
16473 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
16474 if (!bpf_iter_prog_supported(prog))
16475 return -EINVAL;
16476 return 0;
16477 }
16478
16479 if (prog->type == BPF_PROG_TYPE_LSM) {
16480 ret = bpf_lsm_verify_prog(&env->log, prog);
16481 if (ret < 0)
16482 return ret;
35e3815f
JO
16483 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
16484 btf_id_set_contains(&btf_id_deny, btf_id)) {
16485 return -EINVAL;
38207291 16486 }
f7b12b6f 16487
22dc4a0f 16488 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
16489 tr = bpf_trampoline_get(key, &tgt_info);
16490 if (!tr)
16491 return -ENOMEM;
16492
3aac1ead 16493 prog->aux->dst_trampoline = tr;
f7b12b6f 16494 return 0;
38207291
MKL
16495}
16496
76654e67
AM
16497struct btf *bpf_get_btf_vmlinux(void)
16498{
16499 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
16500 mutex_lock(&bpf_verifier_lock);
16501 if (!btf_vmlinux)
16502 btf_vmlinux = btf_parse_vmlinux();
16503 mutex_unlock(&bpf_verifier_lock);
16504 }
16505 return btf_vmlinux;
16506}
16507
af2ac3e1 16508int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
51580e79 16509{
06ee7115 16510 u64 start_time = ktime_get_ns();
58e2af8b 16511 struct bpf_verifier_env *env;
b9193c1b 16512 struct bpf_verifier_log *log;
9e4c24e7 16513 int i, len, ret = -EINVAL;
e2ae4ca2 16514 bool is_priv;
51580e79 16515
eba0c929
AB
16516 /* no program is valid */
16517 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
16518 return -EINVAL;
16519
58e2af8b 16520 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
16521 * allocate/free it every time bpf_check() is called
16522 */
58e2af8b 16523 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
16524 if (!env)
16525 return -ENOMEM;
61bd5218 16526 log = &env->log;
cbd35700 16527
9e4c24e7 16528 len = (*prog)->len;
fad953ce 16529 env->insn_aux_data =
9e4c24e7 16530 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
16531 ret = -ENOMEM;
16532 if (!env->insn_aux_data)
16533 goto err_free_env;
9e4c24e7
JK
16534 for (i = 0; i < len; i++)
16535 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 16536 env->prog = *prog;
00176a34 16537 env->ops = bpf_verifier_ops[env->prog->type];
387544bf 16538 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
2c78ee89 16539 is_priv = bpf_capable();
0246e64d 16540
76654e67 16541 bpf_get_btf_vmlinux();
8580ac94 16542
cbd35700 16543 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
16544 if (!is_priv)
16545 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
16546
16547 if (attr->log_level || attr->log_buf || attr->log_size) {
16548 /* user requested verbose verifier output
16549 * and supplied buffer to store the verification trace
16550 */
e7bf8249
JK
16551 log->level = attr->log_level;
16552 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
16553 log->len_total = attr->log_size;
cbd35700 16554
e7bf8249 16555 /* log attributes have to be sane */
866de407
HT
16556 if (!bpf_verifier_log_attr_valid(log)) {
16557 ret = -EINVAL;
3df126f3 16558 goto err_unlock;
866de407 16559 }
cbd35700 16560 }
1ad2f583 16561
0f55f9ed
CL
16562 mark_verifier_state_clean(env);
16563
8580ac94
AS
16564 if (IS_ERR(btf_vmlinux)) {
16565 /* Either gcc or pahole or kernel are broken. */
16566 verbose(env, "in-kernel BTF is malformed\n");
16567 ret = PTR_ERR(btf_vmlinux);
38207291 16568 goto skip_full_check;
8580ac94
AS
16569 }
16570
1ad2f583
DB
16571 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
16572 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 16573 env->strict_alignment = true;
e9ee9efc
DM
16574 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
16575 env->strict_alignment = false;
cbd35700 16576
2c78ee89 16577 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 16578 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 16579 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
16580 env->bypass_spec_v1 = bpf_bypass_spec_v1();
16581 env->bypass_spec_v4 = bpf_bypass_spec_v4();
16582 env->bpf_capable = bpf_capable();
e2ae4ca2 16583
10d274e8
AS
16584 if (is_priv)
16585 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
16586
dc2a4ebc 16587 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 16588 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
16589 GFP_USER);
16590 ret = -ENOMEM;
16591 if (!env->explored_states)
16592 goto skip_full_check;
16593
e6ac2450
MKL
16594 ret = add_subprog_and_kfunc(env);
16595 if (ret < 0)
16596 goto skip_full_check;
16597
d9762e84 16598 ret = check_subprogs(env);
475fb78f
AS
16599 if (ret < 0)
16600 goto skip_full_check;
16601
c454a46b 16602 ret = check_btf_info(env, attr, uattr);
838e9690
YS
16603 if (ret < 0)
16604 goto skip_full_check;
16605
be8704ff
AS
16606 ret = check_attach_btf_id(env);
16607 if (ret)
16608 goto skip_full_check;
16609
4976b718
HL
16610 ret = resolve_pseudo_ldimm64(env);
16611 if (ret < 0)
16612 goto skip_full_check;
16613
ceb11679
YZ
16614 if (bpf_prog_is_dev_bound(env->prog->aux)) {
16615 ret = bpf_prog_offload_verifier_prep(env->prog);
16616 if (ret)
16617 goto skip_full_check;
16618 }
16619
d9762e84
MKL
16620 ret = check_cfg(env);
16621 if (ret < 0)
16622 goto skip_full_check;
16623
51c39bb1
AS
16624 ret = do_check_subprogs(env);
16625 ret = ret ?: do_check_main(env);
cbd35700 16626
c941ce9c
QM
16627 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
16628 ret = bpf_prog_offload_finalize(env);
16629
0246e64d 16630skip_full_check:
51c39bb1 16631 kvfree(env->explored_states);
0246e64d 16632
c131187d 16633 if (ret == 0)
9b38c405 16634 ret = check_max_stack_depth(env);
c131187d 16635
9b38c405 16636 /* instruction rewrites happen after this point */
1ade2371
EZ
16637 if (ret == 0)
16638 ret = optimize_bpf_loop(env);
16639
e2ae4ca2
JK
16640 if (is_priv) {
16641 if (ret == 0)
16642 opt_hard_wire_dead_code_branches(env);
52875a04
JK
16643 if (ret == 0)
16644 ret = opt_remove_dead_code(env);
a1b14abc
JK
16645 if (ret == 0)
16646 ret = opt_remove_nops(env);
52875a04
JK
16647 } else {
16648 if (ret == 0)
16649 sanitize_dead_code(env);
e2ae4ca2
JK
16650 }
16651
9bac3d6d
AS
16652 if (ret == 0)
16653 /* program is valid, convert *(u32*)(ctx + off) accesses */
16654 ret = convert_ctx_accesses(env);
16655
e245c5c6 16656 if (ret == 0)
e6ac5933 16657 ret = do_misc_fixups(env);
e245c5c6 16658
a4b1d3c1
JW
16659 /* do 32-bit optimization after insn patching has done so those patched
16660 * insns could be handled correctly.
16661 */
d6c2308c
JW
16662 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
16663 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
16664 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
16665 : false;
a4b1d3c1
JW
16666 }
16667
1ea47e01
AS
16668 if (ret == 0)
16669 ret = fixup_call_args(env);
16670
06ee7115
AS
16671 env->verification_time = ktime_get_ns() - start_time;
16672 print_verification_stats(env);
aba64c7d 16673 env->prog->aux->verified_insns = env->insn_processed;
06ee7115 16674
a2a7d570 16675 if (log->level && bpf_verifier_log_full(log))
cbd35700 16676 ret = -ENOSPC;
a2a7d570 16677 if (log->level && !log->ubuf) {
cbd35700 16678 ret = -EFAULT;
a2a7d570 16679 goto err_release_maps;
cbd35700
AS
16680 }
16681
541c3bad
AN
16682 if (ret)
16683 goto err_release_maps;
16684
16685 if (env->used_map_cnt) {
0246e64d 16686 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
16687 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
16688 sizeof(env->used_maps[0]),
16689 GFP_KERNEL);
0246e64d 16690
9bac3d6d 16691 if (!env->prog->aux->used_maps) {
0246e64d 16692 ret = -ENOMEM;
a2a7d570 16693 goto err_release_maps;
0246e64d
AS
16694 }
16695
9bac3d6d 16696 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 16697 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 16698 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
16699 }
16700 if (env->used_btf_cnt) {
16701 /* if program passed verifier, update used_btfs in bpf_prog_aux */
16702 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
16703 sizeof(env->used_btfs[0]),
16704 GFP_KERNEL);
16705 if (!env->prog->aux->used_btfs) {
16706 ret = -ENOMEM;
16707 goto err_release_maps;
16708 }
0246e64d 16709
541c3bad
AN
16710 memcpy(env->prog->aux->used_btfs, env->used_btfs,
16711 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
16712 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
16713 }
16714 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
16715 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
16716 * bpf_ld_imm64 instructions
16717 */
16718 convert_pseudo_ld_imm64(env);
16719 }
cbd35700 16720
541c3bad 16721 adjust_btf_func(env);
ba64e7d8 16722
a2a7d570 16723err_release_maps:
9bac3d6d 16724 if (!env->prog->aux->used_maps)
0246e64d 16725 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 16726 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
16727 */
16728 release_maps(env);
541c3bad
AN
16729 if (!env->prog->aux->used_btfs)
16730 release_btfs(env);
03f87c0b
THJ
16731
16732 /* extension progs temporarily inherit the attach_type of their targets
16733 for verification purposes, so set it back to zero before returning
16734 */
16735 if (env->prog->type == BPF_PROG_TYPE_EXT)
16736 env->prog->expected_attach_type = 0;
16737
9bac3d6d 16738 *prog = env->prog;
3df126f3 16739err_unlock:
45a73c17
AS
16740 if (!is_priv)
16741 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
16742 vfree(env->insn_aux_data);
16743err_free_env:
16744 kfree(env);
51580e79
AS
16745 return ret;
16746}