libbpf: Preserve empty DATASEC BTFs during static linking
[linux-block.git] / kernel / bpf / verifier.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
51580e79 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 3 * Copyright (c) 2016 Facebook
fd978bf7 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79 5 */
838e9690 6#include <uapi/linux/btf.h>
51580e79
AS
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
838e9690 11#include <linux/btf.h>
58e2af8b 12#include <linux/bpf_verifier.h>
51580e79
AS
13#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
ebb676da 17#include <linux/stringify.h>
cc8b0b92
AS
18#include <linux/bsearch.h>
19#include <linux/sort.h>
c195651e 20#include <linux/perf_event.h>
d9762e84 21#include <linux/ctype.h>
6ba43b76 22#include <linux/error-injection.h>
9e4e01df 23#include <linux/bpf_lsm.h>
1e6c62a8 24#include <linux/btf_ids.h>
51580e79 25
f4ac7e0b
JK
26#include "disasm.h"
27
00176a34 28static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 29#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
30 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 32#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
33#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
f2e10bff 36#undef BPF_LINK_TYPE
00176a34
JK
37};
38
51580e79
AS
39/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
eba38a96 51 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
f1174f77 79 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 80 * means the register has some value, but it's not a valid pointer.
f1174f77 81 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
82 *
83 * When verifier sees load or store instructions the type of base register
c64b7983
JS
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
51580e79
AS
86 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
162 */
163
17a52670 164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 165struct bpf_verifier_stack_elem {
17a52670
AS
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
58e2af8b 170 struct bpf_verifier_state st;
17a52670
AS
171 int insn_idx;
172 int prev_insn_idx;
58e2af8b 173 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
cbd35700
AS
176};
177
b285fcb7 178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 179#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 180
d2e4c1e6
DB
181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
c93552c4
DB
184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
d2e4c1e6 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 229}
fad73a1a 230
23a2d70c
YS
231static bool bpf_pseudo_call(const struct bpf_insn *insn)
232{
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
235}
236
69c087ba
YS
237static bool bpf_pseudo_func(const struct bpf_insn *insn)
238{
239 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
240 insn->src_reg == BPF_PSEUDO_FUNC;
241}
242
33ff9823
DB
243struct bpf_call_arg_meta {
244 struct bpf_map *map_ptr;
435faee1 245 bool raw_mode;
36bbef52 246 bool pkt_access;
435faee1
DB
247 int regno;
248 int access_size;
457f4436 249 int mem_size;
10060503 250 u64 msize_max_value;
1b986589 251 int ref_obj_id;
d83525ca 252 int func_id;
22dc4a0f 253 struct btf *btf;
eaa6bcb7 254 u32 btf_id;
22dc4a0f 255 struct btf *ret_btf;
eaa6bcb7 256 u32 ret_btf_id;
69c087ba 257 u32 subprogno;
33ff9823
DB
258};
259
8580ac94
AS
260struct btf *btf_vmlinux;
261
cbd35700
AS
262static DEFINE_MUTEX(bpf_verifier_lock);
263
d9762e84
MKL
264static const struct bpf_line_info *
265find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
266{
267 const struct bpf_line_info *linfo;
268 const struct bpf_prog *prog;
269 u32 i, nr_linfo;
270
271 prog = env->prog;
272 nr_linfo = prog->aux->nr_linfo;
273
274 if (!nr_linfo || insn_off >= prog->len)
275 return NULL;
276
277 linfo = prog->aux->linfo;
278 for (i = 1; i < nr_linfo; i++)
279 if (insn_off < linfo[i].insn_off)
280 break;
281
282 return &linfo[i - 1];
283}
284
77d2e05a
MKL
285void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
286 va_list args)
cbd35700 287{
a2a7d570 288 unsigned int n;
cbd35700 289
a2a7d570 290 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
291
292 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
293 "verifier log line truncated - local buffer too short\n");
294
295 n = min(log->len_total - log->len_used - 1, n);
296 log->kbuf[n] = '\0';
297
8580ac94
AS
298 if (log->level == BPF_LOG_KERNEL) {
299 pr_err("BPF:%s\n", log->kbuf);
300 return;
301 }
a2a7d570
JK
302 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
303 log->len_used += n;
304 else
305 log->ubuf = NULL;
cbd35700 306}
abe08840 307
6f8a57cc
AN
308static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
309{
310 char zero = 0;
311
312 if (!bpf_verifier_log_needed(log))
313 return;
314
315 log->len_used = new_pos;
316 if (put_user(zero, log->ubuf + new_pos))
317 log->ubuf = NULL;
318}
319
abe08840
JO
320/* log_level controls verbosity level of eBPF verifier.
321 * bpf_verifier_log_write() is used to dump the verification trace to the log,
322 * so the user can figure out what's wrong with the program
430e68d1 323 */
abe08840
JO
324__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
325 const char *fmt, ...)
326{
327 va_list args;
328
77d2e05a
MKL
329 if (!bpf_verifier_log_needed(&env->log))
330 return;
331
abe08840 332 va_start(args, fmt);
77d2e05a 333 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
334 va_end(args);
335}
336EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
337
338__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
339{
77d2e05a 340 struct bpf_verifier_env *env = private_data;
abe08840
JO
341 va_list args;
342
77d2e05a
MKL
343 if (!bpf_verifier_log_needed(&env->log))
344 return;
345
abe08840 346 va_start(args, fmt);
77d2e05a 347 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
348 va_end(args);
349}
cbd35700 350
9e15db66
AS
351__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
352 const char *fmt, ...)
353{
354 va_list args;
355
356 if (!bpf_verifier_log_needed(log))
357 return;
358
359 va_start(args, fmt);
360 bpf_verifier_vlog(log, fmt, args);
361 va_end(args);
362}
363
d9762e84
MKL
364static const char *ltrim(const char *s)
365{
366 while (isspace(*s))
367 s++;
368
369 return s;
370}
371
372__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
373 u32 insn_off,
374 const char *prefix_fmt, ...)
375{
376 const struct bpf_line_info *linfo;
377
378 if (!bpf_verifier_log_needed(&env->log))
379 return;
380
381 linfo = find_linfo(env, insn_off);
382 if (!linfo || linfo == env->prev_linfo)
383 return;
384
385 if (prefix_fmt) {
386 va_list args;
387
388 va_start(args, prefix_fmt);
389 bpf_verifier_vlog(&env->log, prefix_fmt, args);
390 va_end(args);
391 }
392
393 verbose(env, "%s\n",
394 ltrim(btf_name_by_offset(env->prog->aux->btf,
395 linfo->line_off)));
396
397 env->prev_linfo = linfo;
398}
399
bc2591d6
YS
400static void verbose_invalid_scalar(struct bpf_verifier_env *env,
401 struct bpf_reg_state *reg,
402 struct tnum *range, const char *ctx,
403 const char *reg_name)
404{
405 char tn_buf[48];
406
407 verbose(env, "At %s the register %s ", ctx, reg_name);
408 if (!tnum_is_unknown(reg->var_off)) {
409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
410 verbose(env, "has value %s", tn_buf);
411 } else {
412 verbose(env, "has unknown scalar value");
413 }
414 tnum_strn(tn_buf, sizeof(tn_buf), *range);
415 verbose(env, " should have been in %s\n", tn_buf);
416}
417
de8f3a83
DB
418static bool type_is_pkt_pointer(enum bpf_reg_type type)
419{
420 return type == PTR_TO_PACKET ||
421 type == PTR_TO_PACKET_META;
422}
423
46f8bc92
MKL
424static bool type_is_sk_pointer(enum bpf_reg_type type)
425{
426 return type == PTR_TO_SOCKET ||
655a51e5 427 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
428 type == PTR_TO_TCP_SOCK ||
429 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
430}
431
cac616db
JF
432static bool reg_type_not_null(enum bpf_reg_type type)
433{
434 return type == PTR_TO_SOCKET ||
435 type == PTR_TO_TCP_SOCK ||
436 type == PTR_TO_MAP_VALUE ||
69c087ba 437 type == PTR_TO_MAP_KEY ||
01c66c48 438 type == PTR_TO_SOCK_COMMON;
cac616db
JF
439}
440
840b9615
JS
441static bool reg_type_may_be_null(enum bpf_reg_type type)
442{
fd978bf7 443 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 444 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 445 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 446 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 447 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
448 type == PTR_TO_MEM_OR_NULL ||
449 type == PTR_TO_RDONLY_BUF_OR_NULL ||
450 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
451}
452
d83525ca
AS
453static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
454{
455 return reg->type == PTR_TO_MAP_VALUE &&
456 map_value_has_spin_lock(reg->map_ptr);
457}
458
cba368c1
MKL
459static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
460{
461 return type == PTR_TO_SOCKET ||
462 type == PTR_TO_SOCKET_OR_NULL ||
463 type == PTR_TO_TCP_SOCK ||
457f4436
AN
464 type == PTR_TO_TCP_SOCK_OR_NULL ||
465 type == PTR_TO_MEM ||
466 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
467}
468
1b986589 469static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 470{
1b986589 471 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
472}
473
fd1b0d60
LB
474static bool arg_type_may_be_null(enum bpf_arg_type type)
475{
476 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
477 type == ARG_PTR_TO_MEM_OR_NULL ||
478 type == ARG_PTR_TO_CTX_OR_NULL ||
479 type == ARG_PTR_TO_SOCKET_OR_NULL ||
69c087ba
YS
480 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
481 type == ARG_PTR_TO_STACK_OR_NULL;
fd1b0d60
LB
482}
483
fd978bf7
JS
484/* Determine whether the function releases some resources allocated by another
485 * function call. The first reference type argument will be assumed to be
486 * released by release_reference().
487 */
488static bool is_release_function(enum bpf_func_id func_id)
489{
457f4436
AN
490 return func_id == BPF_FUNC_sk_release ||
491 func_id == BPF_FUNC_ringbuf_submit ||
492 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
493}
494
64d85290 495static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
496{
497 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 498 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 499 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
500 func_id == BPF_FUNC_map_lookup_elem ||
501 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
502}
503
504static bool is_acquire_function(enum bpf_func_id func_id,
505 const struct bpf_map *map)
506{
507 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
508
509 if (func_id == BPF_FUNC_sk_lookup_tcp ||
510 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
511 func_id == BPF_FUNC_skc_lookup_tcp ||
512 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
513 return true;
514
515 if (func_id == BPF_FUNC_map_lookup_elem &&
516 (map_type == BPF_MAP_TYPE_SOCKMAP ||
517 map_type == BPF_MAP_TYPE_SOCKHASH))
518 return true;
519
520 return false;
46f8bc92
MKL
521}
522
1b986589
MKL
523static bool is_ptr_cast_function(enum bpf_func_id func_id)
524{
525 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
526 func_id == BPF_FUNC_sk_fullsock ||
527 func_id == BPF_FUNC_skc_to_tcp_sock ||
528 func_id == BPF_FUNC_skc_to_tcp6_sock ||
529 func_id == BPF_FUNC_skc_to_udp6_sock ||
530 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
531 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
532}
533
39491867
BJ
534static bool is_cmpxchg_insn(const struct bpf_insn *insn)
535{
536 return BPF_CLASS(insn->code) == BPF_STX &&
537 BPF_MODE(insn->code) == BPF_ATOMIC &&
538 insn->imm == BPF_CMPXCHG;
539}
540
17a52670
AS
541/* string representation of 'enum bpf_reg_type' */
542static const char * const reg_type_str[] = {
543 [NOT_INIT] = "?",
f1174f77 544 [SCALAR_VALUE] = "inv",
17a52670
AS
545 [PTR_TO_CTX] = "ctx",
546 [CONST_PTR_TO_MAP] = "map_ptr",
547 [PTR_TO_MAP_VALUE] = "map_value",
548 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 549 [PTR_TO_STACK] = "fp",
969bf05e 550 [PTR_TO_PACKET] = "pkt",
de8f3a83 551 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 552 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 553 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
554 [PTR_TO_SOCKET] = "sock",
555 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
556 [PTR_TO_SOCK_COMMON] = "sock_common",
557 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
558 [PTR_TO_TCP_SOCK] = "tcp_sock",
559 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 560 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 561 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 562 [PTR_TO_BTF_ID] = "ptr_",
b121b341 563 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
eaa6bcb7 564 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
457f4436
AN
565 [PTR_TO_MEM] = "mem",
566 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
567 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
568 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
569 [PTR_TO_RDWR_BUF] = "rdwr_buf",
570 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
69c087ba
YS
571 [PTR_TO_FUNC] = "func",
572 [PTR_TO_MAP_KEY] = "map_key",
17a52670
AS
573};
574
8efea21d
EC
575static char slot_type_char[] = {
576 [STACK_INVALID] = '?',
577 [STACK_SPILL] = 'r',
578 [STACK_MISC] = 'm',
579 [STACK_ZERO] = '0',
580};
581
4e92024a
AS
582static void print_liveness(struct bpf_verifier_env *env,
583 enum bpf_reg_liveness live)
584{
9242b5f5 585 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
586 verbose(env, "_");
587 if (live & REG_LIVE_READ)
588 verbose(env, "r");
589 if (live & REG_LIVE_WRITTEN)
590 verbose(env, "w");
9242b5f5
AS
591 if (live & REG_LIVE_DONE)
592 verbose(env, "D");
4e92024a
AS
593}
594
f4d7e40a
AS
595static struct bpf_func_state *func(struct bpf_verifier_env *env,
596 const struct bpf_reg_state *reg)
597{
598 struct bpf_verifier_state *cur = env->cur_state;
599
600 return cur->frame[reg->frameno];
601}
602
22dc4a0f 603static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 604{
22dc4a0f 605 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
606}
607
61bd5218 608static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 609 const struct bpf_func_state *state)
17a52670 610{
f4d7e40a 611 const struct bpf_reg_state *reg;
17a52670
AS
612 enum bpf_reg_type t;
613 int i;
614
f4d7e40a
AS
615 if (state->frameno)
616 verbose(env, " frame%d:", state->frameno);
17a52670 617 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
618 reg = &state->regs[i];
619 t = reg->type;
17a52670
AS
620 if (t == NOT_INIT)
621 continue;
4e92024a
AS
622 verbose(env, " R%d", i);
623 print_liveness(env, reg->live);
624 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
625 if (t == SCALAR_VALUE && reg->precise)
626 verbose(env, "P");
f1174f77
EC
627 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
628 tnum_is_const(reg->var_off)) {
629 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 630 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 631 } else {
eaa6bcb7
HL
632 if (t == PTR_TO_BTF_ID ||
633 t == PTR_TO_BTF_ID_OR_NULL ||
634 t == PTR_TO_PERCPU_BTF_ID)
22dc4a0f 635 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
cba368c1
MKL
636 verbose(env, "(id=%d", reg->id);
637 if (reg_type_may_be_refcounted_or_null(t))
638 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 639 if (t != SCALAR_VALUE)
61bd5218 640 verbose(env, ",off=%d", reg->off);
de8f3a83 641 if (type_is_pkt_pointer(t))
61bd5218 642 verbose(env, ",r=%d", reg->range);
f1174f77 643 else if (t == CONST_PTR_TO_MAP ||
69c087ba 644 t == PTR_TO_MAP_KEY ||
f1174f77
EC
645 t == PTR_TO_MAP_VALUE ||
646 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 647 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
648 reg->map_ptr->key_size,
649 reg->map_ptr->value_size);
7d1238f2
EC
650 if (tnum_is_const(reg->var_off)) {
651 /* Typically an immediate SCALAR_VALUE, but
652 * could be a pointer whose offset is too big
653 * for reg->off
654 */
61bd5218 655 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
656 } else {
657 if (reg->smin_value != reg->umin_value &&
658 reg->smin_value != S64_MIN)
61bd5218 659 verbose(env, ",smin_value=%lld",
7d1238f2
EC
660 (long long)reg->smin_value);
661 if (reg->smax_value != reg->umax_value &&
662 reg->smax_value != S64_MAX)
61bd5218 663 verbose(env, ",smax_value=%lld",
7d1238f2
EC
664 (long long)reg->smax_value);
665 if (reg->umin_value != 0)
61bd5218 666 verbose(env, ",umin_value=%llu",
7d1238f2
EC
667 (unsigned long long)reg->umin_value);
668 if (reg->umax_value != U64_MAX)
61bd5218 669 verbose(env, ",umax_value=%llu",
7d1238f2
EC
670 (unsigned long long)reg->umax_value);
671 if (!tnum_is_unknown(reg->var_off)) {
672 char tn_buf[48];
f1174f77 673
7d1238f2 674 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 675 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 676 }
3f50f132
JF
677 if (reg->s32_min_value != reg->smin_value &&
678 reg->s32_min_value != S32_MIN)
679 verbose(env, ",s32_min_value=%d",
680 (int)(reg->s32_min_value));
681 if (reg->s32_max_value != reg->smax_value &&
682 reg->s32_max_value != S32_MAX)
683 verbose(env, ",s32_max_value=%d",
684 (int)(reg->s32_max_value));
685 if (reg->u32_min_value != reg->umin_value &&
686 reg->u32_min_value != U32_MIN)
687 verbose(env, ",u32_min_value=%d",
688 (int)(reg->u32_min_value));
689 if (reg->u32_max_value != reg->umax_value &&
690 reg->u32_max_value != U32_MAX)
691 verbose(env, ",u32_max_value=%d",
692 (int)(reg->u32_max_value));
f1174f77 693 }
61bd5218 694 verbose(env, ")");
f1174f77 695 }
17a52670 696 }
638f5b90 697 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
698 char types_buf[BPF_REG_SIZE + 1];
699 bool valid = false;
700 int j;
701
702 for (j = 0; j < BPF_REG_SIZE; j++) {
703 if (state->stack[i].slot_type[j] != STACK_INVALID)
704 valid = true;
705 types_buf[j] = slot_type_char[
706 state->stack[i].slot_type[j]];
707 }
708 types_buf[BPF_REG_SIZE] = 0;
709 if (!valid)
710 continue;
711 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
712 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
713 if (state->stack[i].slot_type[0] == STACK_SPILL) {
714 reg = &state->stack[i].spilled_ptr;
715 t = reg->type;
716 verbose(env, "=%s", reg_type_str[t]);
717 if (t == SCALAR_VALUE && reg->precise)
718 verbose(env, "P");
719 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
720 verbose(env, "%lld", reg->var_off.value + reg->off);
721 } else {
8efea21d 722 verbose(env, "=%s", types_buf);
b5dc0163 723 }
17a52670 724 }
fd978bf7
JS
725 if (state->acquired_refs && state->refs[0].id) {
726 verbose(env, " refs=%d", state->refs[0].id);
727 for (i = 1; i < state->acquired_refs; i++)
728 if (state->refs[i].id)
729 verbose(env, ",%d", state->refs[i].id);
730 }
61bd5218 731 verbose(env, "\n");
17a52670
AS
732}
733
84dbf350
JS
734#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
735static int copy_##NAME##_state(struct bpf_func_state *dst, \
736 const struct bpf_func_state *src) \
737{ \
738 if (!src->FIELD) \
739 return 0; \
740 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
741 /* internal bug, make state invalid to reject the program */ \
742 memset(dst, 0, sizeof(*dst)); \
743 return -EFAULT; \
744 } \
745 memcpy(dst->FIELD, src->FIELD, \
746 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
747 return 0; \
638f5b90 748}
fd978bf7
JS
749/* copy_reference_state() */
750COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
751/* copy_stack_state() */
752COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
753#undef COPY_STATE_FN
754
755#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
756static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
757 bool copy_old) \
758{ \
759 u32 old_size = state->COUNT; \
760 struct bpf_##NAME##_state *new_##FIELD; \
761 int slot = size / SIZE; \
762 \
763 if (size <= old_size || !size) { \
764 if (copy_old) \
765 return 0; \
766 state->COUNT = slot * SIZE; \
767 if (!size && old_size) { \
768 kfree(state->FIELD); \
769 state->FIELD = NULL; \
770 } \
771 return 0; \
772 } \
773 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
774 GFP_KERNEL); \
775 if (!new_##FIELD) \
776 return -ENOMEM; \
777 if (copy_old) { \
778 if (state->FIELD) \
779 memcpy(new_##FIELD, state->FIELD, \
780 sizeof(*new_##FIELD) * (old_size / SIZE)); \
781 memset(new_##FIELD + old_size / SIZE, 0, \
782 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
783 } \
784 state->COUNT = slot * SIZE; \
785 kfree(state->FIELD); \
786 state->FIELD = new_##FIELD; \
787 return 0; \
788}
fd978bf7
JS
789/* realloc_reference_state() */
790REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
791/* realloc_stack_state() */
792REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
793#undef REALLOC_STATE_FN
638f5b90
AS
794
795/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
796 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 797 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
798 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
799 * which realloc_stack_state() copies over. It points to previous
800 * bpf_verifier_state which is never reallocated.
638f5b90 801 */
fd978bf7
JS
802static int realloc_func_state(struct bpf_func_state *state, int stack_size,
803 int refs_size, bool copy_old)
638f5b90 804{
fd978bf7
JS
805 int err = realloc_reference_state(state, refs_size, copy_old);
806 if (err)
807 return err;
808 return realloc_stack_state(state, stack_size, copy_old);
809}
810
811/* Acquire a pointer id from the env and update the state->refs to include
812 * this new pointer reference.
813 * On success, returns a valid pointer id to associate with the register
814 * On failure, returns a negative errno.
638f5b90 815 */
fd978bf7 816static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 817{
fd978bf7
JS
818 struct bpf_func_state *state = cur_func(env);
819 int new_ofs = state->acquired_refs;
820 int id, err;
821
822 err = realloc_reference_state(state, state->acquired_refs + 1, true);
823 if (err)
824 return err;
825 id = ++env->id_gen;
826 state->refs[new_ofs].id = id;
827 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 828
fd978bf7
JS
829 return id;
830}
831
832/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 833static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
834{
835 int i, last_idx;
836
fd978bf7
JS
837 last_idx = state->acquired_refs - 1;
838 for (i = 0; i < state->acquired_refs; i++) {
839 if (state->refs[i].id == ptr_id) {
840 if (last_idx && i != last_idx)
841 memcpy(&state->refs[i], &state->refs[last_idx],
842 sizeof(*state->refs));
843 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
844 state->acquired_refs--;
638f5b90 845 return 0;
638f5b90 846 }
638f5b90 847 }
46f8bc92 848 return -EINVAL;
fd978bf7
JS
849}
850
851static int transfer_reference_state(struct bpf_func_state *dst,
852 struct bpf_func_state *src)
853{
854 int err = realloc_reference_state(dst, src->acquired_refs, false);
855 if (err)
856 return err;
857 err = copy_reference_state(dst, src);
858 if (err)
859 return err;
638f5b90
AS
860 return 0;
861}
862
f4d7e40a
AS
863static void free_func_state(struct bpf_func_state *state)
864{
5896351e
AS
865 if (!state)
866 return;
fd978bf7 867 kfree(state->refs);
f4d7e40a
AS
868 kfree(state->stack);
869 kfree(state);
870}
871
b5dc0163
AS
872static void clear_jmp_history(struct bpf_verifier_state *state)
873{
874 kfree(state->jmp_history);
875 state->jmp_history = NULL;
876 state->jmp_history_cnt = 0;
877}
878
1969db47
AS
879static void free_verifier_state(struct bpf_verifier_state *state,
880 bool free_self)
638f5b90 881{
f4d7e40a
AS
882 int i;
883
884 for (i = 0; i <= state->curframe; i++) {
885 free_func_state(state->frame[i]);
886 state->frame[i] = NULL;
887 }
b5dc0163 888 clear_jmp_history(state);
1969db47
AS
889 if (free_self)
890 kfree(state);
638f5b90
AS
891}
892
893/* copy verifier state from src to dst growing dst stack space
894 * when necessary to accommodate larger src stack
895 */
f4d7e40a
AS
896static int copy_func_state(struct bpf_func_state *dst,
897 const struct bpf_func_state *src)
638f5b90
AS
898{
899 int err;
900
fd978bf7
JS
901 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
902 false);
903 if (err)
904 return err;
905 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
906 err = copy_reference_state(dst, src);
638f5b90
AS
907 if (err)
908 return err;
638f5b90
AS
909 return copy_stack_state(dst, src);
910}
911
f4d7e40a
AS
912static int copy_verifier_state(struct bpf_verifier_state *dst_state,
913 const struct bpf_verifier_state *src)
914{
915 struct bpf_func_state *dst;
b5dc0163 916 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
917 int i, err;
918
b5dc0163
AS
919 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
920 kfree(dst_state->jmp_history);
921 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
922 if (!dst_state->jmp_history)
923 return -ENOMEM;
924 }
925 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
926 dst_state->jmp_history_cnt = src->jmp_history_cnt;
927
f4d7e40a
AS
928 /* if dst has more stack frames then src frame, free them */
929 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
930 free_func_state(dst_state->frame[i]);
931 dst_state->frame[i] = NULL;
932 }
979d63d5 933 dst_state->speculative = src->speculative;
f4d7e40a 934 dst_state->curframe = src->curframe;
d83525ca 935 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
936 dst_state->branches = src->branches;
937 dst_state->parent = src->parent;
b5dc0163
AS
938 dst_state->first_insn_idx = src->first_insn_idx;
939 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
940 for (i = 0; i <= src->curframe; i++) {
941 dst = dst_state->frame[i];
942 if (!dst) {
943 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
944 if (!dst)
945 return -ENOMEM;
946 dst_state->frame[i] = dst;
947 }
948 err = copy_func_state(dst, src->frame[i]);
949 if (err)
950 return err;
951 }
952 return 0;
953}
954
2589726d
AS
955static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
956{
957 while (st) {
958 u32 br = --st->branches;
959
960 /* WARN_ON(br > 1) technically makes sense here,
961 * but see comment in push_stack(), hence:
962 */
963 WARN_ONCE((int)br < 0,
964 "BUG update_branch_counts:branches_to_explore=%d\n",
965 br);
966 if (br)
967 break;
968 st = st->parent;
969 }
970}
971
638f5b90 972static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 973 int *insn_idx, bool pop_log)
638f5b90
AS
974{
975 struct bpf_verifier_state *cur = env->cur_state;
976 struct bpf_verifier_stack_elem *elem, *head = env->head;
977 int err;
17a52670
AS
978
979 if (env->head == NULL)
638f5b90 980 return -ENOENT;
17a52670 981
638f5b90
AS
982 if (cur) {
983 err = copy_verifier_state(cur, &head->st);
984 if (err)
985 return err;
986 }
6f8a57cc
AN
987 if (pop_log)
988 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
989 if (insn_idx)
990 *insn_idx = head->insn_idx;
17a52670 991 if (prev_insn_idx)
638f5b90
AS
992 *prev_insn_idx = head->prev_insn_idx;
993 elem = head->next;
1969db47 994 free_verifier_state(&head->st, false);
638f5b90 995 kfree(head);
17a52670
AS
996 env->head = elem;
997 env->stack_size--;
638f5b90 998 return 0;
17a52670
AS
999}
1000
58e2af8b 1001static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1002 int insn_idx, int prev_insn_idx,
1003 bool speculative)
17a52670 1004{
638f5b90 1005 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1006 struct bpf_verifier_stack_elem *elem;
638f5b90 1007 int err;
17a52670 1008
638f5b90 1009 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1010 if (!elem)
1011 goto err;
1012
17a52670
AS
1013 elem->insn_idx = insn_idx;
1014 elem->prev_insn_idx = prev_insn_idx;
1015 elem->next = env->head;
6f8a57cc 1016 elem->log_pos = env->log.len_used;
17a52670
AS
1017 env->head = elem;
1018 env->stack_size++;
1969db47
AS
1019 err = copy_verifier_state(&elem->st, cur);
1020 if (err)
1021 goto err;
979d63d5 1022 elem->st.speculative |= speculative;
b285fcb7
AS
1023 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1024 verbose(env, "The sequence of %d jumps is too complex.\n",
1025 env->stack_size);
17a52670
AS
1026 goto err;
1027 }
2589726d
AS
1028 if (elem->st.parent) {
1029 ++elem->st.parent->branches;
1030 /* WARN_ON(branches > 2) technically makes sense here,
1031 * but
1032 * 1. speculative states will bump 'branches' for non-branch
1033 * instructions
1034 * 2. is_state_visited() heuristics may decide not to create
1035 * a new state for a sequence of branches and all such current
1036 * and cloned states will be pointing to a single parent state
1037 * which might have large 'branches' count.
1038 */
1039 }
17a52670
AS
1040 return &elem->st;
1041err:
5896351e
AS
1042 free_verifier_state(env->cur_state, true);
1043 env->cur_state = NULL;
17a52670 1044 /* pop all elements and return */
6f8a57cc 1045 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1046 return NULL;
1047}
1048
1049#define CALLER_SAVED_REGS 6
1050static const int caller_saved[CALLER_SAVED_REGS] = {
1051 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1052};
1053
f54c7898
DB
1054static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1055 struct bpf_reg_state *reg);
f1174f77 1056
e688c3db
AS
1057/* This helper doesn't clear reg->id */
1058static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1059{
b03c9f9f
EC
1060 reg->var_off = tnum_const(imm);
1061 reg->smin_value = (s64)imm;
1062 reg->smax_value = (s64)imm;
1063 reg->umin_value = imm;
1064 reg->umax_value = imm;
3f50f132
JF
1065
1066 reg->s32_min_value = (s32)imm;
1067 reg->s32_max_value = (s32)imm;
1068 reg->u32_min_value = (u32)imm;
1069 reg->u32_max_value = (u32)imm;
1070}
1071
e688c3db
AS
1072/* Mark the unknown part of a register (variable offset or scalar value) as
1073 * known to have the value @imm.
1074 */
1075static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1076{
1077 /* Clear id, off, and union(map_ptr, range) */
1078 memset(((u8 *)reg) + sizeof(reg->type), 0,
1079 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1080 ___mark_reg_known(reg, imm);
1081}
1082
3f50f132
JF
1083static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1084{
1085 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1086 reg->s32_min_value = (s32)imm;
1087 reg->s32_max_value = (s32)imm;
1088 reg->u32_min_value = (u32)imm;
1089 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1090}
1091
f1174f77
EC
1092/* Mark the 'variable offset' part of a register as zero. This should be
1093 * used only on registers holding a pointer type.
1094 */
1095static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1096{
b03c9f9f 1097 __mark_reg_known(reg, 0);
f1174f77 1098}
a9789ef9 1099
cc2b14d5
AS
1100static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1101{
1102 __mark_reg_known(reg, 0);
cc2b14d5
AS
1103 reg->type = SCALAR_VALUE;
1104}
1105
61bd5218
JK
1106static void mark_reg_known_zero(struct bpf_verifier_env *env,
1107 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1108{
1109 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1110 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1111 /* Something bad happened, let's kill all regs */
1112 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1113 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1114 return;
1115 }
1116 __mark_reg_known_zero(regs + regno);
1117}
1118
4ddb7416
DB
1119static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1120{
1121 switch (reg->type) {
1122 case PTR_TO_MAP_VALUE_OR_NULL: {
1123 const struct bpf_map *map = reg->map_ptr;
1124
1125 if (map->inner_map_meta) {
1126 reg->type = CONST_PTR_TO_MAP;
1127 reg->map_ptr = map->inner_map_meta;
1128 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1129 reg->type = PTR_TO_XDP_SOCK;
1130 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1131 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1132 reg->type = PTR_TO_SOCKET;
1133 } else {
1134 reg->type = PTR_TO_MAP_VALUE;
1135 }
1136 break;
1137 }
1138 case PTR_TO_SOCKET_OR_NULL:
1139 reg->type = PTR_TO_SOCKET;
1140 break;
1141 case PTR_TO_SOCK_COMMON_OR_NULL:
1142 reg->type = PTR_TO_SOCK_COMMON;
1143 break;
1144 case PTR_TO_TCP_SOCK_OR_NULL:
1145 reg->type = PTR_TO_TCP_SOCK;
1146 break;
1147 case PTR_TO_BTF_ID_OR_NULL:
1148 reg->type = PTR_TO_BTF_ID;
1149 break;
1150 case PTR_TO_MEM_OR_NULL:
1151 reg->type = PTR_TO_MEM;
1152 break;
1153 case PTR_TO_RDONLY_BUF_OR_NULL:
1154 reg->type = PTR_TO_RDONLY_BUF;
1155 break;
1156 case PTR_TO_RDWR_BUF_OR_NULL:
1157 reg->type = PTR_TO_RDWR_BUF;
1158 break;
1159 default:
33ccec5f 1160 WARN_ONCE(1, "unknown nullable register type");
4ddb7416
DB
1161 }
1162}
1163
de8f3a83
DB
1164static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1165{
1166 return type_is_pkt_pointer(reg->type);
1167}
1168
1169static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1170{
1171 return reg_is_pkt_pointer(reg) ||
1172 reg->type == PTR_TO_PACKET_END;
1173}
1174
1175/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1176static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1177 enum bpf_reg_type which)
1178{
1179 /* The register can already have a range from prior markings.
1180 * This is fine as long as it hasn't been advanced from its
1181 * origin.
1182 */
1183 return reg->type == which &&
1184 reg->id == 0 &&
1185 reg->off == 0 &&
1186 tnum_equals_const(reg->var_off, 0);
1187}
1188
3f50f132
JF
1189/* Reset the min/max bounds of a register */
1190static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1191{
1192 reg->smin_value = S64_MIN;
1193 reg->smax_value = S64_MAX;
1194 reg->umin_value = 0;
1195 reg->umax_value = U64_MAX;
1196
1197 reg->s32_min_value = S32_MIN;
1198 reg->s32_max_value = S32_MAX;
1199 reg->u32_min_value = 0;
1200 reg->u32_max_value = U32_MAX;
1201}
1202
1203static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1204{
1205 reg->smin_value = S64_MIN;
1206 reg->smax_value = S64_MAX;
1207 reg->umin_value = 0;
1208 reg->umax_value = U64_MAX;
1209}
1210
1211static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1212{
1213 reg->s32_min_value = S32_MIN;
1214 reg->s32_max_value = S32_MAX;
1215 reg->u32_min_value = 0;
1216 reg->u32_max_value = U32_MAX;
1217}
1218
1219static void __update_reg32_bounds(struct bpf_reg_state *reg)
1220{
1221 struct tnum var32_off = tnum_subreg(reg->var_off);
1222
1223 /* min signed is max(sign bit) | min(other bits) */
1224 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1225 var32_off.value | (var32_off.mask & S32_MIN));
1226 /* max signed is min(sign bit) | max(other bits) */
1227 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1228 var32_off.value | (var32_off.mask & S32_MAX));
1229 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1230 reg->u32_max_value = min(reg->u32_max_value,
1231 (u32)(var32_off.value | var32_off.mask));
1232}
1233
1234static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1235{
1236 /* min signed is max(sign bit) | min(other bits) */
1237 reg->smin_value = max_t(s64, reg->smin_value,
1238 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1239 /* max signed is min(sign bit) | max(other bits) */
1240 reg->smax_value = min_t(s64, reg->smax_value,
1241 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1242 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1243 reg->umax_value = min(reg->umax_value,
1244 reg->var_off.value | reg->var_off.mask);
1245}
1246
3f50f132
JF
1247static void __update_reg_bounds(struct bpf_reg_state *reg)
1248{
1249 __update_reg32_bounds(reg);
1250 __update_reg64_bounds(reg);
1251}
1252
b03c9f9f 1253/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1254static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1255{
1256 /* Learn sign from signed bounds.
1257 * If we cannot cross the sign boundary, then signed and unsigned bounds
1258 * are the same, so combine. This works even in the negative case, e.g.
1259 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1260 */
1261 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1262 reg->s32_min_value = reg->u32_min_value =
1263 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1264 reg->s32_max_value = reg->u32_max_value =
1265 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1266 return;
1267 }
1268 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1269 * boundary, so we must be careful.
1270 */
1271 if ((s32)reg->u32_max_value >= 0) {
1272 /* Positive. We can't learn anything from the smin, but smax
1273 * is positive, hence safe.
1274 */
1275 reg->s32_min_value = reg->u32_min_value;
1276 reg->s32_max_value = reg->u32_max_value =
1277 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1278 } else if ((s32)reg->u32_min_value < 0) {
1279 /* Negative. We can't learn anything from the smax, but smin
1280 * is negative, hence safe.
1281 */
1282 reg->s32_min_value = reg->u32_min_value =
1283 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1284 reg->s32_max_value = reg->u32_max_value;
1285 }
1286}
1287
1288static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1289{
1290 /* Learn sign from signed bounds.
1291 * If we cannot cross the sign boundary, then signed and unsigned bounds
1292 * are the same, so combine. This works even in the negative case, e.g.
1293 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1294 */
1295 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1296 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1297 reg->umin_value);
1298 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1299 reg->umax_value);
1300 return;
1301 }
1302 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1303 * boundary, so we must be careful.
1304 */
1305 if ((s64)reg->umax_value >= 0) {
1306 /* Positive. We can't learn anything from the smin, but smax
1307 * is positive, hence safe.
1308 */
1309 reg->smin_value = reg->umin_value;
1310 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1311 reg->umax_value);
1312 } else if ((s64)reg->umin_value < 0) {
1313 /* Negative. We can't learn anything from the smax, but smin
1314 * is negative, hence safe.
1315 */
1316 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1317 reg->umin_value);
1318 reg->smax_value = reg->umax_value;
1319 }
1320}
1321
3f50f132
JF
1322static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1323{
1324 __reg32_deduce_bounds(reg);
1325 __reg64_deduce_bounds(reg);
1326}
1327
b03c9f9f
EC
1328/* Attempts to improve var_off based on unsigned min/max information */
1329static void __reg_bound_offset(struct bpf_reg_state *reg)
1330{
3f50f132
JF
1331 struct tnum var64_off = tnum_intersect(reg->var_off,
1332 tnum_range(reg->umin_value,
1333 reg->umax_value));
1334 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1335 tnum_range(reg->u32_min_value,
1336 reg->u32_max_value));
1337
1338 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1339}
1340
3f50f132 1341static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1342{
3f50f132
JF
1343 reg->umin_value = reg->u32_min_value;
1344 reg->umax_value = reg->u32_max_value;
1345 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1346 * but must be positive otherwise set to worse case bounds
1347 * and refine later from tnum.
1348 */
3a71dc36 1349 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1350 reg->smax_value = reg->s32_max_value;
1351 else
1352 reg->smax_value = U32_MAX;
3a71dc36
JF
1353 if (reg->s32_min_value >= 0)
1354 reg->smin_value = reg->s32_min_value;
1355 else
1356 reg->smin_value = 0;
3f50f132
JF
1357}
1358
1359static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1360{
1361 /* special case when 64-bit register has upper 32-bit register
1362 * zeroed. Typically happens after zext or <<32, >>32 sequence
1363 * allowing us to use 32-bit bounds directly,
1364 */
1365 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1366 __reg_assign_32_into_64(reg);
1367 } else {
1368 /* Otherwise the best we can do is push lower 32bit known and
1369 * unknown bits into register (var_off set from jmp logic)
1370 * then learn as much as possible from the 64-bit tnum
1371 * known and unknown bits. The previous smin/smax bounds are
1372 * invalid here because of jmp32 compare so mark them unknown
1373 * so they do not impact tnum bounds calculation.
1374 */
1375 __mark_reg64_unbounded(reg);
1376 __update_reg_bounds(reg);
1377 }
1378
1379 /* Intersecting with the old var_off might have improved our bounds
1380 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1381 * then new var_off is (0; 0x7f...fc) which improves our umax.
1382 */
1383 __reg_deduce_bounds(reg);
1384 __reg_bound_offset(reg);
1385 __update_reg_bounds(reg);
1386}
1387
1388static bool __reg64_bound_s32(s64 a)
1389{
b0270958 1390 return a > S32_MIN && a < S32_MAX;
3f50f132
JF
1391}
1392
1393static bool __reg64_bound_u32(u64 a)
1394{
1395 if (a > U32_MIN && a < U32_MAX)
1396 return true;
1397 return false;
1398}
1399
1400static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1401{
1402 __mark_reg32_unbounded(reg);
1403
b0270958 1404 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1405 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1406 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1407 }
3f50f132
JF
1408 if (__reg64_bound_u32(reg->umin_value))
1409 reg->u32_min_value = (u32)reg->umin_value;
1410 if (__reg64_bound_u32(reg->umax_value))
1411 reg->u32_max_value = (u32)reg->umax_value;
1412
1413 /* Intersecting with the old var_off might have improved our bounds
1414 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1415 * then new var_off is (0; 0x7f...fc) which improves our umax.
1416 */
1417 __reg_deduce_bounds(reg);
1418 __reg_bound_offset(reg);
1419 __update_reg_bounds(reg);
b03c9f9f
EC
1420}
1421
f1174f77 1422/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1423static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1424 struct bpf_reg_state *reg)
f1174f77 1425{
a9c676bc
AS
1426 /*
1427 * Clear type, id, off, and union(map_ptr, range) and
1428 * padding between 'type' and union
1429 */
1430 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1431 reg->type = SCALAR_VALUE;
f1174f77 1432 reg->var_off = tnum_unknown;
f4d7e40a 1433 reg->frameno = 0;
2c78ee89 1434 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1435 __mark_reg_unbounded(reg);
f1174f77
EC
1436}
1437
61bd5218
JK
1438static void mark_reg_unknown(struct bpf_verifier_env *env,
1439 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1440{
1441 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1442 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1443 /* Something bad happened, let's kill all regs except FP */
1444 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1445 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1446 return;
1447 }
f54c7898 1448 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1449}
1450
f54c7898
DB
1451static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1452 struct bpf_reg_state *reg)
f1174f77 1453{
f54c7898 1454 __mark_reg_unknown(env, reg);
f1174f77
EC
1455 reg->type = NOT_INIT;
1456}
1457
61bd5218
JK
1458static void mark_reg_not_init(struct bpf_verifier_env *env,
1459 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1460{
1461 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1462 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1463 /* Something bad happened, let's kill all regs except FP */
1464 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1465 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1466 return;
1467 }
f54c7898 1468 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1469}
1470
41c48f3a
AI
1471static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1472 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1473 enum bpf_reg_type reg_type,
1474 struct btf *btf, u32 btf_id)
41c48f3a
AI
1475{
1476 if (reg_type == SCALAR_VALUE) {
1477 mark_reg_unknown(env, regs, regno);
1478 return;
1479 }
1480 mark_reg_known_zero(env, regs, regno);
1481 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1482 regs[regno].btf = btf;
41c48f3a
AI
1483 regs[regno].btf_id = btf_id;
1484}
1485
5327ed3d 1486#define DEF_NOT_SUBREG (0)
61bd5218 1487static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1488 struct bpf_func_state *state)
17a52670 1489{
f4d7e40a 1490 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1491 int i;
1492
dc503a8a 1493 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1494 mark_reg_not_init(env, regs, i);
dc503a8a 1495 regs[i].live = REG_LIVE_NONE;
679c782d 1496 regs[i].parent = NULL;
5327ed3d 1497 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1498 }
17a52670
AS
1499
1500 /* frame pointer */
f1174f77 1501 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1502 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1503 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1504}
1505
f4d7e40a
AS
1506#define BPF_MAIN_FUNC (-1)
1507static void init_func_state(struct bpf_verifier_env *env,
1508 struct bpf_func_state *state,
1509 int callsite, int frameno, int subprogno)
1510{
1511 state->callsite = callsite;
1512 state->frameno = frameno;
1513 state->subprogno = subprogno;
1514 init_reg_state(env, state);
1515}
1516
17a52670
AS
1517enum reg_arg_type {
1518 SRC_OP, /* register is used as source operand */
1519 DST_OP, /* register is used as destination operand */
1520 DST_OP_NO_MARK /* same as above, check only, don't mark */
1521};
1522
cc8b0b92
AS
1523static int cmp_subprogs(const void *a, const void *b)
1524{
9c8105bd
JW
1525 return ((struct bpf_subprog_info *)a)->start -
1526 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1527}
1528
1529static int find_subprog(struct bpf_verifier_env *env, int off)
1530{
9c8105bd 1531 struct bpf_subprog_info *p;
cc8b0b92 1532
9c8105bd
JW
1533 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1534 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1535 if (!p)
1536 return -ENOENT;
9c8105bd 1537 return p - env->subprog_info;
cc8b0b92
AS
1538
1539}
1540
1541static int add_subprog(struct bpf_verifier_env *env, int off)
1542{
1543 int insn_cnt = env->prog->len;
1544 int ret;
1545
1546 if (off >= insn_cnt || off < 0) {
1547 verbose(env, "call to invalid destination\n");
1548 return -EINVAL;
1549 }
1550 ret = find_subprog(env, off);
1551 if (ret >= 0)
282a0f46 1552 return ret;
4cb3d99c 1553 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1554 verbose(env, "too many subprograms\n");
1555 return -E2BIG;
1556 }
9c8105bd
JW
1557 env->subprog_info[env->subprog_cnt++].start = off;
1558 sort(env->subprog_info, env->subprog_cnt,
1559 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1560 return env->subprog_cnt - 1;
cc8b0b92
AS
1561}
1562
1563static int check_subprogs(struct bpf_verifier_env *env)
1564{
1565 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1566 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1567 struct bpf_insn *insn = env->prog->insnsi;
1568 int insn_cnt = env->prog->len;
1569
f910cefa
JW
1570 /* Add entry function. */
1571 ret = add_subprog(env, 0);
1572 if (ret < 0)
1573 return ret;
1574
cc8b0b92
AS
1575 /* determine subprog starts. The end is one before the next starts */
1576 for (i = 0; i < insn_cnt; i++) {
69c087ba
YS
1577 if (bpf_pseudo_func(insn + i)) {
1578 if (!env->bpf_capable) {
1579 verbose(env,
1580 "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1581 return -EPERM;
1582 }
1583 ret = add_subprog(env, i + insn[i].imm + 1);
1584 if (ret < 0)
1585 return ret;
1586 /* remember subprog */
1587 insn[i + 1].imm = ret;
1588 continue;
1589 }
23a2d70c 1590 if (!bpf_pseudo_call(insn + i))
cc8b0b92 1591 continue;
2c78ee89
AS
1592 if (!env->bpf_capable) {
1593 verbose(env,
1594 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1595 return -EPERM;
1596 }
cc8b0b92
AS
1597 ret = add_subprog(env, i + insn[i].imm + 1);
1598 if (ret < 0)
1599 return ret;
1600 }
1601
4cb3d99c
JW
1602 /* Add a fake 'exit' subprog which could simplify subprog iteration
1603 * logic. 'subprog_cnt' should not be increased.
1604 */
1605 subprog[env->subprog_cnt].start = insn_cnt;
1606
06ee7115 1607 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1608 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1609 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1610
1611 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1612 subprog_start = subprog[cur_subprog].start;
1613 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1614 for (i = 0; i < insn_cnt; i++) {
1615 u8 code = insn[i].code;
1616
7f6e4312
MF
1617 if (code == (BPF_JMP | BPF_CALL) &&
1618 insn[i].imm == BPF_FUNC_tail_call &&
1619 insn[i].src_reg != BPF_PSEUDO_CALL)
1620 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1621 if (BPF_CLASS(code) == BPF_LD &&
1622 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1623 subprog[cur_subprog].has_ld_abs = true;
092ed096 1624 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1625 goto next;
1626 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1627 goto next;
1628 off = i + insn[i].off + 1;
1629 if (off < subprog_start || off >= subprog_end) {
1630 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1631 return -EINVAL;
1632 }
1633next:
1634 if (i == subprog_end - 1) {
1635 /* to avoid fall-through from one subprog into another
1636 * the last insn of the subprog should be either exit
1637 * or unconditional jump back
1638 */
1639 if (code != (BPF_JMP | BPF_EXIT) &&
1640 code != (BPF_JMP | BPF_JA)) {
1641 verbose(env, "last insn is not an exit or jmp\n");
1642 return -EINVAL;
1643 }
1644 subprog_start = subprog_end;
4cb3d99c
JW
1645 cur_subprog++;
1646 if (cur_subprog < env->subprog_cnt)
9c8105bd 1647 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1648 }
1649 }
1650 return 0;
1651}
1652
679c782d
EC
1653/* Parentage chain of this register (or stack slot) should take care of all
1654 * issues like callee-saved registers, stack slot allocation time, etc.
1655 */
f4d7e40a 1656static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1657 const struct bpf_reg_state *state,
5327ed3d 1658 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1659{
1660 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1661 int cnt = 0;
dc503a8a
EC
1662
1663 while (parent) {
1664 /* if read wasn't screened by an earlier write ... */
679c782d 1665 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1666 break;
9242b5f5
AS
1667 if (parent->live & REG_LIVE_DONE) {
1668 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1669 reg_type_str[parent->type],
1670 parent->var_off.value, parent->off);
1671 return -EFAULT;
1672 }
5327ed3d
JW
1673 /* The first condition is more likely to be true than the
1674 * second, checked it first.
1675 */
1676 if ((parent->live & REG_LIVE_READ) == flag ||
1677 parent->live & REG_LIVE_READ64)
25af32da
AS
1678 /* The parentage chain never changes and
1679 * this parent was already marked as LIVE_READ.
1680 * There is no need to keep walking the chain again and
1681 * keep re-marking all parents as LIVE_READ.
1682 * This case happens when the same register is read
1683 * multiple times without writes into it in-between.
5327ed3d
JW
1684 * Also, if parent has the stronger REG_LIVE_READ64 set,
1685 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1686 */
1687 break;
dc503a8a 1688 /* ... then we depend on parent's value */
5327ed3d
JW
1689 parent->live |= flag;
1690 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1691 if (flag == REG_LIVE_READ64)
1692 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1693 state = parent;
1694 parent = state->parent;
f4d7e40a 1695 writes = true;
06ee7115 1696 cnt++;
dc503a8a 1697 }
06ee7115
AS
1698
1699 if (env->longest_mark_read_walk < cnt)
1700 env->longest_mark_read_walk = cnt;
f4d7e40a 1701 return 0;
dc503a8a
EC
1702}
1703
5327ed3d
JW
1704/* This function is supposed to be used by the following 32-bit optimization
1705 * code only. It returns TRUE if the source or destination register operates
1706 * on 64-bit, otherwise return FALSE.
1707 */
1708static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1709 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1710{
1711 u8 code, class, op;
1712
1713 code = insn->code;
1714 class = BPF_CLASS(code);
1715 op = BPF_OP(code);
1716 if (class == BPF_JMP) {
1717 /* BPF_EXIT for "main" will reach here. Return TRUE
1718 * conservatively.
1719 */
1720 if (op == BPF_EXIT)
1721 return true;
1722 if (op == BPF_CALL) {
1723 /* BPF to BPF call will reach here because of marking
1724 * caller saved clobber with DST_OP_NO_MARK for which we
1725 * don't care the register def because they are anyway
1726 * marked as NOT_INIT already.
1727 */
1728 if (insn->src_reg == BPF_PSEUDO_CALL)
1729 return false;
1730 /* Helper call will reach here because of arg type
1731 * check, conservatively return TRUE.
1732 */
1733 if (t == SRC_OP)
1734 return true;
1735
1736 return false;
1737 }
1738 }
1739
1740 if (class == BPF_ALU64 || class == BPF_JMP ||
1741 /* BPF_END always use BPF_ALU class. */
1742 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1743 return true;
1744
1745 if (class == BPF_ALU || class == BPF_JMP32)
1746 return false;
1747
1748 if (class == BPF_LDX) {
1749 if (t != SRC_OP)
1750 return BPF_SIZE(code) == BPF_DW;
1751 /* LDX source must be ptr. */
1752 return true;
1753 }
1754
1755 if (class == BPF_STX) {
83a28819
IL
1756 /* BPF_STX (including atomic variants) has multiple source
1757 * operands, one of which is a ptr. Check whether the caller is
1758 * asking about it.
1759 */
1760 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
1761 return true;
1762 return BPF_SIZE(code) == BPF_DW;
1763 }
1764
1765 if (class == BPF_LD) {
1766 u8 mode = BPF_MODE(code);
1767
1768 /* LD_IMM64 */
1769 if (mode == BPF_IMM)
1770 return true;
1771
1772 /* Both LD_IND and LD_ABS return 32-bit data. */
1773 if (t != SRC_OP)
1774 return false;
1775
1776 /* Implicit ctx ptr. */
1777 if (regno == BPF_REG_6)
1778 return true;
1779
1780 /* Explicit source could be any width. */
1781 return true;
1782 }
1783
1784 if (class == BPF_ST)
1785 /* The only source register for BPF_ST is a ptr. */
1786 return true;
1787
1788 /* Conservatively return true at default. */
1789 return true;
1790}
1791
83a28819
IL
1792/* Return the regno defined by the insn, or -1. */
1793static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 1794{
83a28819
IL
1795 switch (BPF_CLASS(insn->code)) {
1796 case BPF_JMP:
1797 case BPF_JMP32:
1798 case BPF_ST:
1799 return -1;
1800 case BPF_STX:
1801 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1802 (insn->imm & BPF_FETCH)) {
1803 if (insn->imm == BPF_CMPXCHG)
1804 return BPF_REG_0;
1805 else
1806 return insn->src_reg;
1807 } else {
1808 return -1;
1809 }
1810 default:
1811 return insn->dst_reg;
1812 }
b325fbca
JW
1813}
1814
1815/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1816static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1817{
83a28819
IL
1818 int dst_reg = insn_def_regno(insn);
1819
1820 if (dst_reg == -1)
b325fbca
JW
1821 return false;
1822
83a28819 1823 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
1824}
1825
5327ed3d
JW
1826static void mark_insn_zext(struct bpf_verifier_env *env,
1827 struct bpf_reg_state *reg)
1828{
1829 s32 def_idx = reg->subreg_def;
1830
1831 if (def_idx == DEF_NOT_SUBREG)
1832 return;
1833
1834 env->insn_aux_data[def_idx - 1].zext_dst = true;
1835 /* The dst will be zero extended, so won't be sub-register anymore. */
1836 reg->subreg_def = DEF_NOT_SUBREG;
1837}
1838
dc503a8a 1839static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1840 enum reg_arg_type t)
1841{
f4d7e40a
AS
1842 struct bpf_verifier_state *vstate = env->cur_state;
1843 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1844 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1845 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1846 bool rw64;
dc503a8a 1847
17a52670 1848 if (regno >= MAX_BPF_REG) {
61bd5218 1849 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1850 return -EINVAL;
1851 }
1852
c342dc10 1853 reg = &regs[regno];
5327ed3d 1854 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1855 if (t == SRC_OP) {
1856 /* check whether register used as source operand can be read */
c342dc10 1857 if (reg->type == NOT_INIT) {
61bd5218 1858 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1859 return -EACCES;
1860 }
679c782d 1861 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1862 if (regno == BPF_REG_FP)
1863 return 0;
1864
5327ed3d
JW
1865 if (rw64)
1866 mark_insn_zext(env, reg);
1867
1868 return mark_reg_read(env, reg, reg->parent,
1869 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1870 } else {
1871 /* check whether register used as dest operand can be written to */
1872 if (regno == BPF_REG_FP) {
61bd5218 1873 verbose(env, "frame pointer is read only\n");
17a52670
AS
1874 return -EACCES;
1875 }
c342dc10 1876 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1877 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1878 if (t == DST_OP)
61bd5218 1879 mark_reg_unknown(env, regs, regno);
17a52670
AS
1880 }
1881 return 0;
1882}
1883
b5dc0163
AS
1884/* for any branch, call, exit record the history of jmps in the given state */
1885static int push_jmp_history(struct bpf_verifier_env *env,
1886 struct bpf_verifier_state *cur)
1887{
1888 u32 cnt = cur->jmp_history_cnt;
1889 struct bpf_idx_pair *p;
1890
1891 cnt++;
1892 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1893 if (!p)
1894 return -ENOMEM;
1895 p[cnt - 1].idx = env->insn_idx;
1896 p[cnt - 1].prev_idx = env->prev_insn_idx;
1897 cur->jmp_history = p;
1898 cur->jmp_history_cnt = cnt;
1899 return 0;
1900}
1901
1902/* Backtrack one insn at a time. If idx is not at the top of recorded
1903 * history then previous instruction came from straight line execution.
1904 */
1905static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1906 u32 *history)
1907{
1908 u32 cnt = *history;
1909
1910 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1911 i = st->jmp_history[cnt - 1].prev_idx;
1912 (*history)--;
1913 } else {
1914 i--;
1915 }
1916 return i;
1917}
1918
1919/* For given verifier state backtrack_insn() is called from the last insn to
1920 * the first insn. Its purpose is to compute a bitmask of registers and
1921 * stack slots that needs precision in the parent verifier state.
1922 */
1923static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1924 u32 *reg_mask, u64 *stack_mask)
1925{
1926 const struct bpf_insn_cbs cbs = {
1927 .cb_print = verbose,
1928 .private_data = env,
1929 };
1930 struct bpf_insn *insn = env->prog->insnsi + idx;
1931 u8 class = BPF_CLASS(insn->code);
1932 u8 opcode = BPF_OP(insn->code);
1933 u8 mode = BPF_MODE(insn->code);
1934 u32 dreg = 1u << insn->dst_reg;
1935 u32 sreg = 1u << insn->src_reg;
1936 u32 spi;
1937
1938 if (insn->code == 0)
1939 return 0;
1940 if (env->log.level & BPF_LOG_LEVEL) {
1941 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1942 verbose(env, "%d: ", idx);
1943 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1944 }
1945
1946 if (class == BPF_ALU || class == BPF_ALU64) {
1947 if (!(*reg_mask & dreg))
1948 return 0;
1949 if (opcode == BPF_MOV) {
1950 if (BPF_SRC(insn->code) == BPF_X) {
1951 /* dreg = sreg
1952 * dreg needs precision after this insn
1953 * sreg needs precision before this insn
1954 */
1955 *reg_mask &= ~dreg;
1956 *reg_mask |= sreg;
1957 } else {
1958 /* dreg = K
1959 * dreg needs precision after this insn.
1960 * Corresponding register is already marked
1961 * as precise=true in this verifier state.
1962 * No further markings in parent are necessary
1963 */
1964 *reg_mask &= ~dreg;
1965 }
1966 } else {
1967 if (BPF_SRC(insn->code) == BPF_X) {
1968 /* dreg += sreg
1969 * both dreg and sreg need precision
1970 * before this insn
1971 */
1972 *reg_mask |= sreg;
1973 } /* else dreg += K
1974 * dreg still needs precision before this insn
1975 */
1976 }
1977 } else if (class == BPF_LDX) {
1978 if (!(*reg_mask & dreg))
1979 return 0;
1980 *reg_mask &= ~dreg;
1981
1982 /* scalars can only be spilled into stack w/o losing precision.
1983 * Load from any other memory can be zero extended.
1984 * The desire to keep that precision is already indicated
1985 * by 'precise' mark in corresponding register of this state.
1986 * No further tracking necessary.
1987 */
1988 if (insn->src_reg != BPF_REG_FP)
1989 return 0;
1990 if (BPF_SIZE(insn->code) != BPF_DW)
1991 return 0;
1992
1993 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1994 * that [fp - off] slot contains scalar that needs to be
1995 * tracked with precision
1996 */
1997 spi = (-insn->off - 1) / BPF_REG_SIZE;
1998 if (spi >= 64) {
1999 verbose(env, "BUG spi %d\n", spi);
2000 WARN_ONCE(1, "verifier backtracking bug");
2001 return -EFAULT;
2002 }
2003 *stack_mask |= 1ull << spi;
b3b50f05 2004 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2005 if (*reg_mask & dreg)
b3b50f05 2006 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2007 * to access memory. It means backtracking
2008 * encountered a case of pointer subtraction.
2009 */
2010 return -ENOTSUPP;
2011 /* scalars can only be spilled into stack */
2012 if (insn->dst_reg != BPF_REG_FP)
2013 return 0;
2014 if (BPF_SIZE(insn->code) != BPF_DW)
2015 return 0;
2016 spi = (-insn->off - 1) / BPF_REG_SIZE;
2017 if (spi >= 64) {
2018 verbose(env, "BUG spi %d\n", spi);
2019 WARN_ONCE(1, "verifier backtracking bug");
2020 return -EFAULT;
2021 }
2022 if (!(*stack_mask & (1ull << spi)))
2023 return 0;
2024 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2025 if (class == BPF_STX)
2026 *reg_mask |= sreg;
b5dc0163
AS
2027 } else if (class == BPF_JMP || class == BPF_JMP32) {
2028 if (opcode == BPF_CALL) {
2029 if (insn->src_reg == BPF_PSEUDO_CALL)
2030 return -ENOTSUPP;
2031 /* regular helper call sets R0 */
2032 *reg_mask &= ~1;
2033 if (*reg_mask & 0x3f) {
2034 /* if backtracing was looking for registers R1-R5
2035 * they should have been found already.
2036 */
2037 verbose(env, "BUG regs %x\n", *reg_mask);
2038 WARN_ONCE(1, "verifier backtracking bug");
2039 return -EFAULT;
2040 }
2041 } else if (opcode == BPF_EXIT) {
2042 return -ENOTSUPP;
2043 }
2044 } else if (class == BPF_LD) {
2045 if (!(*reg_mask & dreg))
2046 return 0;
2047 *reg_mask &= ~dreg;
2048 /* It's ld_imm64 or ld_abs or ld_ind.
2049 * For ld_imm64 no further tracking of precision
2050 * into parent is necessary
2051 */
2052 if (mode == BPF_IND || mode == BPF_ABS)
2053 /* to be analyzed */
2054 return -ENOTSUPP;
b5dc0163
AS
2055 }
2056 return 0;
2057}
2058
2059/* the scalar precision tracking algorithm:
2060 * . at the start all registers have precise=false.
2061 * . scalar ranges are tracked as normal through alu and jmp insns.
2062 * . once precise value of the scalar register is used in:
2063 * . ptr + scalar alu
2064 * . if (scalar cond K|scalar)
2065 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2066 * backtrack through the verifier states and mark all registers and
2067 * stack slots with spilled constants that these scalar regisers
2068 * should be precise.
2069 * . during state pruning two registers (or spilled stack slots)
2070 * are equivalent if both are not precise.
2071 *
2072 * Note the verifier cannot simply walk register parentage chain,
2073 * since many different registers and stack slots could have been
2074 * used to compute single precise scalar.
2075 *
2076 * The approach of starting with precise=true for all registers and then
2077 * backtrack to mark a register as not precise when the verifier detects
2078 * that program doesn't care about specific value (e.g., when helper
2079 * takes register as ARG_ANYTHING parameter) is not safe.
2080 *
2081 * It's ok to walk single parentage chain of the verifier states.
2082 * It's possible that this backtracking will go all the way till 1st insn.
2083 * All other branches will be explored for needing precision later.
2084 *
2085 * The backtracking needs to deal with cases like:
2086 * 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)
2087 * r9 -= r8
2088 * r5 = r9
2089 * if r5 > 0x79f goto pc+7
2090 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2091 * r5 += 1
2092 * ...
2093 * call bpf_perf_event_output#25
2094 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2095 *
2096 * and this case:
2097 * r6 = 1
2098 * call foo // uses callee's r6 inside to compute r0
2099 * r0 += r6
2100 * if r0 == 0 goto
2101 *
2102 * to track above reg_mask/stack_mask needs to be independent for each frame.
2103 *
2104 * Also if parent's curframe > frame where backtracking started,
2105 * the verifier need to mark registers in both frames, otherwise callees
2106 * may incorrectly prune callers. This is similar to
2107 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2108 *
2109 * For now backtracking falls back into conservative marking.
2110 */
2111static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2112 struct bpf_verifier_state *st)
2113{
2114 struct bpf_func_state *func;
2115 struct bpf_reg_state *reg;
2116 int i, j;
2117
2118 /* big hammer: mark all scalars precise in this path.
2119 * pop_stack may still get !precise scalars.
2120 */
2121 for (; st; st = st->parent)
2122 for (i = 0; i <= st->curframe; i++) {
2123 func = st->frame[i];
2124 for (j = 0; j < BPF_REG_FP; j++) {
2125 reg = &func->regs[j];
2126 if (reg->type != SCALAR_VALUE)
2127 continue;
2128 reg->precise = true;
2129 }
2130 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2131 if (func->stack[j].slot_type[0] != STACK_SPILL)
2132 continue;
2133 reg = &func->stack[j].spilled_ptr;
2134 if (reg->type != SCALAR_VALUE)
2135 continue;
2136 reg->precise = true;
2137 }
2138 }
2139}
2140
a3ce685d
AS
2141static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2142 int spi)
b5dc0163
AS
2143{
2144 struct bpf_verifier_state *st = env->cur_state;
2145 int first_idx = st->first_insn_idx;
2146 int last_idx = env->insn_idx;
2147 struct bpf_func_state *func;
2148 struct bpf_reg_state *reg;
a3ce685d
AS
2149 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2150 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2151 bool skip_first = true;
a3ce685d 2152 bool new_marks = false;
b5dc0163
AS
2153 int i, err;
2154
2c78ee89 2155 if (!env->bpf_capable)
b5dc0163
AS
2156 return 0;
2157
2158 func = st->frame[st->curframe];
a3ce685d
AS
2159 if (regno >= 0) {
2160 reg = &func->regs[regno];
2161 if (reg->type != SCALAR_VALUE) {
2162 WARN_ONCE(1, "backtracing misuse");
2163 return -EFAULT;
2164 }
2165 if (!reg->precise)
2166 new_marks = true;
2167 else
2168 reg_mask = 0;
2169 reg->precise = true;
b5dc0163 2170 }
b5dc0163 2171
a3ce685d
AS
2172 while (spi >= 0) {
2173 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2174 stack_mask = 0;
2175 break;
2176 }
2177 reg = &func->stack[spi].spilled_ptr;
2178 if (reg->type != SCALAR_VALUE) {
2179 stack_mask = 0;
2180 break;
2181 }
2182 if (!reg->precise)
2183 new_marks = true;
2184 else
2185 stack_mask = 0;
2186 reg->precise = true;
2187 break;
2188 }
2189
2190 if (!new_marks)
2191 return 0;
2192 if (!reg_mask && !stack_mask)
2193 return 0;
b5dc0163
AS
2194 for (;;) {
2195 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2196 u32 history = st->jmp_history_cnt;
2197
2198 if (env->log.level & BPF_LOG_LEVEL)
2199 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2200 for (i = last_idx;;) {
2201 if (skip_first) {
2202 err = 0;
2203 skip_first = false;
2204 } else {
2205 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2206 }
2207 if (err == -ENOTSUPP) {
2208 mark_all_scalars_precise(env, st);
2209 return 0;
2210 } else if (err) {
2211 return err;
2212 }
2213 if (!reg_mask && !stack_mask)
2214 /* Found assignment(s) into tracked register in this state.
2215 * Since this state is already marked, just return.
2216 * Nothing to be tracked further in the parent state.
2217 */
2218 return 0;
2219 if (i == first_idx)
2220 break;
2221 i = get_prev_insn_idx(st, i, &history);
2222 if (i >= env->prog->len) {
2223 /* This can happen if backtracking reached insn 0
2224 * and there are still reg_mask or stack_mask
2225 * to backtrack.
2226 * It means the backtracking missed the spot where
2227 * particular register was initialized with a constant.
2228 */
2229 verbose(env, "BUG backtracking idx %d\n", i);
2230 WARN_ONCE(1, "verifier backtracking bug");
2231 return -EFAULT;
2232 }
2233 }
2234 st = st->parent;
2235 if (!st)
2236 break;
2237
a3ce685d 2238 new_marks = false;
b5dc0163
AS
2239 func = st->frame[st->curframe];
2240 bitmap_from_u64(mask, reg_mask);
2241 for_each_set_bit(i, mask, 32) {
2242 reg = &func->regs[i];
a3ce685d
AS
2243 if (reg->type != SCALAR_VALUE) {
2244 reg_mask &= ~(1u << i);
b5dc0163 2245 continue;
a3ce685d 2246 }
b5dc0163
AS
2247 if (!reg->precise)
2248 new_marks = true;
2249 reg->precise = true;
2250 }
2251
2252 bitmap_from_u64(mask, stack_mask);
2253 for_each_set_bit(i, mask, 64) {
2254 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2255 /* the sequence of instructions:
2256 * 2: (bf) r3 = r10
2257 * 3: (7b) *(u64 *)(r3 -8) = r0
2258 * 4: (79) r4 = *(u64 *)(r10 -8)
2259 * doesn't contain jmps. It's backtracked
2260 * as a single block.
2261 * During backtracking insn 3 is not recognized as
2262 * stack access, so at the end of backtracking
2263 * stack slot fp-8 is still marked in stack_mask.
2264 * However the parent state may not have accessed
2265 * fp-8 and it's "unallocated" stack space.
2266 * In such case fallback to conservative.
b5dc0163 2267 */
2339cd6c
AS
2268 mark_all_scalars_precise(env, st);
2269 return 0;
b5dc0163
AS
2270 }
2271
a3ce685d
AS
2272 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2273 stack_mask &= ~(1ull << i);
b5dc0163 2274 continue;
a3ce685d 2275 }
b5dc0163 2276 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2277 if (reg->type != SCALAR_VALUE) {
2278 stack_mask &= ~(1ull << i);
b5dc0163 2279 continue;
a3ce685d 2280 }
b5dc0163
AS
2281 if (!reg->precise)
2282 new_marks = true;
2283 reg->precise = true;
2284 }
2285 if (env->log.level & BPF_LOG_LEVEL) {
2286 print_verifier_state(env, func);
2287 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2288 new_marks ? "didn't have" : "already had",
2289 reg_mask, stack_mask);
2290 }
2291
a3ce685d
AS
2292 if (!reg_mask && !stack_mask)
2293 break;
b5dc0163
AS
2294 if (!new_marks)
2295 break;
2296
2297 last_idx = st->last_insn_idx;
2298 first_idx = st->first_insn_idx;
2299 }
2300 return 0;
2301}
2302
a3ce685d
AS
2303static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2304{
2305 return __mark_chain_precision(env, regno, -1);
2306}
2307
2308static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2309{
2310 return __mark_chain_precision(env, -1, spi);
2311}
b5dc0163 2312
1be7f75d
AS
2313static bool is_spillable_regtype(enum bpf_reg_type type)
2314{
2315 switch (type) {
2316 case PTR_TO_MAP_VALUE:
2317 case PTR_TO_MAP_VALUE_OR_NULL:
2318 case PTR_TO_STACK:
2319 case PTR_TO_CTX:
969bf05e 2320 case PTR_TO_PACKET:
de8f3a83 2321 case PTR_TO_PACKET_META:
969bf05e 2322 case PTR_TO_PACKET_END:
d58e468b 2323 case PTR_TO_FLOW_KEYS:
1be7f75d 2324 case CONST_PTR_TO_MAP:
c64b7983
JS
2325 case PTR_TO_SOCKET:
2326 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2327 case PTR_TO_SOCK_COMMON:
2328 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2329 case PTR_TO_TCP_SOCK:
2330 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2331 case PTR_TO_XDP_SOCK:
65726b5b 2332 case PTR_TO_BTF_ID:
b121b341 2333 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2334 case PTR_TO_RDONLY_BUF:
2335 case PTR_TO_RDONLY_BUF_OR_NULL:
2336 case PTR_TO_RDWR_BUF:
2337 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2338 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2339 case PTR_TO_MEM:
2340 case PTR_TO_MEM_OR_NULL:
69c087ba
YS
2341 case PTR_TO_FUNC:
2342 case PTR_TO_MAP_KEY:
1be7f75d
AS
2343 return true;
2344 default:
2345 return false;
2346 }
2347}
2348
cc2b14d5
AS
2349/* Does this register contain a constant zero? */
2350static bool register_is_null(struct bpf_reg_state *reg)
2351{
2352 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2353}
2354
f7cf25b2
AS
2355static bool register_is_const(struct bpf_reg_state *reg)
2356{
2357 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2358}
2359
5689d49b
YS
2360static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2361{
2362 return tnum_is_unknown(reg->var_off) &&
2363 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2364 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2365 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2366 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2367}
2368
2369static bool register_is_bounded(struct bpf_reg_state *reg)
2370{
2371 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2372}
2373
6e7e63cb
JH
2374static bool __is_pointer_value(bool allow_ptr_leaks,
2375 const struct bpf_reg_state *reg)
2376{
2377 if (allow_ptr_leaks)
2378 return false;
2379
2380 return reg->type != SCALAR_VALUE;
2381}
2382
f7cf25b2
AS
2383static void save_register_state(struct bpf_func_state *state,
2384 int spi, struct bpf_reg_state *reg)
2385{
2386 int i;
2387
2388 state->stack[spi].spilled_ptr = *reg;
2389 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2390
2391 for (i = 0; i < BPF_REG_SIZE; i++)
2392 state->stack[spi].slot_type[i] = STACK_SPILL;
2393}
2394
01f810ac 2395/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2396 * stack boundary and alignment are checked in check_mem_access()
2397 */
01f810ac
AM
2398static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2399 /* stack frame we're writing to */
2400 struct bpf_func_state *state,
2401 int off, int size, int value_regno,
2402 int insn_idx)
17a52670 2403{
f4d7e40a 2404 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2405 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2406 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2407 struct bpf_reg_state *reg = NULL;
638f5b90 2408
f4d7e40a 2409 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2410 state->acquired_refs, true);
638f5b90
AS
2411 if (err)
2412 return err;
9c399760
AS
2413 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2414 * so it's aligned access and [off, off + size) are within stack limits
2415 */
638f5b90
AS
2416 if (!env->allow_ptr_leaks &&
2417 state->stack[spi].slot_type[0] == STACK_SPILL &&
2418 size != BPF_REG_SIZE) {
2419 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2420 return -EACCES;
2421 }
17a52670 2422
f4d7e40a 2423 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2424 if (value_regno >= 0)
2425 reg = &cur->regs[value_regno];
17a52670 2426
5689d49b 2427 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2428 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2429 if (dst_reg != BPF_REG_FP) {
2430 /* The backtracking logic can only recognize explicit
2431 * stack slot address like [fp - 8]. Other spill of
2432 * scalar via different register has to be conervative.
2433 * Backtrack from here and mark all registers as precise
2434 * that contributed into 'reg' being a constant.
2435 */
2436 err = mark_chain_precision(env, value_regno);
2437 if (err)
2438 return err;
2439 }
f7cf25b2
AS
2440 save_register_state(state, spi, reg);
2441 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2442 /* register containing pointer is being spilled into stack */
9c399760 2443 if (size != BPF_REG_SIZE) {
f7cf25b2 2444 verbose_linfo(env, insn_idx, "; ");
61bd5218 2445 verbose(env, "invalid size of register spill\n");
17a52670
AS
2446 return -EACCES;
2447 }
2448
f7cf25b2 2449 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2450 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2451 return -EINVAL;
2452 }
2453
2c78ee89 2454 if (!env->bypass_spec_v4) {
f7cf25b2 2455 bool sanitize = false;
17a52670 2456
f7cf25b2
AS
2457 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2458 register_is_const(&state->stack[spi].spilled_ptr))
2459 sanitize = true;
2460 for (i = 0; i < BPF_REG_SIZE; i++)
2461 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2462 sanitize = true;
2463 break;
2464 }
2465 if (sanitize) {
af86ca4e
AS
2466 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2467 int soff = (-spi - 1) * BPF_REG_SIZE;
2468
2469 /* detected reuse of integer stack slot with a pointer
2470 * which means either llvm is reusing stack slot or
2471 * an attacker is trying to exploit CVE-2018-3639
2472 * (speculative store bypass)
2473 * Have to sanitize that slot with preemptive
2474 * store of zero.
2475 */
2476 if (*poff && *poff != soff) {
2477 /* disallow programs where single insn stores
2478 * into two different stack slots, since verifier
2479 * cannot sanitize them
2480 */
2481 verbose(env,
2482 "insn %d cannot access two stack slots fp%d and fp%d",
2483 insn_idx, *poff, soff);
2484 return -EINVAL;
2485 }
2486 *poff = soff;
2487 }
af86ca4e 2488 }
f7cf25b2 2489 save_register_state(state, spi, reg);
9c399760 2490 } else {
cc2b14d5
AS
2491 u8 type = STACK_MISC;
2492
679c782d
EC
2493 /* regular write of data into stack destroys any spilled ptr */
2494 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2495 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2496 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2497 for (i = 0; i < BPF_REG_SIZE; i++)
2498 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2499
cc2b14d5
AS
2500 /* only mark the slot as written if all 8 bytes were written
2501 * otherwise read propagation may incorrectly stop too soon
2502 * when stack slots are partially written.
2503 * This heuristic means that read propagation will be
2504 * conservative, since it will add reg_live_read marks
2505 * to stack slots all the way to first state when programs
2506 * writes+reads less than 8 bytes
2507 */
2508 if (size == BPF_REG_SIZE)
2509 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2510
2511 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2512 if (reg && register_is_null(reg)) {
2513 /* backtracking doesn't work for STACK_ZERO yet. */
2514 err = mark_chain_precision(env, value_regno);
2515 if (err)
2516 return err;
cc2b14d5 2517 type = STACK_ZERO;
b5dc0163 2518 }
cc2b14d5 2519
0bae2d4d 2520 /* Mark slots affected by this stack write. */
9c399760 2521 for (i = 0; i < size; i++)
638f5b90 2522 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2523 type;
17a52670
AS
2524 }
2525 return 0;
2526}
2527
01f810ac
AM
2528/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2529 * known to contain a variable offset.
2530 * This function checks whether the write is permitted and conservatively
2531 * tracks the effects of the write, considering that each stack slot in the
2532 * dynamic range is potentially written to.
2533 *
2534 * 'off' includes 'regno->off'.
2535 * 'value_regno' can be -1, meaning that an unknown value is being written to
2536 * the stack.
2537 *
2538 * Spilled pointers in range are not marked as written because we don't know
2539 * what's going to be actually written. This means that read propagation for
2540 * future reads cannot be terminated by this write.
2541 *
2542 * For privileged programs, uninitialized stack slots are considered
2543 * initialized by this write (even though we don't know exactly what offsets
2544 * are going to be written to). The idea is that we don't want the verifier to
2545 * reject future reads that access slots written to through variable offsets.
2546 */
2547static int check_stack_write_var_off(struct bpf_verifier_env *env,
2548 /* func where register points to */
2549 struct bpf_func_state *state,
2550 int ptr_regno, int off, int size,
2551 int value_regno, int insn_idx)
2552{
2553 struct bpf_func_state *cur; /* state of the current function */
2554 int min_off, max_off;
2555 int i, err;
2556 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2557 bool writing_zero = false;
2558 /* set if the fact that we're writing a zero is used to let any
2559 * stack slots remain STACK_ZERO
2560 */
2561 bool zero_used = false;
2562
2563 cur = env->cur_state->frame[env->cur_state->curframe];
2564 ptr_reg = &cur->regs[ptr_regno];
2565 min_off = ptr_reg->smin_value + off;
2566 max_off = ptr_reg->smax_value + off + size;
2567 if (value_regno >= 0)
2568 value_reg = &cur->regs[value_regno];
2569 if (value_reg && register_is_null(value_reg))
2570 writing_zero = true;
2571
2572 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2573 state->acquired_refs, true);
2574 if (err)
2575 return err;
2576
2577
2578 /* Variable offset writes destroy any spilled pointers in range. */
2579 for (i = min_off; i < max_off; i++) {
2580 u8 new_type, *stype;
2581 int slot, spi;
2582
2583 slot = -i - 1;
2584 spi = slot / BPF_REG_SIZE;
2585 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2586
2587 if (!env->allow_ptr_leaks
2588 && *stype != NOT_INIT
2589 && *stype != SCALAR_VALUE) {
2590 /* Reject the write if there's are spilled pointers in
2591 * range. If we didn't reject here, the ptr status
2592 * would be erased below (even though not all slots are
2593 * actually overwritten), possibly opening the door to
2594 * leaks.
2595 */
2596 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2597 insn_idx, i);
2598 return -EINVAL;
2599 }
2600
2601 /* Erase all spilled pointers. */
2602 state->stack[spi].spilled_ptr.type = NOT_INIT;
2603
2604 /* Update the slot type. */
2605 new_type = STACK_MISC;
2606 if (writing_zero && *stype == STACK_ZERO) {
2607 new_type = STACK_ZERO;
2608 zero_used = true;
2609 }
2610 /* If the slot is STACK_INVALID, we check whether it's OK to
2611 * pretend that it will be initialized by this write. The slot
2612 * might not actually be written to, and so if we mark it as
2613 * initialized future reads might leak uninitialized memory.
2614 * For privileged programs, we will accept such reads to slots
2615 * that may or may not be written because, if we're reject
2616 * them, the error would be too confusing.
2617 */
2618 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2619 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2620 insn_idx, i);
2621 return -EINVAL;
2622 }
2623 *stype = new_type;
2624 }
2625 if (zero_used) {
2626 /* backtracking doesn't work for STACK_ZERO yet. */
2627 err = mark_chain_precision(env, value_regno);
2628 if (err)
2629 return err;
2630 }
2631 return 0;
2632}
2633
2634/* When register 'dst_regno' is assigned some values from stack[min_off,
2635 * max_off), we set the register's type according to the types of the
2636 * respective stack slots. If all the stack values are known to be zeros, then
2637 * so is the destination reg. Otherwise, the register is considered to be
2638 * SCALAR. This function does not deal with register filling; the caller must
2639 * ensure that all spilled registers in the stack range have been marked as
2640 * read.
2641 */
2642static void mark_reg_stack_read(struct bpf_verifier_env *env,
2643 /* func where src register points to */
2644 struct bpf_func_state *ptr_state,
2645 int min_off, int max_off, int dst_regno)
2646{
2647 struct bpf_verifier_state *vstate = env->cur_state;
2648 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2649 int i, slot, spi;
2650 u8 *stype;
2651 int zeros = 0;
2652
2653 for (i = min_off; i < max_off; i++) {
2654 slot = -i - 1;
2655 spi = slot / BPF_REG_SIZE;
2656 stype = ptr_state->stack[spi].slot_type;
2657 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2658 break;
2659 zeros++;
2660 }
2661 if (zeros == max_off - min_off) {
2662 /* any access_size read into register is zero extended,
2663 * so the whole register == const_zero
2664 */
2665 __mark_reg_const_zero(&state->regs[dst_regno]);
2666 /* backtracking doesn't support STACK_ZERO yet,
2667 * so mark it precise here, so that later
2668 * backtracking can stop here.
2669 * Backtracking may not need this if this register
2670 * doesn't participate in pointer adjustment.
2671 * Forward propagation of precise flag is not
2672 * necessary either. This mark is only to stop
2673 * backtracking. Any register that contributed
2674 * to const 0 was marked precise before spill.
2675 */
2676 state->regs[dst_regno].precise = true;
2677 } else {
2678 /* have read misc data from the stack */
2679 mark_reg_unknown(env, state->regs, dst_regno);
2680 }
2681 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2682}
2683
2684/* Read the stack at 'off' and put the results into the register indicated by
2685 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2686 * spilled reg.
2687 *
2688 * 'dst_regno' can be -1, meaning that the read value is not going to a
2689 * register.
2690 *
2691 * The access is assumed to be within the current stack bounds.
2692 */
2693static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2694 /* func where src register points to */
2695 struct bpf_func_state *reg_state,
2696 int off, int size, int dst_regno)
17a52670 2697{
f4d7e40a
AS
2698 struct bpf_verifier_state *vstate = env->cur_state;
2699 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2700 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2701 struct bpf_reg_state *reg;
638f5b90 2702 u8 *stype;
17a52670 2703
f4d7e40a 2704 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2705 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2706
638f5b90 2707 if (stype[0] == STACK_SPILL) {
9c399760 2708 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2709 if (reg->type != SCALAR_VALUE) {
2710 verbose_linfo(env, env->insn_idx, "; ");
2711 verbose(env, "invalid size of register fill\n");
2712 return -EACCES;
2713 }
01f810ac
AM
2714 if (dst_regno >= 0) {
2715 mark_reg_unknown(env, state->regs, dst_regno);
2716 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2717 }
2718 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2719 return 0;
17a52670 2720 }
9c399760 2721 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2722 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2723 verbose(env, "corrupted spill memory\n");
17a52670
AS
2724 return -EACCES;
2725 }
2726 }
2727
01f810ac 2728 if (dst_regno >= 0) {
17a52670 2729 /* restore register state from stack */
01f810ac 2730 state->regs[dst_regno] = *reg;
2f18f62e
AS
2731 /* mark reg as written since spilled pointer state likely
2732 * has its liveness marks cleared by is_state_visited()
2733 * which resets stack/reg liveness for state transitions
2734 */
01f810ac 2735 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2736 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 2737 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2738 * it is acceptable to use this value as a SCALAR_VALUE
2739 * (e.g. for XADD).
2740 * We must not allow unprivileged callers to do that
2741 * with spilled pointers.
2742 */
2743 verbose(env, "leaking pointer from stack off %d\n",
2744 off);
2745 return -EACCES;
dc503a8a 2746 }
f7cf25b2 2747 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2748 } else {
01f810ac 2749 u8 type;
cc2b14d5 2750
17a52670 2751 for (i = 0; i < size; i++) {
01f810ac
AM
2752 type = stype[(slot - i) % BPF_REG_SIZE];
2753 if (type == STACK_MISC)
cc2b14d5 2754 continue;
01f810ac 2755 if (type == STACK_ZERO)
cc2b14d5 2756 continue;
cc2b14d5
AS
2757 verbose(env, "invalid read from stack off %d+%d size %d\n",
2758 off, i, size);
2759 return -EACCES;
2760 }
f7cf25b2 2761 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
2762 if (dst_regno >= 0)
2763 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2764 }
f7cf25b2 2765 return 0;
17a52670
AS
2766}
2767
01f810ac
AM
2768enum stack_access_src {
2769 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2770 ACCESS_HELPER = 2, /* the access is performed by a helper */
2771};
2772
2773static int check_stack_range_initialized(struct bpf_verifier_env *env,
2774 int regno, int off, int access_size,
2775 bool zero_size_allowed,
2776 enum stack_access_src type,
2777 struct bpf_call_arg_meta *meta);
2778
2779static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2780{
2781 return cur_regs(env) + regno;
2782}
2783
2784/* Read the stack at 'ptr_regno + off' and put the result into the register
2785 * 'dst_regno'.
2786 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2787 * but not its variable offset.
2788 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2789 *
2790 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2791 * filling registers (i.e. reads of spilled register cannot be detected when
2792 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2793 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2794 * offset; for a fixed offset check_stack_read_fixed_off should be used
2795 * instead.
2796 */
2797static int check_stack_read_var_off(struct bpf_verifier_env *env,
2798 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2799{
01f810ac
AM
2800 /* The state of the source register. */
2801 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2802 struct bpf_func_state *ptr_state = func(env, reg);
2803 int err;
2804 int min_off, max_off;
2805
2806 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2807 */
01f810ac
AM
2808 err = check_stack_range_initialized(env, ptr_regno, off, size,
2809 false, ACCESS_DIRECT, NULL);
2810 if (err)
2811 return err;
2812
2813 min_off = reg->smin_value + off;
2814 max_off = reg->smax_value + off;
2815 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2816 return 0;
2817}
2818
2819/* check_stack_read dispatches to check_stack_read_fixed_off or
2820 * check_stack_read_var_off.
2821 *
2822 * The caller must ensure that the offset falls within the allocated stack
2823 * bounds.
2824 *
2825 * 'dst_regno' is a register which will receive the value from the stack. It
2826 * can be -1, meaning that the read value is not going to a register.
2827 */
2828static int check_stack_read(struct bpf_verifier_env *env,
2829 int ptr_regno, int off, int size,
2830 int dst_regno)
2831{
2832 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2833 struct bpf_func_state *state = func(env, reg);
2834 int err;
2835 /* Some accesses are only permitted with a static offset. */
2836 bool var_off = !tnum_is_const(reg->var_off);
2837
2838 /* The offset is required to be static when reads don't go to a
2839 * register, in order to not leak pointers (see
2840 * check_stack_read_fixed_off).
2841 */
2842 if (dst_regno < 0 && var_off) {
e4298d25
DB
2843 char tn_buf[48];
2844
2845 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 2846 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
2847 tn_buf, off, size);
2848 return -EACCES;
2849 }
01f810ac
AM
2850 /* Variable offset is prohibited for unprivileged mode for simplicity
2851 * since it requires corresponding support in Spectre masking for stack
2852 * ALU. See also retrieve_ptr_limit().
2853 */
2854 if (!env->bypass_spec_v1 && var_off) {
2855 char tn_buf[48];
e4298d25 2856
01f810ac
AM
2857 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2858 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2859 ptr_regno, tn_buf);
e4298d25
DB
2860 return -EACCES;
2861 }
2862
01f810ac
AM
2863 if (!var_off) {
2864 off += reg->var_off.value;
2865 err = check_stack_read_fixed_off(env, state, off, size,
2866 dst_regno);
2867 } else {
2868 /* Variable offset stack reads need more conservative handling
2869 * than fixed offset ones. Note that dst_regno >= 0 on this
2870 * branch.
2871 */
2872 err = check_stack_read_var_off(env, ptr_regno, off, size,
2873 dst_regno);
2874 }
2875 return err;
2876}
2877
2878
2879/* check_stack_write dispatches to check_stack_write_fixed_off or
2880 * check_stack_write_var_off.
2881 *
2882 * 'ptr_regno' is the register used as a pointer into the stack.
2883 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2884 * 'value_regno' is the register whose value we're writing to the stack. It can
2885 * be -1, meaning that we're not writing from a register.
2886 *
2887 * The caller must ensure that the offset falls within the maximum stack size.
2888 */
2889static int check_stack_write(struct bpf_verifier_env *env,
2890 int ptr_regno, int off, int size,
2891 int value_regno, int insn_idx)
2892{
2893 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2894 struct bpf_func_state *state = func(env, reg);
2895 int err;
2896
2897 if (tnum_is_const(reg->var_off)) {
2898 off += reg->var_off.value;
2899 err = check_stack_write_fixed_off(env, state, off, size,
2900 value_regno, insn_idx);
2901 } else {
2902 /* Variable offset stack reads need more conservative handling
2903 * than fixed offset ones.
2904 */
2905 err = check_stack_write_var_off(env, state,
2906 ptr_regno, off, size,
2907 value_regno, insn_idx);
2908 }
2909 return err;
e4298d25
DB
2910}
2911
591fe988
DB
2912static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2913 int off, int size, enum bpf_access_type type)
2914{
2915 struct bpf_reg_state *regs = cur_regs(env);
2916 struct bpf_map *map = regs[regno].map_ptr;
2917 u32 cap = bpf_map_flags_to_cap(map);
2918
2919 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2920 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2921 map->value_size, off, size);
2922 return -EACCES;
2923 }
2924
2925 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2926 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2927 map->value_size, off, size);
2928 return -EACCES;
2929 }
2930
2931 return 0;
2932}
2933
457f4436
AN
2934/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2935static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2936 int off, int size, u32 mem_size,
2937 bool zero_size_allowed)
17a52670 2938{
457f4436
AN
2939 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2940 struct bpf_reg_state *reg;
2941
2942 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2943 return 0;
17a52670 2944
457f4436
AN
2945 reg = &cur_regs(env)[regno];
2946 switch (reg->type) {
69c087ba
YS
2947 case PTR_TO_MAP_KEY:
2948 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
2949 mem_size, off, size);
2950 break;
457f4436 2951 case PTR_TO_MAP_VALUE:
61bd5218 2952 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2953 mem_size, off, size);
2954 break;
2955 case PTR_TO_PACKET:
2956 case PTR_TO_PACKET_META:
2957 case PTR_TO_PACKET_END:
2958 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2959 off, size, regno, reg->id, off, mem_size);
2960 break;
2961 case PTR_TO_MEM:
2962 default:
2963 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2964 mem_size, off, size);
17a52670 2965 }
457f4436
AN
2966
2967 return -EACCES;
17a52670
AS
2968}
2969
457f4436
AN
2970/* check read/write into a memory region with possible variable offset */
2971static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2972 int off, int size, u32 mem_size,
2973 bool zero_size_allowed)
dbcfe5f7 2974{
f4d7e40a
AS
2975 struct bpf_verifier_state *vstate = env->cur_state;
2976 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2977 struct bpf_reg_state *reg = &state->regs[regno];
2978 int err;
2979
457f4436 2980 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2981 * need to try adding each of min_value and max_value to off
2982 * to make sure our theoretical access will be safe.
dbcfe5f7 2983 */
06ee7115 2984 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2985 print_verifier_state(env, state);
b7137c4e 2986
dbcfe5f7
GB
2987 /* The minimum value is only important with signed
2988 * comparisons where we can't assume the floor of a
2989 * value is 0. If we are using signed variables for our
2990 * index'es we need to make sure that whatever we use
2991 * will have a set floor within our range.
2992 */
b7137c4e
DB
2993 if (reg->smin_value < 0 &&
2994 (reg->smin_value == S64_MIN ||
2995 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2996 reg->smin_value + off < 0)) {
61bd5218 2997 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2998 regno);
2999 return -EACCES;
3000 }
457f4436
AN
3001 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3002 mem_size, zero_size_allowed);
dbcfe5f7 3003 if (err) {
457f4436 3004 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3005 regno);
dbcfe5f7
GB
3006 return err;
3007 }
3008
b03c9f9f
EC
3009 /* If we haven't set a max value then we need to bail since we can't be
3010 * sure we won't do bad things.
3011 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3012 */
b03c9f9f 3013 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3014 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3015 regno);
3016 return -EACCES;
3017 }
457f4436
AN
3018 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3019 mem_size, zero_size_allowed);
3020 if (err) {
3021 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3022 regno);
457f4436
AN
3023 return err;
3024 }
3025
3026 return 0;
3027}
d83525ca 3028
457f4436
AN
3029/* check read/write into a map element with possible variable offset */
3030static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3031 int off, int size, bool zero_size_allowed)
3032{
3033 struct bpf_verifier_state *vstate = env->cur_state;
3034 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3035 struct bpf_reg_state *reg = &state->regs[regno];
3036 struct bpf_map *map = reg->map_ptr;
3037 int err;
3038
3039 err = check_mem_region_access(env, regno, off, size, map->value_size,
3040 zero_size_allowed);
3041 if (err)
3042 return err;
3043
3044 if (map_value_has_spin_lock(map)) {
3045 u32 lock = map->spin_lock_off;
d83525ca
AS
3046
3047 /* if any part of struct bpf_spin_lock can be touched by
3048 * load/store reject this program.
3049 * To check that [x1, x2) overlaps with [y1, y2)
3050 * it is sufficient to check x1 < y2 && y1 < x2.
3051 */
3052 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3053 lock < reg->umax_value + off + size) {
3054 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3055 return -EACCES;
3056 }
3057 }
f1174f77 3058 return err;
dbcfe5f7
GB
3059}
3060
969bf05e
AS
3061#define MAX_PACKET_OFF 0xffff
3062
7e40781c
UP
3063static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3064{
3aac1ead 3065 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
3066}
3067
58e2af8b 3068static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3069 const struct bpf_call_arg_meta *meta,
3070 enum bpf_access_type t)
4acf6c0b 3071{
7e40781c
UP
3072 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3073
3074 switch (prog_type) {
5d66fa7d 3075 /* Program types only with direct read access go here! */
3a0af8fd
TG
3076 case BPF_PROG_TYPE_LWT_IN:
3077 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3078 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3079 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3080 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3081 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3082 if (t == BPF_WRITE)
3083 return false;
8731745e 3084 fallthrough;
5d66fa7d
DB
3085
3086 /* Program types with direct read + write access go here! */
36bbef52
DB
3087 case BPF_PROG_TYPE_SCHED_CLS:
3088 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3089 case BPF_PROG_TYPE_XDP:
3a0af8fd 3090 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3091 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3092 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3093 if (meta)
3094 return meta->pkt_access;
3095
3096 env->seen_direct_write = true;
4acf6c0b 3097 return true;
0d01da6a
SF
3098
3099 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3100 if (t == BPF_WRITE)
3101 env->seen_direct_write = true;
3102
3103 return true;
3104
4acf6c0b
BB
3105 default:
3106 return false;
3107 }
3108}
3109
f1174f77 3110static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3111 int size, bool zero_size_allowed)
f1174f77 3112{
638f5b90 3113 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3114 struct bpf_reg_state *reg = &regs[regno];
3115 int err;
3116
3117 /* We may have added a variable offset to the packet pointer; but any
3118 * reg->range we have comes after that. We are only checking the fixed
3119 * offset.
3120 */
3121
3122 /* We don't allow negative numbers, because we aren't tracking enough
3123 * detail to prove they're safe.
3124 */
b03c9f9f 3125 if (reg->smin_value < 0) {
61bd5218 3126 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3127 regno);
3128 return -EACCES;
3129 }
6d94e741
AS
3130
3131 err = reg->range < 0 ? -EINVAL :
3132 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3133 zero_size_allowed);
f1174f77 3134 if (err) {
61bd5218 3135 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3136 return err;
3137 }
e647815a 3138
457f4436 3139 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3140 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3141 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3142 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3143 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3144 */
3145 env->prog->aux->max_pkt_offset =
3146 max_t(u32, env->prog->aux->max_pkt_offset,
3147 off + reg->umax_value + size - 1);
3148
f1174f77
EC
3149 return err;
3150}
3151
3152/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3153static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3154 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3155 struct btf **btf, u32 *btf_id)
17a52670 3156{
f96da094
DB
3157 struct bpf_insn_access_aux info = {
3158 .reg_type = *reg_type,
9e15db66 3159 .log = &env->log,
f96da094 3160 };
31fd8581 3161
4f9218aa 3162 if (env->ops->is_valid_access &&
5e43f899 3163 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3164 /* A non zero info.ctx_field_size indicates that this field is a
3165 * candidate for later verifier transformation to load the whole
3166 * field and then apply a mask when accessed with a narrower
3167 * access than actual ctx access size. A zero info.ctx_field_size
3168 * will only allow for whole field access and rejects any other
3169 * type of narrower access.
31fd8581 3170 */
23994631 3171 *reg_type = info.reg_type;
31fd8581 3172
22dc4a0f
AN
3173 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3174 *btf = info.btf;
9e15db66 3175 *btf_id = info.btf_id;
22dc4a0f 3176 } else {
9e15db66 3177 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3178 }
32bbe007
AS
3179 /* remember the offset of last byte accessed in ctx */
3180 if (env->prog->aux->max_ctx_offset < off + size)
3181 env->prog->aux->max_ctx_offset = off + size;
17a52670 3182 return 0;
32bbe007 3183 }
17a52670 3184
61bd5218 3185 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3186 return -EACCES;
3187}
3188
d58e468b
PP
3189static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3190 int size)
3191{
3192 if (size < 0 || off < 0 ||
3193 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3194 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3195 off, size);
3196 return -EACCES;
3197 }
3198 return 0;
3199}
3200
5f456649
MKL
3201static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3202 u32 regno, int off, int size,
3203 enum bpf_access_type t)
c64b7983
JS
3204{
3205 struct bpf_reg_state *regs = cur_regs(env);
3206 struct bpf_reg_state *reg = &regs[regno];
5f456649 3207 struct bpf_insn_access_aux info = {};
46f8bc92 3208 bool valid;
c64b7983
JS
3209
3210 if (reg->smin_value < 0) {
3211 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3212 regno);
3213 return -EACCES;
3214 }
3215
46f8bc92
MKL
3216 switch (reg->type) {
3217 case PTR_TO_SOCK_COMMON:
3218 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3219 break;
3220 case PTR_TO_SOCKET:
3221 valid = bpf_sock_is_valid_access(off, size, t, &info);
3222 break;
655a51e5
MKL
3223 case PTR_TO_TCP_SOCK:
3224 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3225 break;
fada7fdc
JL
3226 case PTR_TO_XDP_SOCK:
3227 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3228 break;
46f8bc92
MKL
3229 default:
3230 valid = false;
c64b7983
JS
3231 }
3232
5f456649 3233
46f8bc92
MKL
3234 if (valid) {
3235 env->insn_aux_data[insn_idx].ctx_field_size =
3236 info.ctx_field_size;
3237 return 0;
3238 }
3239
3240 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3241 regno, reg_type_str[reg->type], off, size);
3242
3243 return -EACCES;
c64b7983
JS
3244}
3245
4cabc5b1
DB
3246static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3247{
2a159c6f 3248 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3249}
3250
f37a8cb8
DB
3251static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3252{
2a159c6f 3253 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3254
46f8bc92
MKL
3255 return reg->type == PTR_TO_CTX;
3256}
3257
3258static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3259{
3260 const struct bpf_reg_state *reg = reg_state(env, regno);
3261
3262 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3263}
3264
ca369602
DB
3265static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3266{
2a159c6f 3267 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3268
3269 return type_is_pkt_pointer(reg->type);
3270}
3271
4b5defde
DB
3272static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3273{
3274 const struct bpf_reg_state *reg = reg_state(env, regno);
3275
3276 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3277 return reg->type == PTR_TO_FLOW_KEYS;
3278}
3279
61bd5218
JK
3280static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3281 const struct bpf_reg_state *reg,
d1174416 3282 int off, int size, bool strict)
969bf05e 3283{
f1174f77 3284 struct tnum reg_off;
e07b98d9 3285 int ip_align;
d1174416
DM
3286
3287 /* Byte size accesses are always allowed. */
3288 if (!strict || size == 1)
3289 return 0;
3290
e4eda884
DM
3291 /* For platforms that do not have a Kconfig enabling
3292 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3293 * NET_IP_ALIGN is universally set to '2'. And on platforms
3294 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3295 * to this code only in strict mode where we want to emulate
3296 * the NET_IP_ALIGN==2 checking. Therefore use an
3297 * unconditional IP align value of '2'.
e07b98d9 3298 */
e4eda884 3299 ip_align = 2;
f1174f77
EC
3300
3301 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3302 if (!tnum_is_aligned(reg_off, size)) {
3303 char tn_buf[48];
3304
3305 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3306 verbose(env,
3307 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3308 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3309 return -EACCES;
3310 }
79adffcd 3311
969bf05e
AS
3312 return 0;
3313}
3314
61bd5218
JK
3315static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3316 const struct bpf_reg_state *reg,
f1174f77
EC
3317 const char *pointer_desc,
3318 int off, int size, bool strict)
79adffcd 3319{
f1174f77
EC
3320 struct tnum reg_off;
3321
3322 /* Byte size accesses are always allowed. */
3323 if (!strict || size == 1)
3324 return 0;
3325
3326 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3327 if (!tnum_is_aligned(reg_off, size)) {
3328 char tn_buf[48];
3329
3330 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3331 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3332 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3333 return -EACCES;
3334 }
3335
969bf05e
AS
3336 return 0;
3337}
3338
e07b98d9 3339static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3340 const struct bpf_reg_state *reg, int off,
3341 int size, bool strict_alignment_once)
79adffcd 3342{
ca369602 3343 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3344 const char *pointer_desc = "";
d1174416 3345
79adffcd
DB
3346 switch (reg->type) {
3347 case PTR_TO_PACKET:
de8f3a83
DB
3348 case PTR_TO_PACKET_META:
3349 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3350 * right in front, treat it the very same way.
3351 */
61bd5218 3352 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3353 case PTR_TO_FLOW_KEYS:
3354 pointer_desc = "flow keys ";
3355 break;
69c087ba
YS
3356 case PTR_TO_MAP_KEY:
3357 pointer_desc = "key ";
3358 break;
f1174f77
EC
3359 case PTR_TO_MAP_VALUE:
3360 pointer_desc = "value ";
3361 break;
3362 case PTR_TO_CTX:
3363 pointer_desc = "context ";
3364 break;
3365 case PTR_TO_STACK:
3366 pointer_desc = "stack ";
01f810ac
AM
3367 /* The stack spill tracking logic in check_stack_write_fixed_off()
3368 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3369 * aligned.
3370 */
3371 strict = true;
f1174f77 3372 break;
c64b7983
JS
3373 case PTR_TO_SOCKET:
3374 pointer_desc = "sock ";
3375 break;
46f8bc92
MKL
3376 case PTR_TO_SOCK_COMMON:
3377 pointer_desc = "sock_common ";
3378 break;
655a51e5
MKL
3379 case PTR_TO_TCP_SOCK:
3380 pointer_desc = "tcp_sock ";
3381 break;
fada7fdc
JL
3382 case PTR_TO_XDP_SOCK:
3383 pointer_desc = "xdp_sock ";
3384 break;
79adffcd 3385 default:
f1174f77 3386 break;
79adffcd 3387 }
61bd5218
JK
3388 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3389 strict);
79adffcd
DB
3390}
3391
f4d7e40a
AS
3392static int update_stack_depth(struct bpf_verifier_env *env,
3393 const struct bpf_func_state *func,
3394 int off)
3395{
9c8105bd 3396 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3397
3398 if (stack >= -off)
3399 return 0;
3400
3401 /* update known max for given subprogram */
9c8105bd 3402 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3403 return 0;
3404}
f4d7e40a 3405
70a87ffe
AS
3406/* starting from main bpf function walk all instructions of the function
3407 * and recursively walk all callees that given function can call.
3408 * Ignore jump and exit insns.
3409 * Since recursion is prevented by check_cfg() this algorithm
3410 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3411 */
3412static int check_max_stack_depth(struct bpf_verifier_env *env)
3413{
9c8105bd
JW
3414 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3415 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3416 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3417 bool tail_call_reachable = false;
70a87ffe
AS
3418 int ret_insn[MAX_CALL_FRAMES];
3419 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3420 int j;
f4d7e40a 3421
70a87ffe 3422process_func:
7f6e4312
MF
3423 /* protect against potential stack overflow that might happen when
3424 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3425 * depth for such case down to 256 so that the worst case scenario
3426 * would result in 8k stack size (32 which is tailcall limit * 256 =
3427 * 8k).
3428 *
3429 * To get the idea what might happen, see an example:
3430 * func1 -> sub rsp, 128
3431 * subfunc1 -> sub rsp, 256
3432 * tailcall1 -> add rsp, 256
3433 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3434 * subfunc2 -> sub rsp, 64
3435 * subfunc22 -> sub rsp, 128
3436 * tailcall2 -> add rsp, 128
3437 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3438 *
3439 * tailcall will unwind the current stack frame but it will not get rid
3440 * of caller's stack as shown on the example above.
3441 */
3442 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3443 verbose(env,
3444 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3445 depth);
3446 return -EACCES;
3447 }
70a87ffe
AS
3448 /* round up to 32-bytes, since this is granularity
3449 * of interpreter stack size
3450 */
9c8105bd 3451 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3452 if (depth > MAX_BPF_STACK) {
f4d7e40a 3453 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3454 frame + 1, depth);
f4d7e40a
AS
3455 return -EACCES;
3456 }
70a87ffe 3457continue_func:
4cb3d99c 3458 subprog_end = subprog[idx + 1].start;
70a87ffe 3459 for (; i < subprog_end; i++) {
69c087ba 3460 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3461 continue;
3462 /* remember insn and function to return to */
3463 ret_insn[frame] = i + 1;
9c8105bd 3464 ret_prog[frame] = idx;
70a87ffe
AS
3465
3466 /* find the callee */
3467 i = i + insn[i].imm + 1;
9c8105bd
JW
3468 idx = find_subprog(env, i);
3469 if (idx < 0) {
70a87ffe
AS
3470 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3471 i);
3472 return -EFAULT;
3473 }
ebf7d1f5
MF
3474
3475 if (subprog[idx].has_tail_call)
3476 tail_call_reachable = true;
3477
70a87ffe
AS
3478 frame++;
3479 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3480 verbose(env, "the call stack of %d frames is too deep !\n",
3481 frame);
3482 return -E2BIG;
70a87ffe
AS
3483 }
3484 goto process_func;
3485 }
ebf7d1f5
MF
3486 /* if tail call got detected across bpf2bpf calls then mark each of the
3487 * currently present subprog frames as tail call reachable subprogs;
3488 * this info will be utilized by JIT so that we will be preserving the
3489 * tail call counter throughout bpf2bpf calls combined with tailcalls
3490 */
3491 if (tail_call_reachable)
3492 for (j = 0; j < frame; j++)
3493 subprog[ret_prog[j]].tail_call_reachable = true;
3494
70a87ffe
AS
3495 /* end of for() loop means the last insn of the 'subprog'
3496 * was reached. Doesn't matter whether it was JA or EXIT
3497 */
3498 if (frame == 0)
3499 return 0;
9c8105bd 3500 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3501 frame--;
3502 i = ret_insn[frame];
9c8105bd 3503 idx = ret_prog[frame];
70a87ffe 3504 goto continue_func;
f4d7e40a
AS
3505}
3506
19d28fbd 3507#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3508static int get_callee_stack_depth(struct bpf_verifier_env *env,
3509 const struct bpf_insn *insn, int idx)
3510{
3511 int start = idx + insn->imm + 1, subprog;
3512
3513 subprog = find_subprog(env, start);
3514 if (subprog < 0) {
3515 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3516 start);
3517 return -EFAULT;
3518 }
9c8105bd 3519 return env->subprog_info[subprog].stack_depth;
1ea47e01 3520}
19d28fbd 3521#endif
1ea47e01 3522
51c39bb1
AS
3523int check_ctx_reg(struct bpf_verifier_env *env,
3524 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3525{
3526 /* Access to ctx or passing it to a helper is only allowed in
3527 * its original, unmodified form.
3528 */
3529
3530 if (reg->off) {
3531 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3532 regno, reg->off);
3533 return -EACCES;
3534 }
3535
3536 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3537 char tn_buf[48];
3538
3539 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3540 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3541 return -EACCES;
3542 }
3543
3544 return 0;
3545}
3546
afbf21dc
YS
3547static int __check_buffer_access(struct bpf_verifier_env *env,
3548 const char *buf_info,
3549 const struct bpf_reg_state *reg,
3550 int regno, int off, int size)
9df1c28b
MM
3551{
3552 if (off < 0) {
3553 verbose(env,
4fc00b79 3554 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3555 regno, buf_info, off, size);
9df1c28b
MM
3556 return -EACCES;
3557 }
3558 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3559 char tn_buf[48];
3560
3561 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3562 verbose(env,
4fc00b79 3563 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3564 regno, off, tn_buf);
3565 return -EACCES;
3566 }
afbf21dc
YS
3567
3568 return 0;
3569}
3570
3571static int check_tp_buffer_access(struct bpf_verifier_env *env,
3572 const struct bpf_reg_state *reg,
3573 int regno, int off, int size)
3574{
3575 int err;
3576
3577 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3578 if (err)
3579 return err;
3580
9df1c28b
MM
3581 if (off + size > env->prog->aux->max_tp_access)
3582 env->prog->aux->max_tp_access = off + size;
3583
3584 return 0;
3585}
3586
afbf21dc
YS
3587static int check_buffer_access(struct bpf_verifier_env *env,
3588 const struct bpf_reg_state *reg,
3589 int regno, int off, int size,
3590 bool zero_size_allowed,
3591 const char *buf_info,
3592 u32 *max_access)
3593{
3594 int err;
3595
3596 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3597 if (err)
3598 return err;
3599
3600 if (off + size > *max_access)
3601 *max_access = off + size;
3602
3603 return 0;
3604}
3605
3f50f132
JF
3606/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3607static void zext_32_to_64(struct bpf_reg_state *reg)
3608{
3609 reg->var_off = tnum_subreg(reg->var_off);
3610 __reg_assign_32_into_64(reg);
3611}
9df1c28b 3612
0c17d1d2
JH
3613/* truncate register to smaller size (in bytes)
3614 * must be called with size < BPF_REG_SIZE
3615 */
3616static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3617{
3618 u64 mask;
3619
3620 /* clear high bits in bit representation */
3621 reg->var_off = tnum_cast(reg->var_off, size);
3622
3623 /* fix arithmetic bounds */
3624 mask = ((u64)1 << (size * 8)) - 1;
3625 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3626 reg->umin_value &= mask;
3627 reg->umax_value &= mask;
3628 } else {
3629 reg->umin_value = 0;
3630 reg->umax_value = mask;
3631 }
3632 reg->smin_value = reg->umin_value;
3633 reg->smax_value = reg->umax_value;
3f50f132
JF
3634
3635 /* If size is smaller than 32bit register the 32bit register
3636 * values are also truncated so we push 64-bit bounds into
3637 * 32-bit bounds. Above were truncated < 32-bits already.
3638 */
3639 if (size >= 4)
3640 return;
3641 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3642}
3643
a23740ec
AN
3644static bool bpf_map_is_rdonly(const struct bpf_map *map)
3645{
3646 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3647}
3648
3649static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3650{
3651 void *ptr;
3652 u64 addr;
3653 int err;
3654
3655 err = map->ops->map_direct_value_addr(map, &addr, off);
3656 if (err)
3657 return err;
2dedd7d2 3658 ptr = (void *)(long)addr + off;
a23740ec
AN
3659
3660 switch (size) {
3661 case sizeof(u8):
3662 *val = (u64)*(u8 *)ptr;
3663 break;
3664 case sizeof(u16):
3665 *val = (u64)*(u16 *)ptr;
3666 break;
3667 case sizeof(u32):
3668 *val = (u64)*(u32 *)ptr;
3669 break;
3670 case sizeof(u64):
3671 *val = *(u64 *)ptr;
3672 break;
3673 default:
3674 return -EINVAL;
3675 }
3676 return 0;
3677}
3678
9e15db66
AS
3679static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3680 struct bpf_reg_state *regs,
3681 int regno, int off, int size,
3682 enum bpf_access_type atype,
3683 int value_regno)
3684{
3685 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3686 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3687 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3688 u32 btf_id;
3689 int ret;
3690
9e15db66
AS
3691 if (off < 0) {
3692 verbose(env,
3693 "R%d is ptr_%s invalid negative access: off=%d\n",
3694 regno, tname, off);
3695 return -EACCES;
3696 }
3697 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3698 char tn_buf[48];
3699
3700 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3701 verbose(env,
3702 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3703 regno, tname, off, tn_buf);
3704 return -EACCES;
3705 }
3706
27ae7997 3707 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3708 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3709 off, size, atype, &btf_id);
27ae7997
MKL
3710 } else {
3711 if (atype != BPF_READ) {
3712 verbose(env, "only read is supported\n");
3713 return -EACCES;
3714 }
3715
22dc4a0f
AN
3716 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3717 atype, &btf_id);
27ae7997
MKL
3718 }
3719
9e15db66
AS
3720 if (ret < 0)
3721 return ret;
3722
41c48f3a 3723 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3724 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3725
3726 return 0;
3727}
3728
3729static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3730 struct bpf_reg_state *regs,
3731 int regno, int off, int size,
3732 enum bpf_access_type atype,
3733 int value_regno)
3734{
3735 struct bpf_reg_state *reg = regs + regno;
3736 struct bpf_map *map = reg->map_ptr;
3737 const struct btf_type *t;
3738 const char *tname;
3739 u32 btf_id;
3740 int ret;
3741
3742 if (!btf_vmlinux) {
3743 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3744 return -ENOTSUPP;
3745 }
3746
3747 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3748 verbose(env, "map_ptr access not supported for map type %d\n",
3749 map->map_type);
3750 return -ENOTSUPP;
3751 }
3752
3753 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3754 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3755
3756 if (!env->allow_ptr_to_map_access) {
3757 verbose(env,
3758 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3759 tname);
3760 return -EPERM;
9e15db66 3761 }
27ae7997 3762
41c48f3a
AI
3763 if (off < 0) {
3764 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3765 regno, tname, off);
3766 return -EACCES;
3767 }
3768
3769 if (atype != BPF_READ) {
3770 verbose(env, "only read from %s is supported\n", tname);
3771 return -EACCES;
3772 }
3773
22dc4a0f 3774 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3775 if (ret < 0)
3776 return ret;
3777
3778 if (value_regno >= 0)
22dc4a0f 3779 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3780
9e15db66
AS
3781 return 0;
3782}
3783
01f810ac
AM
3784/* Check that the stack access at the given offset is within bounds. The
3785 * maximum valid offset is -1.
3786 *
3787 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3788 * -state->allocated_stack for reads.
3789 */
3790static int check_stack_slot_within_bounds(int off,
3791 struct bpf_func_state *state,
3792 enum bpf_access_type t)
3793{
3794 int min_valid_off;
3795
3796 if (t == BPF_WRITE)
3797 min_valid_off = -MAX_BPF_STACK;
3798 else
3799 min_valid_off = -state->allocated_stack;
3800
3801 if (off < min_valid_off || off > -1)
3802 return -EACCES;
3803 return 0;
3804}
3805
3806/* Check that the stack access at 'regno + off' falls within the maximum stack
3807 * bounds.
3808 *
3809 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3810 */
3811static int check_stack_access_within_bounds(
3812 struct bpf_verifier_env *env,
3813 int regno, int off, int access_size,
3814 enum stack_access_src src, enum bpf_access_type type)
3815{
3816 struct bpf_reg_state *regs = cur_regs(env);
3817 struct bpf_reg_state *reg = regs + regno;
3818 struct bpf_func_state *state = func(env, reg);
3819 int min_off, max_off;
3820 int err;
3821 char *err_extra;
3822
3823 if (src == ACCESS_HELPER)
3824 /* We don't know if helpers are reading or writing (or both). */
3825 err_extra = " indirect access to";
3826 else if (type == BPF_READ)
3827 err_extra = " read from";
3828 else
3829 err_extra = " write to";
3830
3831 if (tnum_is_const(reg->var_off)) {
3832 min_off = reg->var_off.value + off;
3833 if (access_size > 0)
3834 max_off = min_off + access_size - 1;
3835 else
3836 max_off = min_off;
3837 } else {
3838 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3839 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3840 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3841 err_extra, regno);
3842 return -EACCES;
3843 }
3844 min_off = reg->smin_value + off;
3845 if (access_size > 0)
3846 max_off = reg->smax_value + off + access_size - 1;
3847 else
3848 max_off = min_off;
3849 }
3850
3851 err = check_stack_slot_within_bounds(min_off, state, type);
3852 if (!err)
3853 err = check_stack_slot_within_bounds(max_off, state, type);
3854
3855 if (err) {
3856 if (tnum_is_const(reg->var_off)) {
3857 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3858 err_extra, regno, off, access_size);
3859 } else {
3860 char tn_buf[48];
3861
3862 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3863 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3864 err_extra, regno, tn_buf, access_size);
3865 }
3866 }
3867 return err;
3868}
41c48f3a 3869
17a52670
AS
3870/* check whether memory at (regno + off) is accessible for t = (read | write)
3871 * if t==write, value_regno is a register which value is stored into memory
3872 * if t==read, value_regno is a register which will receive the value from memory
3873 * if t==write && value_regno==-1, some unknown value is stored into memory
3874 * if t==read && value_regno==-1, don't care what we read from memory
3875 */
ca369602
DB
3876static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3877 int off, int bpf_size, enum bpf_access_type t,
3878 int value_regno, bool strict_alignment_once)
17a52670 3879{
638f5b90
AS
3880 struct bpf_reg_state *regs = cur_regs(env);
3881 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3882 struct bpf_func_state *state;
17a52670
AS
3883 int size, err = 0;
3884
3885 size = bpf_size_to_bytes(bpf_size);
3886 if (size < 0)
3887 return size;
3888
f1174f77 3889 /* alignment checks will add in reg->off themselves */
ca369602 3890 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3891 if (err)
3892 return err;
17a52670 3893
f1174f77
EC
3894 /* for access checks, reg->off is just part of off */
3895 off += reg->off;
3896
69c087ba
YS
3897 if (reg->type == PTR_TO_MAP_KEY) {
3898 if (t == BPF_WRITE) {
3899 verbose(env, "write to change key R%d not allowed\n", regno);
3900 return -EACCES;
3901 }
3902
3903 err = check_mem_region_access(env, regno, off, size,
3904 reg->map_ptr->key_size, false);
3905 if (err)
3906 return err;
3907 if (value_regno >= 0)
3908 mark_reg_unknown(env, regs, value_regno);
3909 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3910 if (t == BPF_WRITE && value_regno >= 0 &&
3911 is_pointer_value(env, value_regno)) {
61bd5218 3912 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3913 return -EACCES;
3914 }
591fe988
DB
3915 err = check_map_access_type(env, regno, off, size, t);
3916 if (err)
3917 return err;
9fd29c08 3918 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3919 if (!err && t == BPF_READ && value_regno >= 0) {
3920 struct bpf_map *map = reg->map_ptr;
3921
3922 /* if map is read-only, track its contents as scalars */
3923 if (tnum_is_const(reg->var_off) &&
3924 bpf_map_is_rdonly(map) &&
3925 map->ops->map_direct_value_addr) {
3926 int map_off = off + reg->var_off.value;
3927 u64 val = 0;
3928
3929 err = bpf_map_direct_read(map, map_off, size,
3930 &val);
3931 if (err)
3932 return err;
3933
3934 regs[value_regno].type = SCALAR_VALUE;
3935 __mark_reg_known(&regs[value_regno], val);
3936 } else {
3937 mark_reg_unknown(env, regs, value_regno);
3938 }
3939 }
457f4436
AN
3940 } else if (reg->type == PTR_TO_MEM) {
3941 if (t == BPF_WRITE && value_regno >= 0 &&
3942 is_pointer_value(env, value_regno)) {
3943 verbose(env, "R%d leaks addr into mem\n", value_regno);
3944 return -EACCES;
3945 }
3946 err = check_mem_region_access(env, regno, off, size,
3947 reg->mem_size, false);
3948 if (!err && t == BPF_READ && value_regno >= 0)
3949 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3950 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3951 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 3952 struct btf *btf = NULL;
9e15db66 3953 u32 btf_id = 0;
19de99f7 3954
1be7f75d
AS
3955 if (t == BPF_WRITE && value_regno >= 0 &&
3956 is_pointer_value(env, value_regno)) {
61bd5218 3957 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3958 return -EACCES;
3959 }
f1174f77 3960
58990d1f
DB
3961 err = check_ctx_reg(env, reg, regno);
3962 if (err < 0)
3963 return err;
3964
22dc4a0f 3965 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
3966 if (err)
3967 verbose_linfo(env, insn_idx, "; ");
969bf05e 3968 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3969 /* ctx access returns either a scalar, or a
de8f3a83
DB
3970 * PTR_TO_PACKET[_META,_END]. In the latter
3971 * case, we know the offset is zero.
f1174f77 3972 */
46f8bc92 3973 if (reg_type == SCALAR_VALUE) {
638f5b90 3974 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3975 } else {
638f5b90 3976 mark_reg_known_zero(env, regs,
61bd5218 3977 value_regno);
46f8bc92
MKL
3978 if (reg_type_may_be_null(reg_type))
3979 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3980 /* A load of ctx field could have different
3981 * actual load size with the one encoded in the
3982 * insn. When the dst is PTR, it is for sure not
3983 * a sub-register.
3984 */
3985 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 3986 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
3987 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3988 regs[value_regno].btf = btf;
9e15db66 3989 regs[value_regno].btf_id = btf_id;
22dc4a0f 3990 }
46f8bc92 3991 }
638f5b90 3992 regs[value_regno].type = reg_type;
969bf05e 3993 }
17a52670 3994
f1174f77 3995 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
3996 /* Basic bounds checks. */
3997 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
3998 if (err)
3999 return err;
8726679a 4000
f4d7e40a
AS
4001 state = func(env, reg);
4002 err = update_stack_depth(env, state, off);
4003 if (err)
4004 return err;
8726679a 4005
01f810ac
AM
4006 if (t == BPF_READ)
4007 err = check_stack_read(env, regno, off, size,
61bd5218 4008 value_regno);
01f810ac
AM
4009 else
4010 err = check_stack_write(env, regno, off, size,
4011 value_regno, insn_idx);
de8f3a83 4012 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 4013 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 4014 verbose(env, "cannot write into packet\n");
969bf05e
AS
4015 return -EACCES;
4016 }
4acf6c0b
BB
4017 if (t == BPF_WRITE && value_regno >= 0 &&
4018 is_pointer_value(env, value_regno)) {
61bd5218
JK
4019 verbose(env, "R%d leaks addr into packet\n",
4020 value_regno);
4acf6c0b
BB
4021 return -EACCES;
4022 }
9fd29c08 4023 err = check_packet_access(env, regno, off, size, false);
969bf05e 4024 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 4025 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
4026 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4027 if (t == BPF_WRITE && value_regno >= 0 &&
4028 is_pointer_value(env, value_regno)) {
4029 verbose(env, "R%d leaks addr into flow keys\n",
4030 value_regno);
4031 return -EACCES;
4032 }
4033
4034 err = check_flow_keys_access(env, off, size);
4035 if (!err && t == BPF_READ && value_regno >= 0)
4036 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4037 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4038 if (t == BPF_WRITE) {
46f8bc92
MKL
4039 verbose(env, "R%d cannot write into %s\n",
4040 regno, reg_type_str[reg->type]);
c64b7983
JS
4041 return -EACCES;
4042 }
5f456649 4043 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4044 if (!err && value_regno >= 0)
4045 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4046 } else if (reg->type == PTR_TO_TP_BUFFER) {
4047 err = check_tp_buffer_access(env, reg, regno, off, size);
4048 if (!err && t == BPF_READ && value_regno >= 0)
4049 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
4050 } else if (reg->type == PTR_TO_BTF_ID) {
4051 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4052 value_regno);
41c48f3a
AI
4053 } else if (reg->type == CONST_PTR_TO_MAP) {
4054 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4055 value_regno);
afbf21dc
YS
4056 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4057 if (t == BPF_WRITE) {
4058 verbose(env, "R%d cannot write into %s\n",
4059 regno, reg_type_str[reg->type]);
4060 return -EACCES;
4061 }
f6dfbe31
CIK
4062 err = check_buffer_access(env, reg, regno, off, size, false,
4063 "rdonly",
afbf21dc
YS
4064 &env->prog->aux->max_rdonly_access);
4065 if (!err && value_regno >= 0)
4066 mark_reg_unknown(env, regs, value_regno);
4067 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
4068 err = check_buffer_access(env, reg, regno, off, size, false,
4069 "rdwr",
afbf21dc
YS
4070 &env->prog->aux->max_rdwr_access);
4071 if (!err && t == BPF_READ && value_regno >= 0)
4072 mark_reg_unknown(env, regs, value_regno);
17a52670 4073 } else {
61bd5218
JK
4074 verbose(env, "R%d invalid mem access '%s'\n", regno,
4075 reg_type_str[reg->type]);
17a52670
AS
4076 return -EACCES;
4077 }
969bf05e 4078
f1174f77 4079 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4080 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4081 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4082 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4083 }
17a52670
AS
4084 return err;
4085}
4086
91c960b0 4087static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4088{
5ffa2550 4089 int load_reg;
17a52670
AS
4090 int err;
4091
5ca419f2
BJ
4092 switch (insn->imm) {
4093 case BPF_ADD:
4094 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4095 case BPF_AND:
4096 case BPF_AND | BPF_FETCH:
4097 case BPF_OR:
4098 case BPF_OR | BPF_FETCH:
4099 case BPF_XOR:
4100 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4101 case BPF_XCHG:
4102 case BPF_CMPXCHG:
5ca419f2
BJ
4103 break;
4104 default:
91c960b0
BJ
4105 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4106 return -EINVAL;
4107 }
4108
4109 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4110 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4111 return -EINVAL;
4112 }
4113
4114 /* check src1 operand */
dc503a8a 4115 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4116 if (err)
4117 return err;
4118
4119 /* check src2 operand */
dc503a8a 4120 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4121 if (err)
4122 return err;
4123
5ffa2550
BJ
4124 if (insn->imm == BPF_CMPXCHG) {
4125 /* Check comparison of R0 with memory location */
4126 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4127 if (err)
4128 return err;
4129 }
4130
6bdf6abc 4131 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4132 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4133 return -EACCES;
4134 }
4135
ca369602 4136 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4137 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4138 is_flow_key_reg(env, insn->dst_reg) ||
4139 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4140 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f
DB
4141 insn->dst_reg,
4142 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
4143 return -EACCES;
4144 }
4145
37086bfd
BJ
4146 if (insn->imm & BPF_FETCH) {
4147 if (insn->imm == BPF_CMPXCHG)
4148 load_reg = BPF_REG_0;
4149 else
4150 load_reg = insn->src_reg;
4151
4152 /* check and record load of old value */
4153 err = check_reg_arg(env, load_reg, DST_OP);
4154 if (err)
4155 return err;
4156 } else {
4157 /* This instruction accesses a memory location but doesn't
4158 * actually load it into a register.
4159 */
4160 load_reg = -1;
4161 }
4162
91c960b0 4163 /* check whether we can read the memory */
31fd8581 4164 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
37086bfd 4165 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
17a52670
AS
4166 if (err)
4167 return err;
4168
91c960b0 4169 /* check whether we can write into the same memory */
5ca419f2
BJ
4170 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4171 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4172 if (err)
4173 return err;
4174
5ca419f2 4175 return 0;
17a52670
AS
4176}
4177
01f810ac
AM
4178/* When register 'regno' is used to read the stack (either directly or through
4179 * a helper function) make sure that it's within stack boundary and, depending
4180 * on the access type, that all elements of the stack are initialized.
4181 *
4182 * 'off' includes 'regno->off', but not its dynamic part (if any).
4183 *
4184 * All registers that have been spilled on the stack in the slots within the
4185 * read offsets are marked as read.
4186 */
4187static int check_stack_range_initialized(
4188 struct bpf_verifier_env *env, int regno, int off,
4189 int access_size, bool zero_size_allowed,
4190 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4191{
4192 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4193 struct bpf_func_state *state = func(env, reg);
4194 int err, min_off, max_off, i, j, slot, spi;
4195 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4196 enum bpf_access_type bounds_check_type;
4197 /* Some accesses can write anything into the stack, others are
4198 * read-only.
4199 */
4200 bool clobber = false;
2011fccf 4201
01f810ac
AM
4202 if (access_size == 0 && !zero_size_allowed) {
4203 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4204 return -EACCES;
4205 }
2011fccf 4206
01f810ac
AM
4207 if (type == ACCESS_HELPER) {
4208 /* The bounds checks for writes are more permissive than for
4209 * reads. However, if raw_mode is not set, we'll do extra
4210 * checks below.
4211 */
4212 bounds_check_type = BPF_WRITE;
4213 clobber = true;
4214 } else {
4215 bounds_check_type = BPF_READ;
4216 }
4217 err = check_stack_access_within_bounds(env, regno, off, access_size,
4218 type, bounds_check_type);
4219 if (err)
4220 return err;
4221
17a52670 4222
2011fccf 4223 if (tnum_is_const(reg->var_off)) {
01f810ac 4224 min_off = max_off = reg->var_off.value + off;
2011fccf 4225 } else {
088ec26d
AI
4226 /* Variable offset is prohibited for unprivileged mode for
4227 * simplicity since it requires corresponding support in
4228 * Spectre masking for stack ALU.
4229 * See also retrieve_ptr_limit().
4230 */
2c78ee89 4231 if (!env->bypass_spec_v1) {
088ec26d 4232 char tn_buf[48];
f1174f77 4233
088ec26d 4234 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4235 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4236 regno, err_extra, tn_buf);
088ec26d
AI
4237 return -EACCES;
4238 }
f2bcd05e
AI
4239 /* Only initialized buffer on stack is allowed to be accessed
4240 * with variable offset. With uninitialized buffer it's hard to
4241 * guarantee that whole memory is marked as initialized on
4242 * helper return since specific bounds are unknown what may
4243 * cause uninitialized stack leaking.
4244 */
4245 if (meta && meta->raw_mode)
4246 meta = NULL;
4247
01f810ac
AM
4248 min_off = reg->smin_value + off;
4249 max_off = reg->smax_value + off;
17a52670
AS
4250 }
4251
435faee1
DB
4252 if (meta && meta->raw_mode) {
4253 meta->access_size = access_size;
4254 meta->regno = regno;
4255 return 0;
4256 }
4257
2011fccf 4258 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4259 u8 *stype;
4260
2011fccf 4261 slot = -i - 1;
638f5b90 4262 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4263 if (state->allocated_stack <= slot)
4264 goto err;
4265 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4266 if (*stype == STACK_MISC)
4267 goto mark;
4268 if (*stype == STACK_ZERO) {
01f810ac
AM
4269 if (clobber) {
4270 /* helper can write anything into the stack */
4271 *stype = STACK_MISC;
4272 }
cc2b14d5 4273 goto mark;
17a52670 4274 }
1d68f22b
YS
4275
4276 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4277 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4278 goto mark;
4279
f7cf25b2 4280 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4281 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4282 env->allow_ptr_leaks)) {
01f810ac
AM
4283 if (clobber) {
4284 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4285 for (j = 0; j < BPF_REG_SIZE; j++)
4286 state->stack[spi].slot_type[j] = STACK_MISC;
4287 }
f7cf25b2
AS
4288 goto mark;
4289 }
4290
cc2b14d5 4291err:
2011fccf 4292 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4293 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4294 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4295 } else {
4296 char tn_buf[48];
4297
4298 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4299 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4300 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4301 }
cc2b14d5
AS
4302 return -EACCES;
4303mark:
4304 /* reading any byte out of 8-byte 'spill_slot' will cause
4305 * the whole slot to be marked as 'read'
4306 */
679c782d 4307 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4308 state->stack[spi].spilled_ptr.parent,
4309 REG_LIVE_READ64);
17a52670 4310 }
2011fccf 4311 return update_stack_depth(env, state, min_off);
17a52670
AS
4312}
4313
06c1c049
GB
4314static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4315 int access_size, bool zero_size_allowed,
4316 struct bpf_call_arg_meta *meta)
4317{
638f5b90 4318 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4319
f1174f77 4320 switch (reg->type) {
06c1c049 4321 case PTR_TO_PACKET:
de8f3a83 4322 case PTR_TO_PACKET_META:
9fd29c08
YS
4323 return check_packet_access(env, regno, reg->off, access_size,
4324 zero_size_allowed);
69c087ba
YS
4325 case PTR_TO_MAP_KEY:
4326 return check_mem_region_access(env, regno, reg->off, access_size,
4327 reg->map_ptr->key_size, false);
06c1c049 4328 case PTR_TO_MAP_VALUE:
591fe988
DB
4329 if (check_map_access_type(env, regno, reg->off, access_size,
4330 meta && meta->raw_mode ? BPF_WRITE :
4331 BPF_READ))
4332 return -EACCES;
9fd29c08
YS
4333 return check_map_access(env, regno, reg->off, access_size,
4334 zero_size_allowed);
457f4436
AN
4335 case PTR_TO_MEM:
4336 return check_mem_region_access(env, regno, reg->off,
4337 access_size, reg->mem_size,
4338 zero_size_allowed);
afbf21dc
YS
4339 case PTR_TO_RDONLY_BUF:
4340 if (meta && meta->raw_mode)
4341 return -EACCES;
4342 return check_buffer_access(env, reg, regno, reg->off,
4343 access_size, zero_size_allowed,
4344 "rdonly",
4345 &env->prog->aux->max_rdonly_access);
4346 case PTR_TO_RDWR_BUF:
4347 return check_buffer_access(env, reg, regno, reg->off,
4348 access_size, zero_size_allowed,
4349 "rdwr",
4350 &env->prog->aux->max_rdwr_access);
0d004c02 4351 case PTR_TO_STACK:
01f810ac
AM
4352 return check_stack_range_initialized(
4353 env,
4354 regno, reg->off, access_size,
4355 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4356 default: /* scalar_value or invalid ptr */
4357 /* Allow zero-byte read from NULL, regardless of pointer type */
4358 if (zero_size_allowed && access_size == 0 &&
4359 register_is_null(reg))
4360 return 0;
4361
4362 verbose(env, "R%d type=%s expected=%s\n", regno,
4363 reg_type_str[reg->type],
4364 reg_type_str[PTR_TO_STACK]);
4365 return -EACCES;
06c1c049
GB
4366 }
4367}
4368
e5069b9c
DB
4369int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4370 u32 regno, u32 mem_size)
4371{
4372 if (register_is_null(reg))
4373 return 0;
4374
4375 if (reg_type_may_be_null(reg->type)) {
4376 /* Assuming that the register contains a value check if the memory
4377 * access is safe. Temporarily save and restore the register's state as
4378 * the conversion shouldn't be visible to a caller.
4379 */
4380 const struct bpf_reg_state saved_reg = *reg;
4381 int rv;
4382
4383 mark_ptr_not_null_reg(reg);
4384 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4385 *reg = saved_reg;
4386 return rv;
4387 }
4388
4389 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4390}
4391
d83525ca
AS
4392/* Implementation details:
4393 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4394 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4395 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4396 * value_or_null->value transition, since the verifier only cares about
4397 * the range of access to valid map value pointer and doesn't care about actual
4398 * address of the map element.
4399 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4400 * reg->id > 0 after value_or_null->value transition. By doing so
4401 * two bpf_map_lookups will be considered two different pointers that
4402 * point to different bpf_spin_locks.
4403 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4404 * dead-locks.
4405 * Since only one bpf_spin_lock is allowed the checks are simpler than
4406 * reg_is_refcounted() logic. The verifier needs to remember only
4407 * one spin_lock instead of array of acquired_refs.
4408 * cur_state->active_spin_lock remembers which map value element got locked
4409 * and clears it after bpf_spin_unlock.
4410 */
4411static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4412 bool is_lock)
4413{
4414 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4415 struct bpf_verifier_state *cur = env->cur_state;
4416 bool is_const = tnum_is_const(reg->var_off);
4417 struct bpf_map *map = reg->map_ptr;
4418 u64 val = reg->var_off.value;
4419
d83525ca
AS
4420 if (!is_const) {
4421 verbose(env,
4422 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4423 regno);
4424 return -EINVAL;
4425 }
4426 if (!map->btf) {
4427 verbose(env,
4428 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4429 map->name);
4430 return -EINVAL;
4431 }
4432 if (!map_value_has_spin_lock(map)) {
4433 if (map->spin_lock_off == -E2BIG)
4434 verbose(env,
4435 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4436 map->name);
4437 else if (map->spin_lock_off == -ENOENT)
4438 verbose(env,
4439 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4440 map->name);
4441 else
4442 verbose(env,
4443 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4444 map->name);
4445 return -EINVAL;
4446 }
4447 if (map->spin_lock_off != val + reg->off) {
4448 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4449 val + reg->off);
4450 return -EINVAL;
4451 }
4452 if (is_lock) {
4453 if (cur->active_spin_lock) {
4454 verbose(env,
4455 "Locking two bpf_spin_locks are not allowed\n");
4456 return -EINVAL;
4457 }
4458 cur->active_spin_lock = reg->id;
4459 } else {
4460 if (!cur->active_spin_lock) {
4461 verbose(env, "bpf_spin_unlock without taking a lock\n");
4462 return -EINVAL;
4463 }
4464 if (cur->active_spin_lock != reg->id) {
4465 verbose(env, "bpf_spin_unlock of different lock\n");
4466 return -EINVAL;
4467 }
4468 cur->active_spin_lock = 0;
4469 }
4470 return 0;
4471}
4472
90133415
DB
4473static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4474{
4475 return type == ARG_PTR_TO_MEM ||
4476 type == ARG_PTR_TO_MEM_OR_NULL ||
4477 type == ARG_PTR_TO_UNINIT_MEM;
4478}
4479
4480static bool arg_type_is_mem_size(enum bpf_arg_type type)
4481{
4482 return type == ARG_CONST_SIZE ||
4483 type == ARG_CONST_SIZE_OR_ZERO;
4484}
4485
457f4436
AN
4486static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4487{
4488 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4489}
4490
57c3bb72
AI
4491static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4492{
4493 return type == ARG_PTR_TO_INT ||
4494 type == ARG_PTR_TO_LONG;
4495}
4496
4497static int int_ptr_type_to_size(enum bpf_arg_type type)
4498{
4499 if (type == ARG_PTR_TO_INT)
4500 return sizeof(u32);
4501 else if (type == ARG_PTR_TO_LONG)
4502 return sizeof(u64);
4503
4504 return -EINVAL;
4505}
4506
912f442c
LB
4507static int resolve_map_arg_type(struct bpf_verifier_env *env,
4508 const struct bpf_call_arg_meta *meta,
4509 enum bpf_arg_type *arg_type)
4510{
4511 if (!meta->map_ptr) {
4512 /* kernel subsystem misconfigured verifier */
4513 verbose(env, "invalid map_ptr to access map->type\n");
4514 return -EACCES;
4515 }
4516
4517 switch (meta->map_ptr->map_type) {
4518 case BPF_MAP_TYPE_SOCKMAP:
4519 case BPF_MAP_TYPE_SOCKHASH:
4520 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4521 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4522 } else {
4523 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4524 return -EINVAL;
4525 }
4526 break;
4527
4528 default:
4529 break;
4530 }
4531 return 0;
4532}
4533
f79e7ea5
LB
4534struct bpf_reg_types {
4535 const enum bpf_reg_type types[10];
1df8f55a 4536 u32 *btf_id;
f79e7ea5
LB
4537};
4538
4539static const struct bpf_reg_types map_key_value_types = {
4540 .types = {
4541 PTR_TO_STACK,
4542 PTR_TO_PACKET,
4543 PTR_TO_PACKET_META,
69c087ba 4544 PTR_TO_MAP_KEY,
f79e7ea5
LB
4545 PTR_TO_MAP_VALUE,
4546 },
4547};
4548
4549static const struct bpf_reg_types sock_types = {
4550 .types = {
4551 PTR_TO_SOCK_COMMON,
4552 PTR_TO_SOCKET,
4553 PTR_TO_TCP_SOCK,
4554 PTR_TO_XDP_SOCK,
4555 },
4556};
4557
49a2a4d4 4558#ifdef CONFIG_NET
1df8f55a
MKL
4559static const struct bpf_reg_types btf_id_sock_common_types = {
4560 .types = {
4561 PTR_TO_SOCK_COMMON,
4562 PTR_TO_SOCKET,
4563 PTR_TO_TCP_SOCK,
4564 PTR_TO_XDP_SOCK,
4565 PTR_TO_BTF_ID,
4566 },
4567 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4568};
49a2a4d4 4569#endif
1df8f55a 4570
f79e7ea5
LB
4571static const struct bpf_reg_types mem_types = {
4572 .types = {
4573 PTR_TO_STACK,
4574 PTR_TO_PACKET,
4575 PTR_TO_PACKET_META,
69c087ba 4576 PTR_TO_MAP_KEY,
f79e7ea5
LB
4577 PTR_TO_MAP_VALUE,
4578 PTR_TO_MEM,
4579 PTR_TO_RDONLY_BUF,
4580 PTR_TO_RDWR_BUF,
4581 },
4582};
4583
4584static const struct bpf_reg_types int_ptr_types = {
4585 .types = {
4586 PTR_TO_STACK,
4587 PTR_TO_PACKET,
4588 PTR_TO_PACKET_META,
69c087ba 4589 PTR_TO_MAP_KEY,
f79e7ea5
LB
4590 PTR_TO_MAP_VALUE,
4591 },
4592};
4593
4594static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4595static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4596static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4597static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4598static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4599static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4600static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4601static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
69c087ba
YS
4602static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4603static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
f79e7ea5 4604
0789e13b 4605static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4606 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4607 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4608 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4609 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4610 [ARG_CONST_SIZE] = &scalar_types,
4611 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4612 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4613 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4614 [ARG_PTR_TO_CTX] = &context_types,
4615 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4616 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4617#ifdef CONFIG_NET
1df8f55a 4618 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4619#endif
f79e7ea5
LB
4620 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4621 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4622 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4623 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4624 [ARG_PTR_TO_MEM] = &mem_types,
4625 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4626 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4627 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4628 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4629 [ARG_PTR_TO_INT] = &int_ptr_types,
4630 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4631 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba
YS
4632 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4633 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
f79e7ea5
LB
4634};
4635
4636static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4637 enum bpf_arg_type arg_type,
4638 const u32 *arg_btf_id)
f79e7ea5
LB
4639{
4640 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4641 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4642 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4643 int i, j;
4644
a968d5e2
MKL
4645 compatible = compatible_reg_types[arg_type];
4646 if (!compatible) {
4647 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4648 return -EFAULT;
4649 }
4650
f79e7ea5
LB
4651 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4652 expected = compatible->types[i];
4653 if (expected == NOT_INIT)
4654 break;
4655
4656 if (type == expected)
a968d5e2 4657 goto found;
f79e7ea5
LB
4658 }
4659
4660 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4661 for (j = 0; j + 1 < i; j++)
4662 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4663 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4664 return -EACCES;
a968d5e2
MKL
4665
4666found:
4667 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4668 if (!arg_btf_id) {
4669 if (!compatible->btf_id) {
4670 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4671 return -EFAULT;
4672 }
4673 arg_btf_id = compatible->btf_id;
4674 }
4675
22dc4a0f
AN
4676 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4677 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4678 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4679 regno, kernel_type_name(reg->btf, reg->btf_id),
4680 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4681 return -EACCES;
4682 }
4683
4684 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4685 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4686 regno);
4687 return -EACCES;
4688 }
4689 }
4690
4691 return 0;
f79e7ea5
LB
4692}
4693
af7ec138
YS
4694static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4695 struct bpf_call_arg_meta *meta,
4696 const struct bpf_func_proto *fn)
17a52670 4697{
af7ec138 4698 u32 regno = BPF_REG_1 + arg;
638f5b90 4699 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4700 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4701 enum bpf_reg_type type = reg->type;
17a52670
AS
4702 int err = 0;
4703
80f1d68c 4704 if (arg_type == ARG_DONTCARE)
17a52670
AS
4705 return 0;
4706
dc503a8a
EC
4707 err = check_reg_arg(env, regno, SRC_OP);
4708 if (err)
4709 return err;
17a52670 4710
1be7f75d
AS
4711 if (arg_type == ARG_ANYTHING) {
4712 if (is_pointer_value(env, regno)) {
61bd5218
JK
4713 verbose(env, "R%d leaks addr into helper function\n",
4714 regno);
1be7f75d
AS
4715 return -EACCES;
4716 }
80f1d68c 4717 return 0;
1be7f75d 4718 }
80f1d68c 4719
de8f3a83 4720 if (type_is_pkt_pointer(type) &&
3a0af8fd 4721 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4722 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4723 return -EACCES;
4724 }
4725
912f442c
LB
4726 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4727 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4728 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4729 err = resolve_map_arg_type(env, meta, &arg_type);
4730 if (err)
4731 return err;
4732 }
4733
fd1b0d60
LB
4734 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4735 /* A NULL register has a SCALAR_VALUE type, so skip
4736 * type checking.
4737 */
4738 goto skip_type_check;
4739
a968d5e2 4740 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4741 if (err)
4742 return err;
4743
a968d5e2 4744 if (type == PTR_TO_CTX) {
feec7040
LB
4745 err = check_ctx_reg(env, reg, regno);
4746 if (err < 0)
4747 return err;
d7b9454a
LB
4748 }
4749
fd1b0d60 4750skip_type_check:
02f7c958 4751 if (reg->ref_obj_id) {
457f4436
AN
4752 if (meta->ref_obj_id) {
4753 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4754 regno, reg->ref_obj_id,
4755 meta->ref_obj_id);
4756 return -EFAULT;
4757 }
4758 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4759 }
4760
17a52670
AS
4761 if (arg_type == ARG_CONST_MAP_PTR) {
4762 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4763 meta->map_ptr = reg->map_ptr;
17a52670
AS
4764 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4765 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4766 * check that [key, key + map->key_size) are within
4767 * stack limits and initialized
4768 */
33ff9823 4769 if (!meta->map_ptr) {
17a52670
AS
4770 /* in function declaration map_ptr must come before
4771 * map_key, so that it's verified and known before
4772 * we have to check map_key here. Otherwise it means
4773 * that kernel subsystem misconfigured verifier
4774 */
61bd5218 4775 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4776 return -EACCES;
4777 }
d71962f3
PC
4778 err = check_helper_mem_access(env, regno,
4779 meta->map_ptr->key_size, false,
4780 NULL);
2ea864c5 4781 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4782 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4783 !register_is_null(reg)) ||
2ea864c5 4784 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4785 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4786 * check [value, value + map->value_size) validity
4787 */
33ff9823 4788 if (!meta->map_ptr) {
17a52670 4789 /* kernel subsystem misconfigured verifier */
61bd5218 4790 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4791 return -EACCES;
4792 }
2ea864c5 4793 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4794 err = check_helper_mem_access(env, regno,
4795 meta->map_ptr->value_size, false,
2ea864c5 4796 meta);
eaa6bcb7
HL
4797 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4798 if (!reg->btf_id) {
4799 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4800 return -EACCES;
4801 }
22dc4a0f 4802 meta->ret_btf = reg->btf;
eaa6bcb7 4803 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4804 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4805 if (meta->func_id == BPF_FUNC_spin_lock) {
4806 if (process_spin_lock(env, regno, true))
4807 return -EACCES;
4808 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4809 if (process_spin_lock(env, regno, false))
4810 return -EACCES;
4811 } else {
4812 verbose(env, "verifier internal error\n");
4813 return -EFAULT;
4814 }
69c087ba
YS
4815 } else if (arg_type == ARG_PTR_TO_FUNC) {
4816 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
4817 } else if (arg_type_is_mem_ptr(arg_type)) {
4818 /* The access to this pointer is only checked when we hit the
4819 * next is_mem_size argument below.
4820 */
4821 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 4822 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4823 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4824
10060503
JF
4825 /* This is used to refine r0 return value bounds for helpers
4826 * that enforce this value as an upper bound on return values.
4827 * See do_refine_retval_range() for helpers that can refine
4828 * the return value. C type of helper is u32 so we pull register
4829 * bound from umax_value however, if negative verifier errors
4830 * out. Only upper bounds can be learned because retval is an
4831 * int type and negative retvals are allowed.
849fa506 4832 */
10060503 4833 meta->msize_max_value = reg->umax_value;
849fa506 4834
f1174f77
EC
4835 /* The register is SCALAR_VALUE; the access check
4836 * happens using its boundaries.
06c1c049 4837 */
f1174f77 4838 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4839 /* For unprivileged variable accesses, disable raw
4840 * mode so that the program is required to
4841 * initialize all the memory that the helper could
4842 * just partially fill up.
4843 */
4844 meta = NULL;
4845
b03c9f9f 4846 if (reg->smin_value < 0) {
61bd5218 4847 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4848 regno);
4849 return -EACCES;
4850 }
06c1c049 4851
b03c9f9f 4852 if (reg->umin_value == 0) {
f1174f77
EC
4853 err = check_helper_mem_access(env, regno - 1, 0,
4854 zero_size_allowed,
4855 meta);
06c1c049
GB
4856 if (err)
4857 return err;
06c1c049 4858 }
f1174f77 4859
b03c9f9f 4860 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4861 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4862 regno);
4863 return -EACCES;
4864 }
4865 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4866 reg->umax_value,
f1174f77 4867 zero_size_allowed, meta);
b5dc0163
AS
4868 if (!err)
4869 err = mark_chain_precision(env, regno);
457f4436
AN
4870 } else if (arg_type_is_alloc_size(arg_type)) {
4871 if (!tnum_is_const(reg->var_off)) {
28a8add6 4872 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
4873 regno);
4874 return -EACCES;
4875 }
4876 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4877 } else if (arg_type_is_int_ptr(arg_type)) {
4878 int size = int_ptr_type_to_size(arg_type);
4879
4880 err = check_helper_mem_access(env, regno, size, false, meta);
4881 if (err)
4882 return err;
4883 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4884 }
4885
4886 return err;
4887}
4888
0126240f
LB
4889static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4890{
4891 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4892 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4893
4894 if (func_id != BPF_FUNC_map_update_elem)
4895 return false;
4896
4897 /* It's not possible to get access to a locked struct sock in these
4898 * contexts, so updating is safe.
4899 */
4900 switch (type) {
4901 case BPF_PROG_TYPE_TRACING:
4902 if (eatype == BPF_TRACE_ITER)
4903 return true;
4904 break;
4905 case BPF_PROG_TYPE_SOCKET_FILTER:
4906 case BPF_PROG_TYPE_SCHED_CLS:
4907 case BPF_PROG_TYPE_SCHED_ACT:
4908 case BPF_PROG_TYPE_XDP:
4909 case BPF_PROG_TYPE_SK_REUSEPORT:
4910 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4911 case BPF_PROG_TYPE_SK_LOOKUP:
4912 return true;
4913 default:
4914 break;
4915 }
4916
4917 verbose(env, "cannot update sockmap in this context\n");
4918 return false;
4919}
4920
e411901c
MF
4921static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4922{
4923 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4924}
4925
61bd5218
JK
4926static int check_map_func_compatibility(struct bpf_verifier_env *env,
4927 struct bpf_map *map, int func_id)
35578d79 4928{
35578d79
KX
4929 if (!map)
4930 return 0;
4931
6aff67c8
AS
4932 /* We need a two way check, first is from map perspective ... */
4933 switch (map->map_type) {
4934 case BPF_MAP_TYPE_PROG_ARRAY:
4935 if (func_id != BPF_FUNC_tail_call)
4936 goto error;
4937 break;
4938 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4939 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4940 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4941 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4942 func_id != BPF_FUNC_perf_event_read_value &&
4943 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4944 goto error;
4945 break;
457f4436
AN
4946 case BPF_MAP_TYPE_RINGBUF:
4947 if (func_id != BPF_FUNC_ringbuf_output &&
4948 func_id != BPF_FUNC_ringbuf_reserve &&
4949 func_id != BPF_FUNC_ringbuf_submit &&
4950 func_id != BPF_FUNC_ringbuf_discard &&
4951 func_id != BPF_FUNC_ringbuf_query)
4952 goto error;
4953 break;
6aff67c8
AS
4954 case BPF_MAP_TYPE_STACK_TRACE:
4955 if (func_id != BPF_FUNC_get_stackid)
4956 goto error;
4957 break;
4ed8ec52 4958 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4959 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4960 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4961 goto error;
4962 break;
cd339431 4963 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4964 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4965 if (func_id != BPF_FUNC_get_local_storage)
4966 goto error;
4967 break;
546ac1ff 4968 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4969 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4970 if (func_id != BPF_FUNC_redirect_map &&
4971 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4972 goto error;
4973 break;
fbfc504a
BT
4974 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4975 * appear.
4976 */
6710e112
JDB
4977 case BPF_MAP_TYPE_CPUMAP:
4978 if (func_id != BPF_FUNC_redirect_map)
4979 goto error;
4980 break;
fada7fdc
JL
4981 case BPF_MAP_TYPE_XSKMAP:
4982 if (func_id != BPF_FUNC_redirect_map &&
4983 func_id != BPF_FUNC_map_lookup_elem)
4984 goto error;
4985 break;
56f668df 4986 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4987 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4988 if (func_id != BPF_FUNC_map_lookup_elem)
4989 goto error;
16a43625 4990 break;
174a79ff
JF
4991 case BPF_MAP_TYPE_SOCKMAP:
4992 if (func_id != BPF_FUNC_sk_redirect_map &&
4993 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4994 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4995 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4996 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4997 func_id != BPF_FUNC_map_lookup_elem &&
4998 !may_update_sockmap(env, func_id))
174a79ff
JF
4999 goto error;
5000 break;
81110384
JF
5001 case BPF_MAP_TYPE_SOCKHASH:
5002 if (func_id != BPF_FUNC_sk_redirect_hash &&
5003 func_id != BPF_FUNC_sock_hash_update &&
5004 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5005 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 5006 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5007 func_id != BPF_FUNC_map_lookup_elem &&
5008 !may_update_sockmap(env, func_id))
81110384
JF
5009 goto error;
5010 break;
2dbb9b9e
MKL
5011 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5012 if (func_id != BPF_FUNC_sk_select_reuseport)
5013 goto error;
5014 break;
f1a2e44a
MV
5015 case BPF_MAP_TYPE_QUEUE:
5016 case BPF_MAP_TYPE_STACK:
5017 if (func_id != BPF_FUNC_map_peek_elem &&
5018 func_id != BPF_FUNC_map_pop_elem &&
5019 func_id != BPF_FUNC_map_push_elem)
5020 goto error;
5021 break;
6ac99e8f
MKL
5022 case BPF_MAP_TYPE_SK_STORAGE:
5023 if (func_id != BPF_FUNC_sk_storage_get &&
5024 func_id != BPF_FUNC_sk_storage_delete)
5025 goto error;
5026 break;
8ea63684
KS
5027 case BPF_MAP_TYPE_INODE_STORAGE:
5028 if (func_id != BPF_FUNC_inode_storage_get &&
5029 func_id != BPF_FUNC_inode_storage_delete)
5030 goto error;
5031 break;
4cf1bc1f
KS
5032 case BPF_MAP_TYPE_TASK_STORAGE:
5033 if (func_id != BPF_FUNC_task_storage_get &&
5034 func_id != BPF_FUNC_task_storage_delete)
5035 goto error;
5036 break;
6aff67c8
AS
5037 default:
5038 break;
5039 }
5040
5041 /* ... and second from the function itself. */
5042 switch (func_id) {
5043 case BPF_FUNC_tail_call:
5044 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5045 goto error;
e411901c
MF
5046 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5047 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5048 return -EINVAL;
5049 }
6aff67c8
AS
5050 break;
5051 case BPF_FUNC_perf_event_read:
5052 case BPF_FUNC_perf_event_output:
908432ca 5053 case BPF_FUNC_perf_event_read_value:
a7658e1a 5054 case BPF_FUNC_skb_output:
d831ee84 5055 case BPF_FUNC_xdp_output:
6aff67c8
AS
5056 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5057 goto error;
5058 break;
5059 case BPF_FUNC_get_stackid:
5060 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5061 goto error;
5062 break;
60d20f91 5063 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5064 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5065 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5066 goto error;
5067 break;
97f91a7c 5068 case BPF_FUNC_redirect_map:
9c270af3 5069 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5070 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5071 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5072 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5073 goto error;
5074 break;
174a79ff 5075 case BPF_FUNC_sk_redirect_map:
4f738adb 5076 case BPF_FUNC_msg_redirect_map:
81110384 5077 case BPF_FUNC_sock_map_update:
174a79ff
JF
5078 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5079 goto error;
5080 break;
81110384
JF
5081 case BPF_FUNC_sk_redirect_hash:
5082 case BPF_FUNC_msg_redirect_hash:
5083 case BPF_FUNC_sock_hash_update:
5084 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5085 goto error;
5086 break;
cd339431 5087 case BPF_FUNC_get_local_storage:
b741f163
RG
5088 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5089 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5090 goto error;
5091 break;
2dbb9b9e 5092 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5093 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5094 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5095 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5096 goto error;
5097 break;
f1a2e44a
MV
5098 case BPF_FUNC_map_peek_elem:
5099 case BPF_FUNC_map_pop_elem:
5100 case BPF_FUNC_map_push_elem:
5101 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5102 map->map_type != BPF_MAP_TYPE_STACK)
5103 goto error;
5104 break;
6ac99e8f
MKL
5105 case BPF_FUNC_sk_storage_get:
5106 case BPF_FUNC_sk_storage_delete:
5107 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5108 goto error;
5109 break;
8ea63684
KS
5110 case BPF_FUNC_inode_storage_get:
5111 case BPF_FUNC_inode_storage_delete:
5112 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5113 goto error;
5114 break;
4cf1bc1f
KS
5115 case BPF_FUNC_task_storage_get:
5116 case BPF_FUNC_task_storage_delete:
5117 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5118 goto error;
5119 break;
6aff67c8
AS
5120 default:
5121 break;
35578d79
KX
5122 }
5123
5124 return 0;
6aff67c8 5125error:
61bd5218 5126 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5127 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5128 return -EINVAL;
35578d79
KX
5129}
5130
90133415 5131static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5132{
5133 int count = 0;
5134
39f19ebb 5135 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5136 count++;
39f19ebb 5137 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5138 count++;
39f19ebb 5139 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5140 count++;
39f19ebb 5141 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5142 count++;
39f19ebb 5143 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5144 count++;
5145
90133415
DB
5146 /* We only support one arg being in raw mode at the moment,
5147 * which is sufficient for the helper functions we have
5148 * right now.
5149 */
5150 return count <= 1;
5151}
5152
5153static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5154 enum bpf_arg_type arg_next)
5155{
5156 return (arg_type_is_mem_ptr(arg_curr) &&
5157 !arg_type_is_mem_size(arg_next)) ||
5158 (!arg_type_is_mem_ptr(arg_curr) &&
5159 arg_type_is_mem_size(arg_next));
5160}
5161
5162static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5163{
5164 /* bpf_xxx(..., buf, len) call will access 'len'
5165 * bytes from memory 'buf'. Both arg types need
5166 * to be paired, so make sure there's no buggy
5167 * helper function specification.
5168 */
5169 if (arg_type_is_mem_size(fn->arg1_type) ||
5170 arg_type_is_mem_ptr(fn->arg5_type) ||
5171 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5172 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5173 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5174 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5175 return false;
5176
5177 return true;
5178}
5179
1b986589 5180static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5181{
5182 int count = 0;
5183
1b986589 5184 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5185 count++;
1b986589 5186 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5187 count++;
1b986589 5188 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5189 count++;
1b986589 5190 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5191 count++;
1b986589 5192 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5193 count++;
5194
1b986589
MKL
5195 /* A reference acquiring function cannot acquire
5196 * another refcounted ptr.
5197 */
64d85290 5198 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5199 return false;
5200
fd978bf7
JS
5201 /* We only support one arg being unreferenced at the moment,
5202 * which is sufficient for the helper functions we have right now.
5203 */
5204 return count <= 1;
5205}
5206
9436ef6e
LB
5207static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5208{
5209 int i;
5210
1df8f55a 5211 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5212 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5213 return false;
5214
1df8f55a
MKL
5215 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5216 return false;
5217 }
5218
9436ef6e
LB
5219 return true;
5220}
5221
1b986589 5222static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5223{
5224 return check_raw_mode_ok(fn) &&
fd978bf7 5225 check_arg_pair_ok(fn) &&
9436ef6e 5226 check_btf_id_ok(fn) &&
1b986589 5227 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5228}
5229
de8f3a83
DB
5230/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5231 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5232 */
f4d7e40a
AS
5233static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5234 struct bpf_func_state *state)
969bf05e 5235{
58e2af8b 5236 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5237 int i;
5238
5239 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5240 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5241 mark_reg_unknown(env, regs, i);
969bf05e 5242
f3709f69
JS
5243 bpf_for_each_spilled_reg(i, state, reg) {
5244 if (!reg)
969bf05e 5245 continue;
de8f3a83 5246 if (reg_is_pkt_pointer_any(reg))
f54c7898 5247 __mark_reg_unknown(env, reg);
969bf05e
AS
5248 }
5249}
5250
f4d7e40a
AS
5251static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5252{
5253 struct bpf_verifier_state *vstate = env->cur_state;
5254 int i;
5255
5256 for (i = 0; i <= vstate->curframe; i++)
5257 __clear_all_pkt_pointers(env, vstate->frame[i]);
5258}
5259
6d94e741
AS
5260enum {
5261 AT_PKT_END = -1,
5262 BEYOND_PKT_END = -2,
5263};
5264
5265static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5266{
5267 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5268 struct bpf_reg_state *reg = &state->regs[regn];
5269
5270 if (reg->type != PTR_TO_PACKET)
5271 /* PTR_TO_PACKET_META is not supported yet */
5272 return;
5273
5274 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5275 * How far beyond pkt_end it goes is unknown.
5276 * if (!range_open) it's the case of pkt >= pkt_end
5277 * if (range_open) it's the case of pkt > pkt_end
5278 * hence this pointer is at least 1 byte bigger than pkt_end
5279 */
5280 if (range_open)
5281 reg->range = BEYOND_PKT_END;
5282 else
5283 reg->range = AT_PKT_END;
5284}
5285
fd978bf7 5286static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5287 struct bpf_func_state *state,
5288 int ref_obj_id)
fd978bf7
JS
5289{
5290 struct bpf_reg_state *regs = state->regs, *reg;
5291 int i;
5292
5293 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5294 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5295 mark_reg_unknown(env, regs, i);
5296
5297 bpf_for_each_spilled_reg(i, state, reg) {
5298 if (!reg)
5299 continue;
1b986589 5300 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5301 __mark_reg_unknown(env, reg);
fd978bf7
JS
5302 }
5303}
5304
5305/* The pointer with the specified id has released its reference to kernel
5306 * resources. Identify all copies of the same pointer and clear the reference.
5307 */
5308static int release_reference(struct bpf_verifier_env *env,
1b986589 5309 int ref_obj_id)
fd978bf7
JS
5310{
5311 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5312 int err;
fd978bf7
JS
5313 int i;
5314
1b986589
MKL
5315 err = release_reference_state(cur_func(env), ref_obj_id);
5316 if (err)
5317 return err;
5318
fd978bf7 5319 for (i = 0; i <= vstate->curframe; i++)
1b986589 5320 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5321
1b986589 5322 return 0;
fd978bf7
JS
5323}
5324
51c39bb1
AS
5325static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5326 struct bpf_reg_state *regs)
5327{
5328 int i;
5329
5330 /* after the call registers r0 - r5 were scratched */
5331 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5332 mark_reg_not_init(env, regs, caller_saved[i]);
5333 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5334 }
5335}
5336
14351375
YS
5337typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5338 struct bpf_func_state *caller,
5339 struct bpf_func_state *callee,
5340 int insn_idx);
5341
5342static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5343 int *insn_idx, int subprog,
5344 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
5345{
5346 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5347 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5348 struct bpf_func_state *caller, *callee;
14351375 5349 int err;
51c39bb1 5350 bool is_global = false;
f4d7e40a 5351
aada9ce6 5352 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5353 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5354 state->curframe + 2);
f4d7e40a
AS
5355 return -E2BIG;
5356 }
5357
f4d7e40a
AS
5358 caller = state->frame[state->curframe];
5359 if (state->frame[state->curframe + 1]) {
5360 verbose(env, "verifier bug. Frame %d already allocated\n",
5361 state->curframe + 1);
5362 return -EFAULT;
5363 }
5364
51c39bb1
AS
5365 func_info_aux = env->prog->aux->func_info_aux;
5366 if (func_info_aux)
5367 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5368 err = btf_check_func_arg_match(env, subprog, caller->regs);
5369 if (err == -EFAULT)
5370 return err;
5371 if (is_global) {
5372 if (err) {
5373 verbose(env, "Caller passes invalid args into func#%d\n",
5374 subprog);
5375 return err;
5376 } else {
5377 if (env->log.level & BPF_LOG_LEVEL)
5378 verbose(env,
5379 "Func#%d is global and valid. Skipping.\n",
5380 subprog);
5381 clear_caller_saved_regs(env, caller->regs);
5382
45159b27 5383 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5384 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 5385 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5386
5387 /* continue with next insn after call */
5388 return 0;
5389 }
5390 }
5391
f4d7e40a
AS
5392 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5393 if (!callee)
5394 return -ENOMEM;
5395 state->frame[state->curframe + 1] = callee;
5396
5397 /* callee cannot access r0, r6 - r9 for reading and has to write
5398 * into its own stack before reading from it.
5399 * callee can read/write into caller's stack
5400 */
5401 init_func_state(env, callee,
5402 /* remember the callsite, it will be used by bpf_exit */
5403 *insn_idx /* callsite */,
5404 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5405 subprog /* subprog number within this prog */);
f4d7e40a 5406
fd978bf7
JS
5407 /* Transfer references to the callee */
5408 err = transfer_reference_state(callee, caller);
5409 if (err)
5410 return err;
5411
14351375
YS
5412 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5413 if (err)
5414 return err;
f4d7e40a 5415
51c39bb1 5416 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5417
5418 /* only increment it after check_reg_arg() finished */
5419 state->curframe++;
5420
5421 /* and go analyze first insn of the callee */
14351375 5422 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 5423
06ee7115 5424 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5425 verbose(env, "caller:\n");
5426 print_verifier_state(env, caller);
5427 verbose(env, "callee:\n");
5428 print_verifier_state(env, callee);
5429 }
5430 return 0;
5431}
5432
314ee05e
YS
5433int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5434 struct bpf_func_state *caller,
5435 struct bpf_func_state *callee)
5436{
5437 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5438 * void *callback_ctx, u64 flags);
5439 * callback_fn(struct bpf_map *map, void *key, void *value,
5440 * void *callback_ctx);
5441 */
5442 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5443
5444 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5445 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5446 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5447
5448 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5449 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5450 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5451
5452 /* pointer to stack or null */
5453 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5454
5455 /* unused */
5456 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5457 return 0;
5458}
5459
14351375
YS
5460static int set_callee_state(struct bpf_verifier_env *env,
5461 struct bpf_func_state *caller,
5462 struct bpf_func_state *callee, int insn_idx)
5463{
5464 int i;
5465
5466 /* copy r1 - r5 args that callee can access. The copy includes parent
5467 * pointers, which connects us up to the liveness chain
5468 */
5469 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5470 callee->regs[i] = caller->regs[i];
5471 return 0;
5472}
5473
5474static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5475 int *insn_idx)
5476{
5477 int subprog, target_insn;
5478
5479 target_insn = *insn_idx + insn->imm + 1;
5480 subprog = find_subprog(env, target_insn);
5481 if (subprog < 0) {
5482 verbose(env, "verifier bug. No program starts at insn %d\n",
5483 target_insn);
5484 return -EFAULT;
5485 }
5486
5487 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5488}
5489
69c087ba
YS
5490static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5491 struct bpf_func_state *caller,
5492 struct bpf_func_state *callee,
5493 int insn_idx)
5494{
5495 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5496 struct bpf_map *map;
5497 int err;
5498
5499 if (bpf_map_ptr_poisoned(insn_aux)) {
5500 verbose(env, "tail_call abusing map_ptr\n");
5501 return -EINVAL;
5502 }
5503
5504 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5505 if (!map->ops->map_set_for_each_callback_args ||
5506 !map->ops->map_for_each_callback) {
5507 verbose(env, "callback function not allowed for map\n");
5508 return -ENOTSUPP;
5509 }
5510
5511 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5512 if (err)
5513 return err;
5514
5515 callee->in_callback_fn = true;
5516 return 0;
5517}
5518
f4d7e40a
AS
5519static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5520{
5521 struct bpf_verifier_state *state = env->cur_state;
5522 struct bpf_func_state *caller, *callee;
5523 struct bpf_reg_state *r0;
fd978bf7 5524 int err;
f4d7e40a
AS
5525
5526 callee = state->frame[state->curframe];
5527 r0 = &callee->regs[BPF_REG_0];
5528 if (r0->type == PTR_TO_STACK) {
5529 /* technically it's ok to return caller's stack pointer
5530 * (or caller's caller's pointer) back to the caller,
5531 * since these pointers are valid. Only current stack
5532 * pointer will be invalid as soon as function exits,
5533 * but let's be conservative
5534 */
5535 verbose(env, "cannot return stack pointer to the caller\n");
5536 return -EINVAL;
5537 }
5538
5539 state->curframe--;
5540 caller = state->frame[state->curframe];
69c087ba
YS
5541 if (callee->in_callback_fn) {
5542 /* enforce R0 return value range [0, 1]. */
5543 struct tnum range = tnum_range(0, 1);
5544
5545 if (r0->type != SCALAR_VALUE) {
5546 verbose(env, "R0 not a scalar value\n");
5547 return -EACCES;
5548 }
5549 if (!tnum_in(range, r0->var_off)) {
5550 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5551 return -EINVAL;
5552 }
5553 } else {
5554 /* return to the caller whatever r0 had in the callee */
5555 caller->regs[BPF_REG_0] = *r0;
5556 }
f4d7e40a 5557
fd978bf7
JS
5558 /* Transfer references to the caller */
5559 err = transfer_reference_state(caller, callee);
5560 if (err)
5561 return err;
5562
f4d7e40a 5563 *insn_idx = callee->callsite + 1;
06ee7115 5564 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5565 verbose(env, "returning from callee:\n");
5566 print_verifier_state(env, callee);
5567 verbose(env, "to caller at %d:\n", *insn_idx);
5568 print_verifier_state(env, caller);
5569 }
5570 /* clear everything in the callee */
5571 free_func_state(callee);
5572 state->frame[state->curframe + 1] = NULL;
5573 return 0;
5574}
5575
849fa506
YS
5576static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5577 int func_id,
5578 struct bpf_call_arg_meta *meta)
5579{
5580 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5581
5582 if (ret_type != RET_INTEGER ||
5583 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
5584 func_id != BPF_FUNC_probe_read_str &&
5585 func_id != BPF_FUNC_probe_read_kernel_str &&
5586 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5587 return;
5588
10060503 5589 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5590 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5591 ret_reg->smin_value = -MAX_ERRNO;
5592 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5593 __reg_deduce_bounds(ret_reg);
5594 __reg_bound_offset(ret_reg);
10060503 5595 __update_reg_bounds(ret_reg);
849fa506
YS
5596}
5597
c93552c4
DB
5598static int
5599record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5600 int func_id, int insn_idx)
5601{
5602 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5603 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5604
5605 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5606 func_id != BPF_FUNC_map_lookup_elem &&
5607 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5608 func_id != BPF_FUNC_map_delete_elem &&
5609 func_id != BPF_FUNC_map_push_elem &&
5610 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 5611 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f
BT
5612 func_id != BPF_FUNC_for_each_map_elem &&
5613 func_id != BPF_FUNC_redirect_map)
c93552c4 5614 return 0;
09772d92 5615
591fe988 5616 if (map == NULL) {
c93552c4
DB
5617 verbose(env, "kernel subsystem misconfigured verifier\n");
5618 return -EINVAL;
5619 }
5620
591fe988
DB
5621 /* In case of read-only, some additional restrictions
5622 * need to be applied in order to prevent altering the
5623 * state of the map from program side.
5624 */
5625 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5626 (func_id == BPF_FUNC_map_delete_elem ||
5627 func_id == BPF_FUNC_map_update_elem ||
5628 func_id == BPF_FUNC_map_push_elem ||
5629 func_id == BPF_FUNC_map_pop_elem)) {
5630 verbose(env, "write into map forbidden\n");
5631 return -EACCES;
5632 }
5633
d2e4c1e6 5634 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5635 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5636 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5637 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5638 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5639 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5640 return 0;
5641}
5642
d2e4c1e6
DB
5643static int
5644record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5645 int func_id, int insn_idx)
5646{
5647 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5648 struct bpf_reg_state *regs = cur_regs(env), *reg;
5649 struct bpf_map *map = meta->map_ptr;
5650 struct tnum range;
5651 u64 val;
cc52d914 5652 int err;
d2e4c1e6
DB
5653
5654 if (func_id != BPF_FUNC_tail_call)
5655 return 0;
5656 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5657 verbose(env, "kernel subsystem misconfigured verifier\n");
5658 return -EINVAL;
5659 }
5660
5661 range = tnum_range(0, map->max_entries - 1);
5662 reg = &regs[BPF_REG_3];
5663
5664 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5665 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5666 return 0;
5667 }
5668
cc52d914
DB
5669 err = mark_chain_precision(env, BPF_REG_3);
5670 if (err)
5671 return err;
5672
d2e4c1e6
DB
5673 val = reg->var_off.value;
5674 if (bpf_map_key_unseen(aux))
5675 bpf_map_key_store(aux, val);
5676 else if (!bpf_map_key_poisoned(aux) &&
5677 bpf_map_key_immediate(aux) != val)
5678 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5679 return 0;
5680}
5681
fd978bf7
JS
5682static int check_reference_leak(struct bpf_verifier_env *env)
5683{
5684 struct bpf_func_state *state = cur_func(env);
5685 int i;
5686
5687 for (i = 0; i < state->acquired_refs; i++) {
5688 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5689 state->refs[i].id, state->refs[i].insn_idx);
5690 }
5691 return state->acquired_refs ? -EINVAL : 0;
5692}
5693
69c087ba
YS
5694static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5695 int *insn_idx_p)
17a52670 5696{
17a52670 5697 const struct bpf_func_proto *fn = NULL;
638f5b90 5698 struct bpf_reg_state *regs;
33ff9823 5699 struct bpf_call_arg_meta meta;
69c087ba 5700 int insn_idx = *insn_idx_p;
969bf05e 5701 bool changes_data;
69c087ba 5702 int i, err, func_id;
17a52670
AS
5703
5704 /* find function prototype */
69c087ba 5705 func_id = insn->imm;
17a52670 5706 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5707 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5708 func_id);
17a52670
AS
5709 return -EINVAL;
5710 }
5711
00176a34 5712 if (env->ops->get_func_proto)
5e43f899 5713 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5714 if (!fn) {
61bd5218
JK
5715 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5716 func_id);
17a52670
AS
5717 return -EINVAL;
5718 }
5719
5720 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5721 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5722 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5723 return -EINVAL;
5724 }
5725
eae2e83e
JO
5726 if (fn->allowed && !fn->allowed(env->prog)) {
5727 verbose(env, "helper call is not allowed in probe\n");
5728 return -EINVAL;
5729 }
5730
04514d13 5731 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5732 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5733 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5734 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5735 func_id_name(func_id), func_id);
5736 return -EINVAL;
5737 }
969bf05e 5738
33ff9823 5739 memset(&meta, 0, sizeof(meta));
36bbef52 5740 meta.pkt_access = fn->pkt_access;
33ff9823 5741
1b986589 5742 err = check_func_proto(fn, func_id);
435faee1 5743 if (err) {
61bd5218 5744 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 5745 func_id_name(func_id), func_id);
435faee1
DB
5746 return err;
5747 }
5748
d83525ca 5749 meta.func_id = func_id;
17a52670 5750 /* check args */
523a4cf4 5751 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 5752 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
5753 if (err)
5754 return err;
5755 }
17a52670 5756
c93552c4
DB
5757 err = record_func_map(env, &meta, func_id, insn_idx);
5758 if (err)
5759 return err;
5760
d2e4c1e6
DB
5761 err = record_func_key(env, &meta, func_id, insn_idx);
5762 if (err)
5763 return err;
5764
435faee1
DB
5765 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5766 * is inferred from register state.
5767 */
5768 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
5769 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5770 BPF_WRITE, -1, false);
435faee1
DB
5771 if (err)
5772 return err;
5773 }
5774
fd978bf7
JS
5775 if (func_id == BPF_FUNC_tail_call) {
5776 err = check_reference_leak(env);
5777 if (err) {
5778 verbose(env, "tail_call would lead to reference leak\n");
5779 return err;
5780 }
5781 } else if (is_release_function(func_id)) {
1b986589 5782 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
5783 if (err) {
5784 verbose(env, "func %s#%d reference has not been acquired before\n",
5785 func_id_name(func_id), func_id);
fd978bf7 5786 return err;
46f8bc92 5787 }
fd978bf7
JS
5788 }
5789
638f5b90 5790 regs = cur_regs(env);
cd339431
RG
5791
5792 /* check that flags argument in get_local_storage(map, flags) is 0,
5793 * this is required because get_local_storage() can't return an error.
5794 */
5795 if (func_id == BPF_FUNC_get_local_storage &&
5796 !register_is_null(&regs[BPF_REG_2])) {
5797 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5798 return -EINVAL;
5799 }
5800
69c087ba
YS
5801 if (func_id == BPF_FUNC_for_each_map_elem) {
5802 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
5803 set_map_elem_callback_state);
5804 if (err < 0)
5805 return -EINVAL;
5806 }
5807
17a52670 5808 /* reset caller saved regs */
dc503a8a 5809 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5810 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5811 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5812 }
17a52670 5813
5327ed3d
JW
5814 /* helper call returns 64-bit value. */
5815 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5816
dc503a8a 5817 /* update return register (already marked as written above) */
17a52670 5818 if (fn->ret_type == RET_INTEGER) {
f1174f77 5819 /* sets type to SCALAR_VALUE */
61bd5218 5820 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5821 } else if (fn->ret_type == RET_VOID) {
5822 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5823 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5824 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5825 /* There is no offset yet applied, variable or fixed */
61bd5218 5826 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5827 /* remember map_ptr, so that check_map_access()
5828 * can check 'value_size' boundary of memory access
5829 * to map element returned from bpf_map_lookup_elem()
5830 */
33ff9823 5831 if (meta.map_ptr == NULL) {
61bd5218
JK
5832 verbose(env,
5833 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5834 return -EINVAL;
5835 }
33ff9823 5836 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5837 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5838 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5839 if (map_value_has_spin_lock(meta.map_ptr))
5840 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5841 } else {
5842 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 5843 }
c64b7983
JS
5844 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5845 mark_reg_known_zero(env, regs, BPF_REG_0);
5846 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
5847 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5848 mark_reg_known_zero(env, regs, BPF_REG_0);
5849 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
5850 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5851 mark_reg_known_zero(env, regs, BPF_REG_0);
5852 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
5853 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5854 mark_reg_known_zero(env, regs, BPF_REG_0);
5855 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 5856 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
5857 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5858 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
5859 const struct btf_type *t;
5860
5861 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 5862 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
5863 if (!btf_type_is_struct(t)) {
5864 u32 tsize;
5865 const struct btf_type *ret;
5866 const char *tname;
5867
5868 /* resolve the type size of ksym. */
22dc4a0f 5869 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 5870 if (IS_ERR(ret)) {
22dc4a0f 5871 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
5872 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5873 tname, PTR_ERR(ret));
5874 return -EINVAL;
5875 }
63d9b80d
HL
5876 regs[BPF_REG_0].type =
5877 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5878 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
5879 regs[BPF_REG_0].mem_size = tsize;
5880 } else {
63d9b80d
HL
5881 regs[BPF_REG_0].type =
5882 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5883 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 5884 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
5885 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5886 }
3ca1032a
KS
5887 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5888 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
5889 int ret_btf_id;
5890
5891 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
5892 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5893 PTR_TO_BTF_ID :
5894 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
5895 ret_btf_id = *fn->ret_btf_id;
5896 if (ret_btf_id == 0) {
5897 verbose(env, "invalid return type %d of func %s#%d\n",
5898 fn->ret_type, func_id_name(func_id), func_id);
5899 return -EINVAL;
5900 }
22dc4a0f
AN
5901 /* current BPF helper definitions are only coming from
5902 * built-in code with type IDs from vmlinux BTF
5903 */
5904 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 5905 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5906 } else {
61bd5218 5907 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5908 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5909 return -EINVAL;
5910 }
04fd61ab 5911
93c230e3
MKL
5912 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5913 regs[BPF_REG_0].id = ++env->id_gen;
5914
0f3adc28 5915 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5916 /* For release_reference() */
5917 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5918 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5919 int id = acquire_reference_state(env, insn_idx);
5920
5921 if (id < 0)
5922 return id;
5923 /* For mark_ptr_or_null_reg() */
5924 regs[BPF_REG_0].id = id;
5925 /* For release_reference() */
5926 regs[BPF_REG_0].ref_obj_id = id;
5927 }
1b986589 5928
849fa506
YS
5929 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5930
61bd5218 5931 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5932 if (err)
5933 return err;
04fd61ab 5934
fa28dcb8
SL
5935 if ((func_id == BPF_FUNC_get_stack ||
5936 func_id == BPF_FUNC_get_task_stack) &&
5937 !env->prog->has_callchain_buf) {
c195651e
YS
5938 const char *err_str;
5939
5940#ifdef CONFIG_PERF_EVENTS
5941 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5942 err_str = "cannot get callchain buffer for func %s#%d\n";
5943#else
5944 err = -ENOTSUPP;
5945 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5946#endif
5947 if (err) {
5948 verbose(env, err_str, func_id_name(func_id), func_id);
5949 return err;
5950 }
5951
5952 env->prog->has_callchain_buf = true;
5953 }
5954
5d99cb2c
SL
5955 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5956 env->prog->call_get_stack = true;
5957
969bf05e
AS
5958 if (changes_data)
5959 clear_all_pkt_pointers(env);
5960 return 0;
5961}
5962
b03c9f9f
EC
5963static bool signed_add_overflows(s64 a, s64 b)
5964{
5965 /* Do the add in u64, where overflow is well-defined */
5966 s64 res = (s64)((u64)a + (u64)b);
5967
5968 if (b < 0)
5969 return res > a;
5970 return res < a;
5971}
5972
bc895e8b 5973static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
5974{
5975 /* Do the add in u32, where overflow is well-defined */
5976 s32 res = (s32)((u32)a + (u32)b);
5977
5978 if (b < 0)
5979 return res > a;
5980 return res < a;
5981}
5982
bc895e8b 5983static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
5984{
5985 /* Do the sub in u64, where overflow is well-defined */
5986 s64 res = (s64)((u64)a - (u64)b);
5987
5988 if (b < 0)
5989 return res < a;
5990 return res > a;
969bf05e
AS
5991}
5992
3f50f132
JF
5993static bool signed_sub32_overflows(s32 a, s32 b)
5994{
bc895e8b 5995 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
5996 s32 res = (s32)((u32)a - (u32)b);
5997
5998 if (b < 0)
5999 return res < a;
6000 return res > a;
6001}
6002
bb7f0f98
AS
6003static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6004 const struct bpf_reg_state *reg,
6005 enum bpf_reg_type type)
6006{
6007 bool known = tnum_is_const(reg->var_off);
6008 s64 val = reg->var_off.value;
6009 s64 smin = reg->smin_value;
6010
6011 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6012 verbose(env, "math between %s pointer and %lld is not allowed\n",
6013 reg_type_str[type], val);
6014 return false;
6015 }
6016
6017 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6018 verbose(env, "%s pointer offset %d is not allowed\n",
6019 reg_type_str[type], reg->off);
6020 return false;
6021 }
6022
6023 if (smin == S64_MIN) {
6024 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6025 reg_type_str[type]);
6026 return false;
6027 }
6028
6029 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6030 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6031 smin, reg_type_str[type]);
6032 return false;
6033 }
6034
6035 return true;
6036}
6037
979d63d5
DB
6038static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6039{
6040 return &env->insn_aux_data[env->insn_idx];
6041}
6042
6043static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6044 u32 *ptr_limit, u8 opcode, bool off_is_neg)
6045{
6046 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6047 (opcode == BPF_SUB && !off_is_neg);
1b1597e6 6048 u32 off, max;
979d63d5
DB
6049
6050 switch (ptr_reg->type) {
6051 case PTR_TO_STACK:
1b1597e6
PK
6052 /* Offset 0 is out-of-bounds, but acceptable start for the
6053 * left direction, see BPF_REG_FP.
6054 */
6055 max = MAX_BPF_STACK + mask_to_left;
088ec26d
AI
6056 /* Indirect variable offset stack access is prohibited in
6057 * unprivileged mode so it's not handled here.
6058 */
979d63d5
DB
6059 off = ptr_reg->off + ptr_reg->var_off.value;
6060 if (mask_to_left)
6061 *ptr_limit = MAX_BPF_STACK + off;
6062 else
b5871dca 6063 *ptr_limit = -off - 1;
1b1597e6 6064 return *ptr_limit >= max ? -ERANGE : 0;
979d63d5 6065 case PTR_TO_MAP_VALUE:
1b1597e6 6066 max = ptr_reg->map_ptr->value_size;
979d63d5
DB
6067 if (mask_to_left) {
6068 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6069 } else {
6070 off = ptr_reg->smin_value + ptr_reg->off;
b5871dca 6071 *ptr_limit = ptr_reg->map_ptr->value_size - off - 1;
979d63d5 6072 }
1b1597e6 6073 return *ptr_limit >= max ? -ERANGE : 0;
979d63d5
DB
6074 default:
6075 return -EINVAL;
6076 }
6077}
6078
d3bd7413
DB
6079static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6080 const struct bpf_insn *insn)
6081{
2c78ee89 6082 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
6083}
6084
6085static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6086 u32 alu_state, u32 alu_limit)
6087{
6088 /* If we arrived here from different branches with different
6089 * state or limits to sanitize, then this won't work.
6090 */
6091 if (aux->alu_state &&
6092 (aux->alu_state != alu_state ||
6093 aux->alu_limit != alu_limit))
6094 return -EACCES;
6095
e6ac5933 6096 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
6097 aux->alu_state = alu_state;
6098 aux->alu_limit = alu_limit;
6099 return 0;
6100}
6101
6102static int sanitize_val_alu(struct bpf_verifier_env *env,
6103 struct bpf_insn *insn)
6104{
6105 struct bpf_insn_aux_data *aux = cur_aux(env);
6106
6107 if (can_skip_alu_sanitation(env, insn))
6108 return 0;
6109
6110 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6111}
6112
979d63d5
DB
6113static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6114 struct bpf_insn *insn,
6115 const struct bpf_reg_state *ptr_reg,
6116 struct bpf_reg_state *dst_reg,
6117 bool off_is_neg)
6118{
6119 struct bpf_verifier_state *vstate = env->cur_state;
6120 struct bpf_insn_aux_data *aux = cur_aux(env);
6121 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6122 u8 opcode = BPF_OP(insn->code);
6123 u32 alu_state, alu_limit;
6124 struct bpf_reg_state tmp;
6125 bool ret;
f232326f 6126 int err;
979d63d5 6127
d3bd7413 6128 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
6129 return 0;
6130
6131 /* We already marked aux for masking from non-speculative
6132 * paths, thus we got here in the first place. We only care
6133 * to explore bad access from here.
6134 */
6135 if (vstate->speculative)
6136 goto do_sim;
6137
6138 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6139 alu_state |= ptr_is_dst_reg ?
6140 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6141
f232326f
PK
6142 err = retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg);
6143 if (err < 0)
6144 return err;
6145
6146 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6147 if (err < 0)
6148 return err;
979d63d5
DB
6149do_sim:
6150 /* Simulate and find potential out-of-bounds access under
6151 * speculative execution from truncation as a result of
6152 * masking when off was not within expected range. If off
6153 * sits in dst, then we temporarily need to move ptr there
6154 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6155 * for cases where we use K-based arithmetic in one direction
6156 * and truncated reg-based in the other in order to explore
6157 * bad access.
6158 */
6159 if (!ptr_is_dst_reg) {
6160 tmp = *dst_reg;
6161 *dst_reg = *ptr_reg;
6162 }
6163 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 6164 if (!ptr_is_dst_reg && ret)
979d63d5
DB
6165 *dst_reg = tmp;
6166 return !ret ? -EFAULT : 0;
6167}
6168
01f810ac
AM
6169/* check that stack access falls within stack limits and that 'reg' doesn't
6170 * have a variable offset.
6171 *
6172 * Variable offset is prohibited for unprivileged mode for simplicity since it
6173 * requires corresponding support in Spectre masking for stack ALU. See also
6174 * retrieve_ptr_limit().
6175 *
6176 *
6177 * 'off' includes 'reg->off'.
6178 */
6179static int check_stack_access_for_ptr_arithmetic(
6180 struct bpf_verifier_env *env,
6181 int regno,
6182 const struct bpf_reg_state *reg,
6183 int off)
6184{
6185 if (!tnum_is_const(reg->var_off)) {
6186 char tn_buf[48];
6187
6188 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6189 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6190 regno, tn_buf, off);
6191 return -EACCES;
6192 }
6193
6194 if (off >= 0 || off < -MAX_BPF_STACK) {
6195 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6196 "prohibited for !root; off=%d\n", regno, off);
6197 return -EACCES;
6198 }
6199
6200 return 0;
6201}
6202
6203
f1174f77 6204/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
6205 * Caller should also handle BPF_MOV case separately.
6206 * If we return -EACCES, caller may want to try again treating pointer as a
6207 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6208 */
6209static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6210 struct bpf_insn *insn,
6211 const struct bpf_reg_state *ptr_reg,
6212 const struct bpf_reg_state *off_reg)
969bf05e 6213{
f4d7e40a
AS
6214 struct bpf_verifier_state *vstate = env->cur_state;
6215 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6216 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 6217 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
6218 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6219 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6220 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6221 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 6222 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 6223 u8 opcode = BPF_OP(insn->code);
979d63d5 6224 int ret;
969bf05e 6225
f1174f77 6226 dst_reg = &regs[dst];
969bf05e 6227
6f16101e
DB
6228 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6229 smin_val > smax_val || umin_val > umax_val) {
6230 /* Taint dst register if offset had invalid bounds derived from
6231 * e.g. dead branches.
6232 */
f54c7898 6233 __mark_reg_unknown(env, dst_reg);
6f16101e 6234 return 0;
f1174f77
EC
6235 }
6236
6237 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6238 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6239 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6240 __mark_reg_unknown(env, dst_reg);
6241 return 0;
6242 }
6243
82abbf8d
AS
6244 verbose(env,
6245 "R%d 32-bit pointer arithmetic prohibited\n",
6246 dst);
f1174f77 6247 return -EACCES;
969bf05e
AS
6248 }
6249
aad2eeaf
JS
6250 switch (ptr_reg->type) {
6251 case PTR_TO_MAP_VALUE_OR_NULL:
6252 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6253 dst, reg_type_str[ptr_reg->type]);
f1174f77 6254 return -EACCES;
aad2eeaf 6255 case CONST_PTR_TO_MAP:
7c696732
YS
6256 /* smin_val represents the known value */
6257 if (known && smin_val == 0 && opcode == BPF_ADD)
6258 break;
8731745e 6259 fallthrough;
aad2eeaf 6260 case PTR_TO_PACKET_END:
c64b7983
JS
6261 case PTR_TO_SOCKET:
6262 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6263 case PTR_TO_SOCK_COMMON:
6264 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6265 case PTR_TO_TCP_SOCK:
6266 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6267 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6268 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6269 dst, reg_type_str[ptr_reg->type]);
f1174f77 6270 return -EACCES;
9d7eceed
DB
6271 case PTR_TO_MAP_VALUE:
6272 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6273 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6274 off_reg == dst_reg ? dst : src);
6275 return -EACCES;
6276 }
df561f66 6277 fallthrough;
aad2eeaf
JS
6278 default:
6279 break;
f1174f77
EC
6280 }
6281
6282 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6283 * The id may be overwritten later if we create a new variable offset.
969bf05e 6284 */
f1174f77
EC
6285 dst_reg->type = ptr_reg->type;
6286 dst_reg->id = ptr_reg->id;
969bf05e 6287
bb7f0f98
AS
6288 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6289 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6290 return -EINVAL;
6291
3f50f132
JF
6292 /* pointer types do not carry 32-bit bounds at the moment. */
6293 __mark_reg32_unbounded(dst_reg);
6294
f1174f77
EC
6295 switch (opcode) {
6296 case BPF_ADD:
979d63d5
DB
6297 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6298 if (ret < 0) {
f232326f 6299 verbose(env, "R%d tried to add from different maps, paths, or prohibited types\n", dst);
979d63d5
DB
6300 return ret;
6301 }
f1174f77
EC
6302 /* We can take a fixed offset as long as it doesn't overflow
6303 * the s32 'off' field
969bf05e 6304 */
b03c9f9f
EC
6305 if (known && (ptr_reg->off + smin_val ==
6306 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6307 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6308 dst_reg->smin_value = smin_ptr;
6309 dst_reg->smax_value = smax_ptr;
6310 dst_reg->umin_value = umin_ptr;
6311 dst_reg->umax_value = umax_ptr;
f1174f77 6312 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6313 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6314 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6315 break;
6316 }
f1174f77
EC
6317 /* A new variable offset is created. Note that off_reg->off
6318 * == 0, since it's a scalar.
6319 * dst_reg gets the pointer type and since some positive
6320 * integer value was added to the pointer, give it a new 'id'
6321 * if it's a PTR_TO_PACKET.
6322 * this creates a new 'base' pointer, off_reg (variable) gets
6323 * added into the variable offset, and we copy the fixed offset
6324 * from ptr_reg.
969bf05e 6325 */
b03c9f9f
EC
6326 if (signed_add_overflows(smin_ptr, smin_val) ||
6327 signed_add_overflows(smax_ptr, smax_val)) {
6328 dst_reg->smin_value = S64_MIN;
6329 dst_reg->smax_value = S64_MAX;
6330 } else {
6331 dst_reg->smin_value = smin_ptr + smin_val;
6332 dst_reg->smax_value = smax_ptr + smax_val;
6333 }
6334 if (umin_ptr + umin_val < umin_ptr ||
6335 umax_ptr + umax_val < umax_ptr) {
6336 dst_reg->umin_value = 0;
6337 dst_reg->umax_value = U64_MAX;
6338 } else {
6339 dst_reg->umin_value = umin_ptr + umin_val;
6340 dst_reg->umax_value = umax_ptr + umax_val;
6341 }
f1174f77
EC
6342 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6343 dst_reg->off = ptr_reg->off;
0962590e 6344 dst_reg->raw = ptr_reg->raw;
de8f3a83 6345 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6346 dst_reg->id = ++env->id_gen;
6347 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6348 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6349 }
6350 break;
6351 case BPF_SUB:
979d63d5
DB
6352 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6353 if (ret < 0) {
f232326f 6354 verbose(env, "R%d tried to sub from different maps, paths, or prohibited types\n", dst);
979d63d5
DB
6355 return ret;
6356 }
f1174f77
EC
6357 if (dst_reg == off_reg) {
6358 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6359 verbose(env, "R%d tried to subtract pointer from scalar\n",
6360 dst);
f1174f77
EC
6361 return -EACCES;
6362 }
6363 /* We don't allow subtraction from FP, because (according to
6364 * test_verifier.c test "invalid fp arithmetic", JITs might not
6365 * be able to deal with it.
969bf05e 6366 */
f1174f77 6367 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6368 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6369 dst);
f1174f77
EC
6370 return -EACCES;
6371 }
b03c9f9f
EC
6372 if (known && (ptr_reg->off - smin_val ==
6373 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6374 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6375 dst_reg->smin_value = smin_ptr;
6376 dst_reg->smax_value = smax_ptr;
6377 dst_reg->umin_value = umin_ptr;
6378 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6379 dst_reg->var_off = ptr_reg->var_off;
6380 dst_reg->id = ptr_reg->id;
b03c9f9f 6381 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6382 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6383 break;
6384 }
f1174f77
EC
6385 /* A new variable offset is created. If the subtrahend is known
6386 * nonnegative, then any reg->range we had before is still good.
969bf05e 6387 */
b03c9f9f
EC
6388 if (signed_sub_overflows(smin_ptr, smax_val) ||
6389 signed_sub_overflows(smax_ptr, smin_val)) {
6390 /* Overflow possible, we know nothing */
6391 dst_reg->smin_value = S64_MIN;
6392 dst_reg->smax_value = S64_MAX;
6393 } else {
6394 dst_reg->smin_value = smin_ptr - smax_val;
6395 dst_reg->smax_value = smax_ptr - smin_val;
6396 }
6397 if (umin_ptr < umax_val) {
6398 /* Overflow possible, we know nothing */
6399 dst_reg->umin_value = 0;
6400 dst_reg->umax_value = U64_MAX;
6401 } else {
6402 /* Cannot overflow (as long as bounds are consistent) */
6403 dst_reg->umin_value = umin_ptr - umax_val;
6404 dst_reg->umax_value = umax_ptr - umin_val;
6405 }
f1174f77
EC
6406 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6407 dst_reg->off = ptr_reg->off;
0962590e 6408 dst_reg->raw = ptr_reg->raw;
de8f3a83 6409 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6410 dst_reg->id = ++env->id_gen;
6411 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6412 if (smin_val < 0)
22dc4a0f 6413 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6414 }
f1174f77
EC
6415 break;
6416 case BPF_AND:
6417 case BPF_OR:
6418 case BPF_XOR:
82abbf8d
AS
6419 /* bitwise ops on pointers are troublesome, prohibit. */
6420 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6421 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6422 return -EACCES;
6423 default:
6424 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6425 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6426 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6427 return -EACCES;
43188702
JF
6428 }
6429
bb7f0f98
AS
6430 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6431 return -EINVAL;
6432
b03c9f9f
EC
6433 __update_reg_bounds(dst_reg);
6434 __reg_deduce_bounds(dst_reg);
6435 __reg_bound_offset(dst_reg);
0d6303db
DB
6436
6437 /* For unprivileged we require that resulting offset must be in bounds
6438 * in order to be able to sanitize access later on.
6439 */
2c78ee89 6440 if (!env->bypass_spec_v1) {
e4298d25
DB
6441 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6442 check_map_access(env, dst, dst_reg->off, 1, false)) {
6443 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6444 "prohibited for !root\n", dst);
6445 return -EACCES;
6446 } else if (dst_reg->type == PTR_TO_STACK &&
01f810ac
AM
6447 check_stack_access_for_ptr_arithmetic(
6448 env, dst, dst_reg, dst_reg->off +
6449 dst_reg->var_off.value)) {
e4298d25
DB
6450 return -EACCES;
6451 }
0d6303db
DB
6452 }
6453
43188702
JF
6454 return 0;
6455}
6456
3f50f132
JF
6457static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6458 struct bpf_reg_state *src_reg)
6459{
6460 s32 smin_val = src_reg->s32_min_value;
6461 s32 smax_val = src_reg->s32_max_value;
6462 u32 umin_val = src_reg->u32_min_value;
6463 u32 umax_val = src_reg->u32_max_value;
6464
6465 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6466 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6467 dst_reg->s32_min_value = S32_MIN;
6468 dst_reg->s32_max_value = S32_MAX;
6469 } else {
6470 dst_reg->s32_min_value += smin_val;
6471 dst_reg->s32_max_value += smax_val;
6472 }
6473 if (dst_reg->u32_min_value + umin_val < umin_val ||
6474 dst_reg->u32_max_value + umax_val < umax_val) {
6475 dst_reg->u32_min_value = 0;
6476 dst_reg->u32_max_value = U32_MAX;
6477 } else {
6478 dst_reg->u32_min_value += umin_val;
6479 dst_reg->u32_max_value += umax_val;
6480 }
6481}
6482
07cd2631
JF
6483static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6484 struct bpf_reg_state *src_reg)
6485{
6486 s64 smin_val = src_reg->smin_value;
6487 s64 smax_val = src_reg->smax_value;
6488 u64 umin_val = src_reg->umin_value;
6489 u64 umax_val = src_reg->umax_value;
6490
6491 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6492 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6493 dst_reg->smin_value = S64_MIN;
6494 dst_reg->smax_value = S64_MAX;
6495 } else {
6496 dst_reg->smin_value += smin_val;
6497 dst_reg->smax_value += smax_val;
6498 }
6499 if (dst_reg->umin_value + umin_val < umin_val ||
6500 dst_reg->umax_value + umax_val < umax_val) {
6501 dst_reg->umin_value = 0;
6502 dst_reg->umax_value = U64_MAX;
6503 } else {
6504 dst_reg->umin_value += umin_val;
6505 dst_reg->umax_value += umax_val;
6506 }
3f50f132
JF
6507}
6508
6509static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6510 struct bpf_reg_state *src_reg)
6511{
6512 s32 smin_val = src_reg->s32_min_value;
6513 s32 smax_val = src_reg->s32_max_value;
6514 u32 umin_val = src_reg->u32_min_value;
6515 u32 umax_val = src_reg->u32_max_value;
6516
6517 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6518 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6519 /* Overflow possible, we know nothing */
6520 dst_reg->s32_min_value = S32_MIN;
6521 dst_reg->s32_max_value = S32_MAX;
6522 } else {
6523 dst_reg->s32_min_value -= smax_val;
6524 dst_reg->s32_max_value -= smin_val;
6525 }
6526 if (dst_reg->u32_min_value < umax_val) {
6527 /* Overflow possible, we know nothing */
6528 dst_reg->u32_min_value = 0;
6529 dst_reg->u32_max_value = U32_MAX;
6530 } else {
6531 /* Cannot overflow (as long as bounds are consistent) */
6532 dst_reg->u32_min_value -= umax_val;
6533 dst_reg->u32_max_value -= umin_val;
6534 }
07cd2631
JF
6535}
6536
6537static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6538 struct bpf_reg_state *src_reg)
6539{
6540 s64 smin_val = src_reg->smin_value;
6541 s64 smax_val = src_reg->smax_value;
6542 u64 umin_val = src_reg->umin_value;
6543 u64 umax_val = src_reg->umax_value;
6544
6545 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6546 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6547 /* Overflow possible, we know nothing */
6548 dst_reg->smin_value = S64_MIN;
6549 dst_reg->smax_value = S64_MAX;
6550 } else {
6551 dst_reg->smin_value -= smax_val;
6552 dst_reg->smax_value -= smin_val;
6553 }
6554 if (dst_reg->umin_value < umax_val) {
6555 /* Overflow possible, we know nothing */
6556 dst_reg->umin_value = 0;
6557 dst_reg->umax_value = U64_MAX;
6558 } else {
6559 /* Cannot overflow (as long as bounds are consistent) */
6560 dst_reg->umin_value -= umax_val;
6561 dst_reg->umax_value -= umin_val;
6562 }
3f50f132
JF
6563}
6564
6565static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6566 struct bpf_reg_state *src_reg)
6567{
6568 s32 smin_val = src_reg->s32_min_value;
6569 u32 umin_val = src_reg->u32_min_value;
6570 u32 umax_val = src_reg->u32_max_value;
6571
6572 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6573 /* Ain't nobody got time to multiply that sign */
6574 __mark_reg32_unbounded(dst_reg);
6575 return;
6576 }
6577 /* Both values are positive, so we can work with unsigned and
6578 * copy the result to signed (unless it exceeds S32_MAX).
6579 */
6580 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6581 /* Potential overflow, we know nothing */
6582 __mark_reg32_unbounded(dst_reg);
6583 return;
6584 }
6585 dst_reg->u32_min_value *= umin_val;
6586 dst_reg->u32_max_value *= umax_val;
6587 if (dst_reg->u32_max_value > S32_MAX) {
6588 /* Overflow possible, we know nothing */
6589 dst_reg->s32_min_value = S32_MIN;
6590 dst_reg->s32_max_value = S32_MAX;
6591 } else {
6592 dst_reg->s32_min_value = dst_reg->u32_min_value;
6593 dst_reg->s32_max_value = dst_reg->u32_max_value;
6594 }
07cd2631
JF
6595}
6596
6597static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6598 struct bpf_reg_state *src_reg)
6599{
6600 s64 smin_val = src_reg->smin_value;
6601 u64 umin_val = src_reg->umin_value;
6602 u64 umax_val = src_reg->umax_value;
6603
07cd2631
JF
6604 if (smin_val < 0 || dst_reg->smin_value < 0) {
6605 /* Ain't nobody got time to multiply that sign */
3f50f132 6606 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6607 return;
6608 }
6609 /* Both values are positive, so we can work with unsigned and
6610 * copy the result to signed (unless it exceeds S64_MAX).
6611 */
6612 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6613 /* Potential overflow, we know nothing */
3f50f132 6614 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6615 return;
6616 }
6617 dst_reg->umin_value *= umin_val;
6618 dst_reg->umax_value *= umax_val;
6619 if (dst_reg->umax_value > S64_MAX) {
6620 /* Overflow possible, we know nothing */
6621 dst_reg->smin_value = S64_MIN;
6622 dst_reg->smax_value = S64_MAX;
6623 } else {
6624 dst_reg->smin_value = dst_reg->umin_value;
6625 dst_reg->smax_value = dst_reg->umax_value;
6626 }
6627}
6628
3f50f132
JF
6629static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6630 struct bpf_reg_state *src_reg)
6631{
6632 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6633 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6634 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6635 s32 smin_val = src_reg->s32_min_value;
6636 u32 umax_val = src_reg->u32_max_value;
6637
6638 /* Assuming scalar64_min_max_and will be called so its safe
6639 * to skip updating register for known 32-bit case.
6640 */
6641 if (src_known && dst_known)
6642 return;
6643
6644 /* We get our minimum from the var_off, since that's inherently
6645 * bitwise. Our maximum is the minimum of the operands' maxima.
6646 */
6647 dst_reg->u32_min_value = var32_off.value;
6648 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6649 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6650 /* Lose signed bounds when ANDing negative numbers,
6651 * ain't nobody got time for that.
6652 */
6653 dst_reg->s32_min_value = S32_MIN;
6654 dst_reg->s32_max_value = S32_MAX;
6655 } else {
6656 /* ANDing two positives gives a positive, so safe to
6657 * cast result into s64.
6658 */
6659 dst_reg->s32_min_value = dst_reg->u32_min_value;
6660 dst_reg->s32_max_value = dst_reg->u32_max_value;
6661 }
6662
6663}
6664
07cd2631
JF
6665static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6666 struct bpf_reg_state *src_reg)
6667{
3f50f132
JF
6668 bool src_known = tnum_is_const(src_reg->var_off);
6669 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
6670 s64 smin_val = src_reg->smin_value;
6671 u64 umax_val = src_reg->umax_value;
6672
3f50f132 6673 if (src_known && dst_known) {
4fbb38a3 6674 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
6675 return;
6676 }
6677
07cd2631
JF
6678 /* We get our minimum from the var_off, since that's inherently
6679 * bitwise. Our maximum is the minimum of the operands' maxima.
6680 */
07cd2631
JF
6681 dst_reg->umin_value = dst_reg->var_off.value;
6682 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6683 if (dst_reg->smin_value < 0 || smin_val < 0) {
6684 /* Lose signed bounds when ANDing negative numbers,
6685 * ain't nobody got time for that.
6686 */
6687 dst_reg->smin_value = S64_MIN;
6688 dst_reg->smax_value = S64_MAX;
6689 } else {
6690 /* ANDing two positives gives a positive, so safe to
6691 * cast result into s64.
6692 */
6693 dst_reg->smin_value = dst_reg->umin_value;
6694 dst_reg->smax_value = dst_reg->umax_value;
6695 }
6696 /* We may learn something more from the var_off */
6697 __update_reg_bounds(dst_reg);
6698}
6699
3f50f132
JF
6700static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6701 struct bpf_reg_state *src_reg)
6702{
6703 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6704 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6705 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
6706 s32 smin_val = src_reg->s32_min_value;
6707 u32 umin_val = src_reg->u32_min_value;
3f50f132
JF
6708
6709 /* Assuming scalar64_min_max_or will be called so it is safe
6710 * to skip updating register for known case.
6711 */
6712 if (src_known && dst_known)
6713 return;
6714
6715 /* We get our maximum from the var_off, and our minimum is the
6716 * maximum of the operands' minima
6717 */
6718 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6719 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6720 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6721 /* Lose signed bounds when ORing negative numbers,
6722 * ain't nobody got time for that.
6723 */
6724 dst_reg->s32_min_value = S32_MIN;
6725 dst_reg->s32_max_value = S32_MAX;
6726 } else {
6727 /* ORing two positives gives a positive, so safe to
6728 * cast result into s64.
6729 */
5b9fbeb7
DB
6730 dst_reg->s32_min_value = dst_reg->u32_min_value;
6731 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
6732 }
6733}
6734
07cd2631
JF
6735static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6736 struct bpf_reg_state *src_reg)
6737{
3f50f132
JF
6738 bool src_known = tnum_is_const(src_reg->var_off);
6739 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
6740 s64 smin_val = src_reg->smin_value;
6741 u64 umin_val = src_reg->umin_value;
6742
3f50f132 6743 if (src_known && dst_known) {
4fbb38a3 6744 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
6745 return;
6746 }
6747
07cd2631
JF
6748 /* We get our maximum from the var_off, and our minimum is the
6749 * maximum of the operands' minima
6750 */
07cd2631
JF
6751 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6752 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6753 if (dst_reg->smin_value < 0 || smin_val < 0) {
6754 /* Lose signed bounds when ORing negative numbers,
6755 * ain't nobody got time for that.
6756 */
6757 dst_reg->smin_value = S64_MIN;
6758 dst_reg->smax_value = S64_MAX;
6759 } else {
6760 /* ORing two positives gives a positive, so safe to
6761 * cast result into s64.
6762 */
6763 dst_reg->smin_value = dst_reg->umin_value;
6764 dst_reg->smax_value = dst_reg->umax_value;
6765 }
6766 /* We may learn something more from the var_off */
6767 __update_reg_bounds(dst_reg);
6768}
6769
2921c90d
YS
6770static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6771 struct bpf_reg_state *src_reg)
6772{
6773 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6774 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6775 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6776 s32 smin_val = src_reg->s32_min_value;
6777
6778 /* Assuming scalar64_min_max_xor will be called so it is safe
6779 * to skip updating register for known case.
6780 */
6781 if (src_known && dst_known)
6782 return;
6783
6784 /* We get both minimum and maximum from the var32_off. */
6785 dst_reg->u32_min_value = var32_off.value;
6786 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6787
6788 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6789 /* XORing two positive sign numbers gives a positive,
6790 * so safe to cast u32 result into s32.
6791 */
6792 dst_reg->s32_min_value = dst_reg->u32_min_value;
6793 dst_reg->s32_max_value = dst_reg->u32_max_value;
6794 } else {
6795 dst_reg->s32_min_value = S32_MIN;
6796 dst_reg->s32_max_value = S32_MAX;
6797 }
6798}
6799
6800static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6801 struct bpf_reg_state *src_reg)
6802{
6803 bool src_known = tnum_is_const(src_reg->var_off);
6804 bool dst_known = tnum_is_const(dst_reg->var_off);
6805 s64 smin_val = src_reg->smin_value;
6806
6807 if (src_known && dst_known) {
6808 /* dst_reg->var_off.value has been updated earlier */
6809 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6810 return;
6811 }
6812
6813 /* We get both minimum and maximum from the var_off. */
6814 dst_reg->umin_value = dst_reg->var_off.value;
6815 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6816
6817 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6818 /* XORing two positive sign numbers gives a positive,
6819 * so safe to cast u64 result into s64.
6820 */
6821 dst_reg->smin_value = dst_reg->umin_value;
6822 dst_reg->smax_value = dst_reg->umax_value;
6823 } else {
6824 dst_reg->smin_value = S64_MIN;
6825 dst_reg->smax_value = S64_MAX;
6826 }
6827
6828 __update_reg_bounds(dst_reg);
6829}
6830
3f50f132
JF
6831static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6832 u64 umin_val, u64 umax_val)
07cd2631 6833{
07cd2631
JF
6834 /* We lose all sign bit information (except what we can pick
6835 * up from var_off)
6836 */
3f50f132
JF
6837 dst_reg->s32_min_value = S32_MIN;
6838 dst_reg->s32_max_value = S32_MAX;
6839 /* If we might shift our top bit out, then we know nothing */
6840 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6841 dst_reg->u32_min_value = 0;
6842 dst_reg->u32_max_value = U32_MAX;
6843 } else {
6844 dst_reg->u32_min_value <<= umin_val;
6845 dst_reg->u32_max_value <<= umax_val;
6846 }
6847}
6848
6849static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6850 struct bpf_reg_state *src_reg)
6851{
6852 u32 umax_val = src_reg->u32_max_value;
6853 u32 umin_val = src_reg->u32_min_value;
6854 /* u32 alu operation will zext upper bits */
6855 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6856
6857 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6858 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6859 /* Not required but being careful mark reg64 bounds as unknown so
6860 * that we are forced to pick them up from tnum and zext later and
6861 * if some path skips this step we are still safe.
6862 */
6863 __mark_reg64_unbounded(dst_reg);
6864 __update_reg32_bounds(dst_reg);
6865}
6866
6867static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6868 u64 umin_val, u64 umax_val)
6869{
6870 /* Special case <<32 because it is a common compiler pattern to sign
6871 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6872 * positive we know this shift will also be positive so we can track
6873 * bounds correctly. Otherwise we lose all sign bit information except
6874 * what we can pick up from var_off. Perhaps we can generalize this
6875 * later to shifts of any length.
6876 */
6877 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6878 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6879 else
6880 dst_reg->smax_value = S64_MAX;
6881
6882 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6883 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6884 else
6885 dst_reg->smin_value = S64_MIN;
6886
07cd2631
JF
6887 /* If we might shift our top bit out, then we know nothing */
6888 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6889 dst_reg->umin_value = 0;
6890 dst_reg->umax_value = U64_MAX;
6891 } else {
6892 dst_reg->umin_value <<= umin_val;
6893 dst_reg->umax_value <<= umax_val;
6894 }
3f50f132
JF
6895}
6896
6897static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6898 struct bpf_reg_state *src_reg)
6899{
6900 u64 umax_val = src_reg->umax_value;
6901 u64 umin_val = src_reg->umin_value;
6902
6903 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6904 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6905 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6906
07cd2631
JF
6907 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6908 /* We may learn something more from the var_off */
6909 __update_reg_bounds(dst_reg);
6910}
6911
3f50f132
JF
6912static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6913 struct bpf_reg_state *src_reg)
6914{
6915 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6916 u32 umax_val = src_reg->u32_max_value;
6917 u32 umin_val = src_reg->u32_min_value;
6918
6919 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6920 * be negative, then either:
6921 * 1) src_reg might be zero, so the sign bit of the result is
6922 * unknown, so we lose our signed bounds
6923 * 2) it's known negative, thus the unsigned bounds capture the
6924 * signed bounds
6925 * 3) the signed bounds cross zero, so they tell us nothing
6926 * about the result
6927 * If the value in dst_reg is known nonnegative, then again the
18b24d78 6928 * unsigned bounds capture the signed bounds.
3f50f132
JF
6929 * Thus, in all cases it suffices to blow away our signed bounds
6930 * and rely on inferring new ones from the unsigned bounds and
6931 * var_off of the result.
6932 */
6933 dst_reg->s32_min_value = S32_MIN;
6934 dst_reg->s32_max_value = S32_MAX;
6935
6936 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6937 dst_reg->u32_min_value >>= umax_val;
6938 dst_reg->u32_max_value >>= umin_val;
6939
6940 __mark_reg64_unbounded(dst_reg);
6941 __update_reg32_bounds(dst_reg);
6942}
6943
07cd2631
JF
6944static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6945 struct bpf_reg_state *src_reg)
6946{
6947 u64 umax_val = src_reg->umax_value;
6948 u64 umin_val = src_reg->umin_value;
6949
6950 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6951 * be negative, then either:
6952 * 1) src_reg might be zero, so the sign bit of the result is
6953 * unknown, so we lose our signed bounds
6954 * 2) it's known negative, thus the unsigned bounds capture the
6955 * signed bounds
6956 * 3) the signed bounds cross zero, so they tell us nothing
6957 * about the result
6958 * If the value in dst_reg is known nonnegative, then again the
18b24d78 6959 * unsigned bounds capture the signed bounds.
07cd2631
JF
6960 * Thus, in all cases it suffices to blow away our signed bounds
6961 * and rely on inferring new ones from the unsigned bounds and
6962 * var_off of the result.
6963 */
6964 dst_reg->smin_value = S64_MIN;
6965 dst_reg->smax_value = S64_MAX;
6966 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6967 dst_reg->umin_value >>= umax_val;
6968 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6969
6970 /* Its not easy to operate on alu32 bounds here because it depends
6971 * on bits being shifted in. Take easy way out and mark unbounded
6972 * so we can recalculate later from tnum.
6973 */
6974 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6975 __update_reg_bounds(dst_reg);
6976}
6977
3f50f132
JF
6978static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6979 struct bpf_reg_state *src_reg)
07cd2631 6980{
3f50f132 6981 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6982
6983 /* Upon reaching here, src_known is true and
6984 * umax_val is equal to umin_val.
6985 */
3f50f132
JF
6986 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6987 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6988
3f50f132
JF
6989 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6990
6991 /* blow away the dst_reg umin_value/umax_value and rely on
6992 * dst_reg var_off to refine the result.
6993 */
6994 dst_reg->u32_min_value = 0;
6995 dst_reg->u32_max_value = U32_MAX;
6996
6997 __mark_reg64_unbounded(dst_reg);
6998 __update_reg32_bounds(dst_reg);
6999}
7000
7001static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7002 struct bpf_reg_state *src_reg)
7003{
7004 u64 umin_val = src_reg->umin_value;
7005
7006 /* Upon reaching here, src_known is true and umax_val is equal
7007 * to umin_val.
7008 */
7009 dst_reg->smin_value >>= umin_val;
7010 dst_reg->smax_value >>= umin_val;
7011
7012 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
7013
7014 /* blow away the dst_reg umin_value/umax_value and rely on
7015 * dst_reg var_off to refine the result.
7016 */
7017 dst_reg->umin_value = 0;
7018 dst_reg->umax_value = U64_MAX;
3f50f132
JF
7019
7020 /* Its not easy to operate on alu32 bounds here because it depends
7021 * on bits being shifted in from upper 32-bits. Take easy way out
7022 * and mark unbounded so we can recalculate later from tnum.
7023 */
7024 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7025 __update_reg_bounds(dst_reg);
7026}
7027
468f6eaf
JH
7028/* WARNING: This function does calculations on 64-bit values, but the actual
7029 * execution may occur on 32-bit values. Therefore, things like bitshifts
7030 * need extra checks in the 32-bit case.
7031 */
f1174f77
EC
7032static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7033 struct bpf_insn *insn,
7034 struct bpf_reg_state *dst_reg,
7035 struct bpf_reg_state src_reg)
969bf05e 7036{
638f5b90 7037 struct bpf_reg_state *regs = cur_regs(env);
48461135 7038 u8 opcode = BPF_OP(insn->code);
b0b3fb67 7039 bool src_known;
b03c9f9f
EC
7040 s64 smin_val, smax_val;
7041 u64 umin_val, umax_val;
3f50f132
JF
7042 s32 s32_min_val, s32_max_val;
7043 u32 u32_min_val, u32_max_val;
468f6eaf 7044 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
7045 u32 dst = insn->dst_reg;
7046 int ret;
3f50f132 7047 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 7048
b03c9f9f
EC
7049 smin_val = src_reg.smin_value;
7050 smax_val = src_reg.smax_value;
7051 umin_val = src_reg.umin_value;
7052 umax_val = src_reg.umax_value;
f23cc643 7053
3f50f132
JF
7054 s32_min_val = src_reg.s32_min_value;
7055 s32_max_val = src_reg.s32_max_value;
7056 u32_min_val = src_reg.u32_min_value;
7057 u32_max_val = src_reg.u32_max_value;
7058
7059 if (alu32) {
7060 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
7061 if ((src_known &&
7062 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7063 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7064 /* Taint dst register if offset had invalid bounds
7065 * derived from e.g. dead branches.
7066 */
7067 __mark_reg_unknown(env, dst_reg);
7068 return 0;
7069 }
7070 } else {
7071 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
7072 if ((src_known &&
7073 (smin_val != smax_val || umin_val != umax_val)) ||
7074 smin_val > smax_val || umin_val > umax_val) {
7075 /* Taint dst register if offset had invalid bounds
7076 * derived from e.g. dead branches.
7077 */
7078 __mark_reg_unknown(env, dst_reg);
7079 return 0;
7080 }
6f16101e
DB
7081 }
7082
bb7f0f98
AS
7083 if (!src_known &&
7084 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 7085 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
7086 return 0;
7087 }
7088
3f50f132
JF
7089 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7090 * There are two classes of instructions: The first class we track both
7091 * alu32 and alu64 sign/unsigned bounds independently this provides the
7092 * greatest amount of precision when alu operations are mixed with jmp32
7093 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7094 * and BPF_OR. This is possible because these ops have fairly easy to
7095 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7096 * See alu32 verifier tests for examples. The second class of
7097 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7098 * with regards to tracking sign/unsigned bounds because the bits may
7099 * cross subreg boundaries in the alu64 case. When this happens we mark
7100 * the reg unbounded in the subreg bound space and use the resulting
7101 * tnum to calculate an approximation of the sign/unsigned bounds.
7102 */
48461135
JB
7103 switch (opcode) {
7104 case BPF_ADD:
d3bd7413
DB
7105 ret = sanitize_val_alu(env, insn);
7106 if (ret < 0) {
7107 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7108 return ret;
7109 }
3f50f132 7110 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 7111 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 7112 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
7113 break;
7114 case BPF_SUB:
d3bd7413
DB
7115 ret = sanitize_val_alu(env, insn);
7116 if (ret < 0) {
7117 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7118 return ret;
7119 }
3f50f132 7120 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 7121 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 7122 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
7123 break;
7124 case BPF_MUL:
3f50f132
JF
7125 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7126 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 7127 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
7128 break;
7129 case BPF_AND:
3f50f132
JF
7130 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7131 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 7132 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
7133 break;
7134 case BPF_OR:
3f50f132
JF
7135 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7136 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 7137 scalar_min_max_or(dst_reg, &src_reg);
48461135 7138 break;
2921c90d
YS
7139 case BPF_XOR:
7140 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7141 scalar32_min_max_xor(dst_reg, &src_reg);
7142 scalar_min_max_xor(dst_reg, &src_reg);
7143 break;
48461135 7144 case BPF_LSH:
468f6eaf
JH
7145 if (umax_val >= insn_bitness) {
7146 /* Shifts greater than 31 or 63 are undefined.
7147 * This includes shifts by a negative number.
b03c9f9f 7148 */
61bd5218 7149 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7150 break;
7151 }
3f50f132
JF
7152 if (alu32)
7153 scalar32_min_max_lsh(dst_reg, &src_reg);
7154 else
7155 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
7156 break;
7157 case BPF_RSH:
468f6eaf
JH
7158 if (umax_val >= insn_bitness) {
7159 /* Shifts greater than 31 or 63 are undefined.
7160 * This includes shifts by a negative number.
b03c9f9f 7161 */
61bd5218 7162 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7163 break;
7164 }
3f50f132
JF
7165 if (alu32)
7166 scalar32_min_max_rsh(dst_reg, &src_reg);
7167 else
7168 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 7169 break;
9cbe1f5a
YS
7170 case BPF_ARSH:
7171 if (umax_val >= insn_bitness) {
7172 /* Shifts greater than 31 or 63 are undefined.
7173 * This includes shifts by a negative number.
7174 */
7175 mark_reg_unknown(env, regs, insn->dst_reg);
7176 break;
7177 }
3f50f132
JF
7178 if (alu32)
7179 scalar32_min_max_arsh(dst_reg, &src_reg);
7180 else
7181 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 7182 break;
48461135 7183 default:
61bd5218 7184 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
7185 break;
7186 }
7187
3f50f132
JF
7188 /* ALU32 ops are zero extended into 64bit register */
7189 if (alu32)
7190 zext_32_to_64(dst_reg);
468f6eaf 7191
294f2fc6 7192 __update_reg_bounds(dst_reg);
b03c9f9f
EC
7193 __reg_deduce_bounds(dst_reg);
7194 __reg_bound_offset(dst_reg);
f1174f77
EC
7195 return 0;
7196}
7197
7198/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7199 * and var_off.
7200 */
7201static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7202 struct bpf_insn *insn)
7203{
f4d7e40a
AS
7204 struct bpf_verifier_state *vstate = env->cur_state;
7205 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7206 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
7207 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7208 u8 opcode = BPF_OP(insn->code);
b5dc0163 7209 int err;
f1174f77
EC
7210
7211 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
7212 src_reg = NULL;
7213 if (dst_reg->type != SCALAR_VALUE)
7214 ptr_reg = dst_reg;
75748837
AS
7215 else
7216 /* Make sure ID is cleared otherwise dst_reg min/max could be
7217 * incorrectly propagated into other registers by find_equal_scalars()
7218 */
7219 dst_reg->id = 0;
f1174f77
EC
7220 if (BPF_SRC(insn->code) == BPF_X) {
7221 src_reg = &regs[insn->src_reg];
f1174f77
EC
7222 if (src_reg->type != SCALAR_VALUE) {
7223 if (dst_reg->type != SCALAR_VALUE) {
7224 /* Combining two pointers by any ALU op yields
82abbf8d
AS
7225 * an arbitrary scalar. Disallow all math except
7226 * pointer subtraction
f1174f77 7227 */
dd066823 7228 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
7229 mark_reg_unknown(env, regs, insn->dst_reg);
7230 return 0;
f1174f77 7231 }
82abbf8d
AS
7232 verbose(env, "R%d pointer %s pointer prohibited\n",
7233 insn->dst_reg,
7234 bpf_alu_string[opcode >> 4]);
7235 return -EACCES;
f1174f77
EC
7236 } else {
7237 /* scalar += pointer
7238 * This is legal, but we have to reverse our
7239 * src/dest handling in computing the range
7240 */
b5dc0163
AS
7241 err = mark_chain_precision(env, insn->dst_reg);
7242 if (err)
7243 return err;
82abbf8d
AS
7244 return adjust_ptr_min_max_vals(env, insn,
7245 src_reg, dst_reg);
f1174f77
EC
7246 }
7247 } else if (ptr_reg) {
7248 /* pointer += scalar */
b5dc0163
AS
7249 err = mark_chain_precision(env, insn->src_reg);
7250 if (err)
7251 return err;
82abbf8d
AS
7252 return adjust_ptr_min_max_vals(env, insn,
7253 dst_reg, src_reg);
f1174f77
EC
7254 }
7255 } else {
7256 /* Pretend the src is a reg with a known value, since we only
7257 * need to be able to read from this state.
7258 */
7259 off_reg.type = SCALAR_VALUE;
b03c9f9f 7260 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7261 src_reg = &off_reg;
82abbf8d
AS
7262 if (ptr_reg) /* pointer += K */
7263 return adjust_ptr_min_max_vals(env, insn,
7264 ptr_reg, src_reg);
f1174f77
EC
7265 }
7266
7267 /* Got here implies adding two SCALAR_VALUEs */
7268 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7269 print_verifier_state(env, state);
61bd5218 7270 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7271 return -EINVAL;
7272 }
7273 if (WARN_ON(!src_reg)) {
f4d7e40a 7274 print_verifier_state(env, state);
61bd5218 7275 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7276 return -EINVAL;
7277 }
7278 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7279}
7280
17a52670 7281/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7282static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7283{
638f5b90 7284 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7285 u8 opcode = BPF_OP(insn->code);
7286 int err;
7287
7288 if (opcode == BPF_END || opcode == BPF_NEG) {
7289 if (opcode == BPF_NEG) {
7290 if (BPF_SRC(insn->code) != 0 ||
7291 insn->src_reg != BPF_REG_0 ||
7292 insn->off != 0 || insn->imm != 0) {
61bd5218 7293 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7294 return -EINVAL;
7295 }
7296 } else {
7297 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7298 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7299 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7300 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7301 return -EINVAL;
7302 }
7303 }
7304
7305 /* check src operand */
dc503a8a 7306 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7307 if (err)
7308 return err;
7309
1be7f75d 7310 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7311 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7312 insn->dst_reg);
7313 return -EACCES;
7314 }
7315
17a52670 7316 /* check dest operand */
dc503a8a 7317 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7318 if (err)
7319 return err;
7320
7321 } else if (opcode == BPF_MOV) {
7322
7323 if (BPF_SRC(insn->code) == BPF_X) {
7324 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7325 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7326 return -EINVAL;
7327 }
7328
7329 /* check src operand */
dc503a8a 7330 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7331 if (err)
7332 return err;
7333 } else {
7334 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7335 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7336 return -EINVAL;
7337 }
7338 }
7339
fbeb1603
AF
7340 /* check dest operand, mark as required later */
7341 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7342 if (err)
7343 return err;
7344
7345 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7346 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7347 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7348
17a52670
AS
7349 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7350 /* case: R1 = R2
7351 * copy register state to dest reg
7352 */
75748837
AS
7353 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7354 /* Assign src and dst registers the same ID
7355 * that will be used by find_equal_scalars()
7356 * to propagate min/max range.
7357 */
7358 src_reg->id = ++env->id_gen;
e434b8cd
JW
7359 *dst_reg = *src_reg;
7360 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7361 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7362 } else {
f1174f77 7363 /* R1 = (u32) R2 */
1be7f75d 7364 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7365 verbose(env,
7366 "R%d partial copy of pointer\n",
1be7f75d
AS
7367 insn->src_reg);
7368 return -EACCES;
e434b8cd
JW
7369 } else if (src_reg->type == SCALAR_VALUE) {
7370 *dst_reg = *src_reg;
75748837
AS
7371 /* Make sure ID is cleared otherwise
7372 * dst_reg min/max could be incorrectly
7373 * propagated into src_reg by find_equal_scalars()
7374 */
7375 dst_reg->id = 0;
e434b8cd 7376 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7377 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7378 } else {
7379 mark_reg_unknown(env, regs,
7380 insn->dst_reg);
1be7f75d 7381 }
3f50f132 7382 zext_32_to_64(dst_reg);
17a52670
AS
7383 }
7384 } else {
7385 /* case: R = imm
7386 * remember the value we stored into this reg
7387 */
fbeb1603
AF
7388 /* clear any state __mark_reg_known doesn't set */
7389 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7390 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7391 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7392 __mark_reg_known(regs + insn->dst_reg,
7393 insn->imm);
7394 } else {
7395 __mark_reg_known(regs + insn->dst_reg,
7396 (u32)insn->imm);
7397 }
17a52670
AS
7398 }
7399
7400 } else if (opcode > BPF_END) {
61bd5218 7401 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7402 return -EINVAL;
7403
7404 } else { /* all other ALU ops: and, sub, xor, add, ... */
7405
17a52670
AS
7406 if (BPF_SRC(insn->code) == BPF_X) {
7407 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7408 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7409 return -EINVAL;
7410 }
7411 /* check src1 operand */
dc503a8a 7412 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7413 if (err)
7414 return err;
7415 } else {
7416 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7417 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7418 return -EINVAL;
7419 }
7420 }
7421
7422 /* check src2 operand */
dc503a8a 7423 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7424 if (err)
7425 return err;
7426
7427 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7428 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7429 verbose(env, "div by zero\n");
17a52670
AS
7430 return -EINVAL;
7431 }
7432
229394e8
RV
7433 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7434 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7435 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7436
7437 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7438 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7439 return -EINVAL;
7440 }
7441 }
7442
1a0dc1ac 7443 /* check dest operand */
dc503a8a 7444 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7445 if (err)
7446 return err;
7447
f1174f77 7448 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7449 }
7450
7451 return 0;
7452}
7453
c6a9efa1
PC
7454static void __find_good_pkt_pointers(struct bpf_func_state *state,
7455 struct bpf_reg_state *dst_reg,
6d94e741 7456 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7457{
7458 struct bpf_reg_state *reg;
7459 int i;
7460
7461 for (i = 0; i < MAX_BPF_REG; i++) {
7462 reg = &state->regs[i];
7463 if (reg->type == type && reg->id == dst_reg->id)
7464 /* keep the maximum range already checked */
7465 reg->range = max(reg->range, new_range);
7466 }
7467
7468 bpf_for_each_spilled_reg(i, state, reg) {
7469 if (!reg)
7470 continue;
7471 if (reg->type == type && reg->id == dst_reg->id)
7472 reg->range = max(reg->range, new_range);
7473 }
7474}
7475
f4d7e40a 7476static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7477 struct bpf_reg_state *dst_reg,
f8ddadc4 7478 enum bpf_reg_type type,
fb2a311a 7479 bool range_right_open)
969bf05e 7480{
6d94e741 7481 int new_range, i;
2d2be8ca 7482
fb2a311a
DB
7483 if (dst_reg->off < 0 ||
7484 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7485 /* This doesn't give us any range */
7486 return;
7487
b03c9f9f
EC
7488 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7489 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7490 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7491 * than pkt_end, but that's because it's also less than pkt.
7492 */
7493 return;
7494
fb2a311a
DB
7495 new_range = dst_reg->off;
7496 if (range_right_open)
7497 new_range--;
7498
7499 /* Examples for register markings:
2d2be8ca 7500 *
fb2a311a 7501 * pkt_data in dst register:
2d2be8ca
DB
7502 *
7503 * r2 = r3;
7504 * r2 += 8;
7505 * if (r2 > pkt_end) goto <handle exception>
7506 * <access okay>
7507 *
b4e432f1
DB
7508 * r2 = r3;
7509 * r2 += 8;
7510 * if (r2 < pkt_end) goto <access okay>
7511 * <handle exception>
7512 *
2d2be8ca
DB
7513 * Where:
7514 * r2 == dst_reg, pkt_end == src_reg
7515 * r2=pkt(id=n,off=8,r=0)
7516 * r3=pkt(id=n,off=0,r=0)
7517 *
fb2a311a 7518 * pkt_data in src register:
2d2be8ca
DB
7519 *
7520 * r2 = r3;
7521 * r2 += 8;
7522 * if (pkt_end >= r2) goto <access okay>
7523 * <handle exception>
7524 *
b4e432f1
DB
7525 * r2 = r3;
7526 * r2 += 8;
7527 * if (pkt_end <= r2) goto <handle exception>
7528 * <access okay>
7529 *
2d2be8ca
DB
7530 * Where:
7531 * pkt_end == dst_reg, r2 == src_reg
7532 * r2=pkt(id=n,off=8,r=0)
7533 * r3=pkt(id=n,off=0,r=0)
7534 *
7535 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
7536 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7537 * and [r3, r3 + 8-1) respectively is safe to access depending on
7538 * the check.
969bf05e 7539 */
2d2be8ca 7540
f1174f77
EC
7541 /* If our ids match, then we must have the same max_value. And we
7542 * don't care about the other reg's fixed offset, since if it's too big
7543 * the range won't allow anything.
7544 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7545 */
c6a9efa1
PC
7546 for (i = 0; i <= vstate->curframe; i++)
7547 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7548 new_range);
969bf05e
AS
7549}
7550
3f50f132 7551static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 7552{
3f50f132
JF
7553 struct tnum subreg = tnum_subreg(reg->var_off);
7554 s32 sval = (s32)val;
a72dafaf 7555
3f50f132
JF
7556 switch (opcode) {
7557 case BPF_JEQ:
7558 if (tnum_is_const(subreg))
7559 return !!tnum_equals_const(subreg, val);
7560 break;
7561 case BPF_JNE:
7562 if (tnum_is_const(subreg))
7563 return !tnum_equals_const(subreg, val);
7564 break;
7565 case BPF_JSET:
7566 if ((~subreg.mask & subreg.value) & val)
7567 return 1;
7568 if (!((subreg.mask | subreg.value) & val))
7569 return 0;
7570 break;
7571 case BPF_JGT:
7572 if (reg->u32_min_value > val)
7573 return 1;
7574 else if (reg->u32_max_value <= val)
7575 return 0;
7576 break;
7577 case BPF_JSGT:
7578 if (reg->s32_min_value > sval)
7579 return 1;
ee114dd6 7580 else if (reg->s32_max_value <= sval)
3f50f132
JF
7581 return 0;
7582 break;
7583 case BPF_JLT:
7584 if (reg->u32_max_value < val)
7585 return 1;
7586 else if (reg->u32_min_value >= val)
7587 return 0;
7588 break;
7589 case BPF_JSLT:
7590 if (reg->s32_max_value < sval)
7591 return 1;
7592 else if (reg->s32_min_value >= sval)
7593 return 0;
7594 break;
7595 case BPF_JGE:
7596 if (reg->u32_min_value >= val)
7597 return 1;
7598 else if (reg->u32_max_value < val)
7599 return 0;
7600 break;
7601 case BPF_JSGE:
7602 if (reg->s32_min_value >= sval)
7603 return 1;
7604 else if (reg->s32_max_value < sval)
7605 return 0;
7606 break;
7607 case BPF_JLE:
7608 if (reg->u32_max_value <= val)
7609 return 1;
7610 else if (reg->u32_min_value > val)
7611 return 0;
7612 break;
7613 case BPF_JSLE:
7614 if (reg->s32_max_value <= sval)
7615 return 1;
7616 else if (reg->s32_min_value > sval)
7617 return 0;
7618 break;
7619 }
4f7b3e82 7620
3f50f132
JF
7621 return -1;
7622}
092ed096 7623
3f50f132
JF
7624
7625static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7626{
7627 s64 sval = (s64)val;
a72dafaf 7628
4f7b3e82
AS
7629 switch (opcode) {
7630 case BPF_JEQ:
7631 if (tnum_is_const(reg->var_off))
7632 return !!tnum_equals_const(reg->var_off, val);
7633 break;
7634 case BPF_JNE:
7635 if (tnum_is_const(reg->var_off))
7636 return !tnum_equals_const(reg->var_off, val);
7637 break;
960ea056
JK
7638 case BPF_JSET:
7639 if ((~reg->var_off.mask & reg->var_off.value) & val)
7640 return 1;
7641 if (!((reg->var_off.mask | reg->var_off.value) & val))
7642 return 0;
7643 break;
4f7b3e82
AS
7644 case BPF_JGT:
7645 if (reg->umin_value > val)
7646 return 1;
7647 else if (reg->umax_value <= val)
7648 return 0;
7649 break;
7650 case BPF_JSGT:
a72dafaf 7651 if (reg->smin_value > sval)
4f7b3e82 7652 return 1;
ee114dd6 7653 else if (reg->smax_value <= sval)
4f7b3e82
AS
7654 return 0;
7655 break;
7656 case BPF_JLT:
7657 if (reg->umax_value < val)
7658 return 1;
7659 else if (reg->umin_value >= val)
7660 return 0;
7661 break;
7662 case BPF_JSLT:
a72dafaf 7663 if (reg->smax_value < sval)
4f7b3e82 7664 return 1;
a72dafaf 7665 else if (reg->smin_value >= sval)
4f7b3e82
AS
7666 return 0;
7667 break;
7668 case BPF_JGE:
7669 if (reg->umin_value >= val)
7670 return 1;
7671 else if (reg->umax_value < val)
7672 return 0;
7673 break;
7674 case BPF_JSGE:
a72dafaf 7675 if (reg->smin_value >= sval)
4f7b3e82 7676 return 1;
a72dafaf 7677 else if (reg->smax_value < sval)
4f7b3e82
AS
7678 return 0;
7679 break;
7680 case BPF_JLE:
7681 if (reg->umax_value <= val)
7682 return 1;
7683 else if (reg->umin_value > val)
7684 return 0;
7685 break;
7686 case BPF_JSLE:
a72dafaf 7687 if (reg->smax_value <= sval)
4f7b3e82 7688 return 1;
a72dafaf 7689 else if (reg->smin_value > sval)
4f7b3e82
AS
7690 return 0;
7691 break;
7692 }
7693
7694 return -1;
7695}
7696
3f50f132
JF
7697/* compute branch direction of the expression "if (reg opcode val) goto target;"
7698 * and return:
7699 * 1 - branch will be taken and "goto target" will be executed
7700 * 0 - branch will not be taken and fall-through to next insn
7701 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7702 * range [0,10]
604dca5e 7703 */
3f50f132
JF
7704static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7705 bool is_jmp32)
604dca5e 7706{
cac616db
JF
7707 if (__is_pointer_value(false, reg)) {
7708 if (!reg_type_not_null(reg->type))
7709 return -1;
7710
7711 /* If pointer is valid tests against zero will fail so we can
7712 * use this to direct branch taken.
7713 */
7714 if (val != 0)
7715 return -1;
7716
7717 switch (opcode) {
7718 case BPF_JEQ:
7719 return 0;
7720 case BPF_JNE:
7721 return 1;
7722 default:
7723 return -1;
7724 }
7725 }
604dca5e 7726
3f50f132
JF
7727 if (is_jmp32)
7728 return is_branch32_taken(reg, val, opcode);
7729 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
7730}
7731
6d94e741
AS
7732static int flip_opcode(u32 opcode)
7733{
7734 /* How can we transform "a <op> b" into "b <op> a"? */
7735 static const u8 opcode_flip[16] = {
7736 /* these stay the same */
7737 [BPF_JEQ >> 4] = BPF_JEQ,
7738 [BPF_JNE >> 4] = BPF_JNE,
7739 [BPF_JSET >> 4] = BPF_JSET,
7740 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7741 [BPF_JGE >> 4] = BPF_JLE,
7742 [BPF_JGT >> 4] = BPF_JLT,
7743 [BPF_JLE >> 4] = BPF_JGE,
7744 [BPF_JLT >> 4] = BPF_JGT,
7745 [BPF_JSGE >> 4] = BPF_JSLE,
7746 [BPF_JSGT >> 4] = BPF_JSLT,
7747 [BPF_JSLE >> 4] = BPF_JSGE,
7748 [BPF_JSLT >> 4] = BPF_JSGT
7749 };
7750 return opcode_flip[opcode >> 4];
7751}
7752
7753static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7754 struct bpf_reg_state *src_reg,
7755 u8 opcode)
7756{
7757 struct bpf_reg_state *pkt;
7758
7759 if (src_reg->type == PTR_TO_PACKET_END) {
7760 pkt = dst_reg;
7761 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7762 pkt = src_reg;
7763 opcode = flip_opcode(opcode);
7764 } else {
7765 return -1;
7766 }
7767
7768 if (pkt->range >= 0)
7769 return -1;
7770
7771 switch (opcode) {
7772 case BPF_JLE:
7773 /* pkt <= pkt_end */
7774 fallthrough;
7775 case BPF_JGT:
7776 /* pkt > pkt_end */
7777 if (pkt->range == BEYOND_PKT_END)
7778 /* pkt has at last one extra byte beyond pkt_end */
7779 return opcode == BPF_JGT;
7780 break;
7781 case BPF_JLT:
7782 /* pkt < pkt_end */
7783 fallthrough;
7784 case BPF_JGE:
7785 /* pkt >= pkt_end */
7786 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7787 return opcode == BPF_JGE;
7788 break;
7789 }
7790 return -1;
7791}
7792
48461135
JB
7793/* Adjusts the register min/max values in the case that the dst_reg is the
7794 * variable register that we are working on, and src_reg is a constant or we're
7795 * simply doing a BPF_K check.
f1174f77 7796 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
7797 */
7798static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
7799 struct bpf_reg_state *false_reg,
7800 u64 val, u32 val32,
092ed096 7801 u8 opcode, bool is_jmp32)
48461135 7802{
3f50f132
JF
7803 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7804 struct tnum false_64off = false_reg->var_off;
7805 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7806 struct tnum true_64off = true_reg->var_off;
7807 s64 sval = (s64)val;
7808 s32 sval32 = (s32)val32;
a72dafaf 7809
f1174f77
EC
7810 /* If the dst_reg is a pointer, we can't learn anything about its
7811 * variable offset from the compare (unless src_reg were a pointer into
7812 * the same object, but we don't bother with that.
7813 * Since false_reg and true_reg have the same type by construction, we
7814 * only need to check one of them for pointerness.
7815 */
7816 if (__is_pointer_value(false, false_reg))
7817 return;
4cabc5b1 7818
48461135
JB
7819 switch (opcode) {
7820 case BPF_JEQ:
48461135 7821 case BPF_JNE:
a72dafaf
JW
7822 {
7823 struct bpf_reg_state *reg =
7824 opcode == BPF_JEQ ? true_reg : false_reg;
7825
e688c3db
AS
7826 /* JEQ/JNE comparison doesn't change the register equivalence.
7827 * r1 = r2;
7828 * if (r1 == 42) goto label;
7829 * ...
7830 * label: // here both r1 and r2 are known to be 42.
7831 *
7832 * Hence when marking register as known preserve it's ID.
48461135 7833 */
3f50f132
JF
7834 if (is_jmp32)
7835 __mark_reg32_known(reg, val32);
7836 else
e688c3db 7837 ___mark_reg_known(reg, val);
48461135 7838 break;
a72dafaf 7839 }
960ea056 7840 case BPF_JSET:
3f50f132
JF
7841 if (is_jmp32) {
7842 false_32off = tnum_and(false_32off, tnum_const(~val32));
7843 if (is_power_of_2(val32))
7844 true_32off = tnum_or(true_32off,
7845 tnum_const(val32));
7846 } else {
7847 false_64off = tnum_and(false_64off, tnum_const(~val));
7848 if (is_power_of_2(val))
7849 true_64off = tnum_or(true_64off,
7850 tnum_const(val));
7851 }
960ea056 7852 break;
48461135 7853 case BPF_JGE:
a72dafaf
JW
7854 case BPF_JGT:
7855 {
3f50f132
JF
7856 if (is_jmp32) {
7857 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7858 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7859
7860 false_reg->u32_max_value = min(false_reg->u32_max_value,
7861 false_umax);
7862 true_reg->u32_min_value = max(true_reg->u32_min_value,
7863 true_umin);
7864 } else {
7865 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7866 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7867
7868 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7869 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7870 }
b03c9f9f 7871 break;
a72dafaf 7872 }
48461135 7873 case BPF_JSGE:
a72dafaf
JW
7874 case BPF_JSGT:
7875 {
3f50f132
JF
7876 if (is_jmp32) {
7877 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7878 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 7879
3f50f132
JF
7880 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7881 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7882 } else {
7883 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7884 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7885
7886 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7887 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7888 }
48461135 7889 break;
a72dafaf 7890 }
b4e432f1 7891 case BPF_JLE:
a72dafaf
JW
7892 case BPF_JLT:
7893 {
3f50f132
JF
7894 if (is_jmp32) {
7895 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7896 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7897
7898 false_reg->u32_min_value = max(false_reg->u32_min_value,
7899 false_umin);
7900 true_reg->u32_max_value = min(true_reg->u32_max_value,
7901 true_umax);
7902 } else {
7903 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7904 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7905
7906 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7907 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7908 }
b4e432f1 7909 break;
a72dafaf 7910 }
b4e432f1 7911 case BPF_JSLE:
a72dafaf
JW
7912 case BPF_JSLT:
7913 {
3f50f132
JF
7914 if (is_jmp32) {
7915 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7916 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 7917
3f50f132
JF
7918 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7919 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7920 } else {
7921 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7922 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7923
7924 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7925 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7926 }
b4e432f1 7927 break;
a72dafaf 7928 }
48461135 7929 default:
0fc31b10 7930 return;
48461135
JB
7931 }
7932
3f50f132
JF
7933 if (is_jmp32) {
7934 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7935 tnum_subreg(false_32off));
7936 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7937 tnum_subreg(true_32off));
7938 __reg_combine_32_into_64(false_reg);
7939 __reg_combine_32_into_64(true_reg);
7940 } else {
7941 false_reg->var_off = false_64off;
7942 true_reg->var_off = true_64off;
7943 __reg_combine_64_into_32(false_reg);
7944 __reg_combine_64_into_32(true_reg);
7945 }
48461135
JB
7946}
7947
f1174f77
EC
7948/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7949 * the variable reg.
48461135
JB
7950 */
7951static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
7952 struct bpf_reg_state *false_reg,
7953 u64 val, u32 val32,
092ed096 7954 u8 opcode, bool is_jmp32)
48461135 7955{
6d94e741 7956 opcode = flip_opcode(opcode);
0fc31b10
JH
7957 /* This uses zero as "not present in table"; luckily the zero opcode,
7958 * BPF_JA, can't get here.
b03c9f9f 7959 */
0fc31b10 7960 if (opcode)
3f50f132 7961 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7962}
7963
7964/* Regs are known to be equal, so intersect their min/max/var_off */
7965static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7966 struct bpf_reg_state *dst_reg)
7967{
b03c9f9f
EC
7968 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7969 dst_reg->umin_value);
7970 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7971 dst_reg->umax_value);
7972 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7973 dst_reg->smin_value);
7974 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7975 dst_reg->smax_value);
f1174f77
EC
7976 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7977 dst_reg->var_off);
b03c9f9f
EC
7978 /* We might have learned new bounds from the var_off. */
7979 __update_reg_bounds(src_reg);
7980 __update_reg_bounds(dst_reg);
7981 /* We might have learned something about the sign bit. */
7982 __reg_deduce_bounds(src_reg);
7983 __reg_deduce_bounds(dst_reg);
7984 /* We might have learned some bits from the bounds. */
7985 __reg_bound_offset(src_reg);
7986 __reg_bound_offset(dst_reg);
7987 /* Intersecting with the old var_off might have improved our bounds
7988 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7989 * then new var_off is (0; 0x7f...fc) which improves our umax.
7990 */
7991 __update_reg_bounds(src_reg);
7992 __update_reg_bounds(dst_reg);
f1174f77
EC
7993}
7994
7995static void reg_combine_min_max(struct bpf_reg_state *true_src,
7996 struct bpf_reg_state *true_dst,
7997 struct bpf_reg_state *false_src,
7998 struct bpf_reg_state *false_dst,
7999 u8 opcode)
8000{
8001 switch (opcode) {
8002 case BPF_JEQ:
8003 __reg_combine_min_max(true_src, true_dst);
8004 break;
8005 case BPF_JNE:
8006 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 8007 break;
4cabc5b1 8008 }
48461135
JB
8009}
8010
fd978bf7
JS
8011static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8012 struct bpf_reg_state *reg, u32 id,
840b9615 8013 bool is_null)
57a09bf0 8014{
93c230e3
MKL
8015 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8016 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
8017 /* Old offset (both fixed and variable parts) should
8018 * have been known-zero, because we don't allow pointer
8019 * arithmetic on pointers that might be NULL.
8020 */
b03c9f9f
EC
8021 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8022 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 8023 reg->off)) {
b03c9f9f
EC
8024 __mark_reg_known_zero(reg);
8025 reg->off = 0;
f1174f77
EC
8026 }
8027 if (is_null) {
8028 reg->type = SCALAR_VALUE;
1b986589
MKL
8029 /* We don't need id and ref_obj_id from this point
8030 * onwards anymore, thus we should better reset it,
8031 * so that state pruning has chances to take effect.
8032 */
8033 reg->id = 0;
8034 reg->ref_obj_id = 0;
4ddb7416
DB
8035
8036 return;
8037 }
8038
8039 mark_ptr_not_null_reg(reg);
8040
8041 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
8042 /* For not-NULL ptr, reg->ref_obj_id will be reset
8043 * in release_reg_references().
8044 *
8045 * reg->id is still used by spin_lock ptr. Other
8046 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
8047 */
8048 reg->id = 0;
56f668df 8049 }
57a09bf0
TG
8050 }
8051}
8052
c6a9efa1
PC
8053static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8054 bool is_null)
8055{
8056 struct bpf_reg_state *reg;
8057 int i;
8058
8059 for (i = 0; i < MAX_BPF_REG; i++)
8060 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8061
8062 bpf_for_each_spilled_reg(i, state, reg) {
8063 if (!reg)
8064 continue;
8065 mark_ptr_or_null_reg(state, reg, id, is_null);
8066 }
8067}
8068
57a09bf0
TG
8069/* The logic is similar to find_good_pkt_pointers(), both could eventually
8070 * be folded together at some point.
8071 */
840b9615
JS
8072static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8073 bool is_null)
57a09bf0 8074{
f4d7e40a 8075 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 8076 struct bpf_reg_state *regs = state->regs;
1b986589 8077 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 8078 u32 id = regs[regno].id;
c6a9efa1 8079 int i;
57a09bf0 8080
1b986589
MKL
8081 if (ref_obj_id && ref_obj_id == id && is_null)
8082 /* regs[regno] is in the " == NULL" branch.
8083 * No one could have freed the reference state before
8084 * doing the NULL check.
8085 */
8086 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 8087
c6a9efa1
PC
8088 for (i = 0; i <= vstate->curframe; i++)
8089 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
8090}
8091
5beca081
DB
8092static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8093 struct bpf_reg_state *dst_reg,
8094 struct bpf_reg_state *src_reg,
8095 struct bpf_verifier_state *this_branch,
8096 struct bpf_verifier_state *other_branch)
8097{
8098 if (BPF_SRC(insn->code) != BPF_X)
8099 return false;
8100
092ed096
JW
8101 /* Pointers are always 64-bit. */
8102 if (BPF_CLASS(insn->code) == BPF_JMP32)
8103 return false;
8104
5beca081
DB
8105 switch (BPF_OP(insn->code)) {
8106 case BPF_JGT:
8107 if ((dst_reg->type == PTR_TO_PACKET &&
8108 src_reg->type == PTR_TO_PACKET_END) ||
8109 (dst_reg->type == PTR_TO_PACKET_META &&
8110 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8111 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8112 find_good_pkt_pointers(this_branch, dst_reg,
8113 dst_reg->type, false);
6d94e741 8114 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
8115 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8116 src_reg->type == PTR_TO_PACKET) ||
8117 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8118 src_reg->type == PTR_TO_PACKET_META)) {
8119 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8120 find_good_pkt_pointers(other_branch, src_reg,
8121 src_reg->type, true);
6d94e741 8122 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
8123 } else {
8124 return false;
8125 }
8126 break;
8127 case BPF_JLT:
8128 if ((dst_reg->type == PTR_TO_PACKET &&
8129 src_reg->type == PTR_TO_PACKET_END) ||
8130 (dst_reg->type == PTR_TO_PACKET_META &&
8131 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8132 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8133 find_good_pkt_pointers(other_branch, dst_reg,
8134 dst_reg->type, true);
6d94e741 8135 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
8136 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8137 src_reg->type == PTR_TO_PACKET) ||
8138 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8139 src_reg->type == PTR_TO_PACKET_META)) {
8140 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8141 find_good_pkt_pointers(this_branch, src_reg,
8142 src_reg->type, false);
6d94e741 8143 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
8144 } else {
8145 return false;
8146 }
8147 break;
8148 case BPF_JGE:
8149 if ((dst_reg->type == PTR_TO_PACKET &&
8150 src_reg->type == PTR_TO_PACKET_END) ||
8151 (dst_reg->type == PTR_TO_PACKET_META &&
8152 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8153 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8154 find_good_pkt_pointers(this_branch, dst_reg,
8155 dst_reg->type, true);
6d94e741 8156 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
8157 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8158 src_reg->type == PTR_TO_PACKET) ||
8159 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8160 src_reg->type == PTR_TO_PACKET_META)) {
8161 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8162 find_good_pkt_pointers(other_branch, src_reg,
8163 src_reg->type, false);
6d94e741 8164 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
8165 } else {
8166 return false;
8167 }
8168 break;
8169 case BPF_JLE:
8170 if ((dst_reg->type == PTR_TO_PACKET &&
8171 src_reg->type == PTR_TO_PACKET_END) ||
8172 (dst_reg->type == PTR_TO_PACKET_META &&
8173 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8174 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8175 find_good_pkt_pointers(other_branch, dst_reg,
8176 dst_reg->type, false);
6d94e741 8177 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
8178 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8179 src_reg->type == PTR_TO_PACKET) ||
8180 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8181 src_reg->type == PTR_TO_PACKET_META)) {
8182 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8183 find_good_pkt_pointers(this_branch, src_reg,
8184 src_reg->type, true);
6d94e741 8185 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
8186 } else {
8187 return false;
8188 }
8189 break;
8190 default:
8191 return false;
8192 }
8193
8194 return true;
8195}
8196
75748837
AS
8197static void find_equal_scalars(struct bpf_verifier_state *vstate,
8198 struct bpf_reg_state *known_reg)
8199{
8200 struct bpf_func_state *state;
8201 struct bpf_reg_state *reg;
8202 int i, j;
8203
8204 for (i = 0; i <= vstate->curframe; i++) {
8205 state = vstate->frame[i];
8206 for (j = 0; j < MAX_BPF_REG; j++) {
8207 reg = &state->regs[j];
8208 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8209 *reg = *known_reg;
8210 }
8211
8212 bpf_for_each_spilled_reg(j, state, reg) {
8213 if (!reg)
8214 continue;
8215 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8216 *reg = *known_reg;
8217 }
8218 }
8219}
8220
58e2af8b 8221static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8222 struct bpf_insn *insn, int *insn_idx)
8223{
f4d7e40a
AS
8224 struct bpf_verifier_state *this_branch = env->cur_state;
8225 struct bpf_verifier_state *other_branch;
8226 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8227 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8228 u8 opcode = BPF_OP(insn->code);
092ed096 8229 bool is_jmp32;
fb8d251e 8230 int pred = -1;
17a52670
AS
8231 int err;
8232
092ed096
JW
8233 /* Only conditional jumps are expected to reach here. */
8234 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8235 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8236 return -EINVAL;
8237 }
8238
8239 if (BPF_SRC(insn->code) == BPF_X) {
8240 if (insn->imm != 0) {
092ed096 8241 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8242 return -EINVAL;
8243 }
8244
8245 /* check src1 operand */
dc503a8a 8246 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8247 if (err)
8248 return err;
1be7f75d
AS
8249
8250 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8251 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8252 insn->src_reg);
8253 return -EACCES;
8254 }
fb8d251e 8255 src_reg = &regs[insn->src_reg];
17a52670
AS
8256 } else {
8257 if (insn->src_reg != BPF_REG_0) {
092ed096 8258 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8259 return -EINVAL;
8260 }
8261 }
8262
8263 /* check src2 operand */
dc503a8a 8264 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8265 if (err)
8266 return err;
8267
1a0dc1ac 8268 dst_reg = &regs[insn->dst_reg];
092ed096 8269 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8270
3f50f132
JF
8271 if (BPF_SRC(insn->code) == BPF_K) {
8272 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8273 } else if (src_reg->type == SCALAR_VALUE &&
8274 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8275 pred = is_branch_taken(dst_reg,
8276 tnum_subreg(src_reg->var_off).value,
8277 opcode,
8278 is_jmp32);
8279 } else if (src_reg->type == SCALAR_VALUE &&
8280 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8281 pred = is_branch_taken(dst_reg,
8282 src_reg->var_off.value,
8283 opcode,
8284 is_jmp32);
6d94e741
AS
8285 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8286 reg_is_pkt_pointer_any(src_reg) &&
8287 !is_jmp32) {
8288 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8289 }
8290
b5dc0163 8291 if (pred >= 0) {
cac616db
JF
8292 /* If we get here with a dst_reg pointer type it is because
8293 * above is_branch_taken() special cased the 0 comparison.
8294 */
8295 if (!__is_pointer_value(false, dst_reg))
8296 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8297 if (BPF_SRC(insn->code) == BPF_X && !err &&
8298 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8299 err = mark_chain_precision(env, insn->src_reg);
8300 if (err)
8301 return err;
8302 }
fb8d251e
AS
8303 if (pred == 1) {
8304 /* only follow the goto, ignore fall-through */
8305 *insn_idx += insn->off;
8306 return 0;
8307 } else if (pred == 0) {
8308 /* only follow fall-through branch, since
8309 * that's where the program will go
8310 */
8311 return 0;
17a52670
AS
8312 }
8313
979d63d5
DB
8314 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8315 false);
17a52670
AS
8316 if (!other_branch)
8317 return -EFAULT;
f4d7e40a 8318 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8319
48461135
JB
8320 /* detect if we are comparing against a constant value so we can adjust
8321 * our min/max values for our dst register.
f1174f77
EC
8322 * this is only legit if both are scalars (or pointers to the same
8323 * object, I suppose, but we don't support that right now), because
8324 * otherwise the different base pointers mean the offsets aren't
8325 * comparable.
48461135
JB
8326 */
8327 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8328 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8329
f1174f77 8330 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8331 src_reg->type == SCALAR_VALUE) {
8332 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8333 (is_jmp32 &&
8334 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8335 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8336 dst_reg,
3f50f132
JF
8337 src_reg->var_off.value,
8338 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8339 opcode, is_jmp32);
8340 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8341 (is_jmp32 &&
8342 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8343 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8344 src_reg,
3f50f132
JF
8345 dst_reg->var_off.value,
8346 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8347 opcode, is_jmp32);
8348 else if (!is_jmp32 &&
8349 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8350 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8351 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8352 &other_branch_regs[insn->dst_reg],
092ed096 8353 src_reg, dst_reg, opcode);
e688c3db
AS
8354 if (src_reg->id &&
8355 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8356 find_equal_scalars(this_branch, src_reg);
8357 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8358 }
8359
f1174f77
EC
8360 }
8361 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8362 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8363 dst_reg, insn->imm, (u32)insn->imm,
8364 opcode, is_jmp32);
48461135
JB
8365 }
8366
e688c3db
AS
8367 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8368 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8369 find_equal_scalars(this_branch, dst_reg);
8370 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8371 }
8372
092ed096
JW
8373 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8374 * NOTE: these optimizations below are related with pointer comparison
8375 * which will never be JMP32.
8376 */
8377 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8378 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8379 reg_type_may_be_null(dst_reg->type)) {
8380 /* Mark all identical registers in each branch as either
57a09bf0
TG
8381 * safe or unknown depending R == 0 or R != 0 conditional.
8382 */
840b9615
JS
8383 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8384 opcode == BPF_JNE);
8385 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8386 opcode == BPF_JEQ);
5beca081
DB
8387 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8388 this_branch, other_branch) &&
8389 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8390 verbose(env, "R%d pointer comparison prohibited\n",
8391 insn->dst_reg);
1be7f75d 8392 return -EACCES;
17a52670 8393 }
06ee7115 8394 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8395 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8396 return 0;
8397}
8398
17a52670 8399/* verify BPF_LD_IMM64 instruction */
58e2af8b 8400static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8401{
d8eca5bb 8402 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8403 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8404 struct bpf_reg_state *dst_reg;
d8eca5bb 8405 struct bpf_map *map;
17a52670
AS
8406 int err;
8407
8408 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8409 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8410 return -EINVAL;
8411 }
8412 if (insn->off != 0) {
61bd5218 8413 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8414 return -EINVAL;
8415 }
8416
dc503a8a 8417 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8418 if (err)
8419 return err;
8420
4976b718 8421 dst_reg = &regs[insn->dst_reg];
6b173873 8422 if (insn->src_reg == 0) {
6b173873
JK
8423 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8424
4976b718 8425 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8426 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8427 return 0;
6b173873 8428 }
17a52670 8429
4976b718
HL
8430 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8431 mark_reg_known_zero(env, regs, insn->dst_reg);
8432
8433 dst_reg->type = aux->btf_var.reg_type;
8434 switch (dst_reg->type) {
8435 case PTR_TO_MEM:
8436 dst_reg->mem_size = aux->btf_var.mem_size;
8437 break;
8438 case PTR_TO_BTF_ID:
eaa6bcb7 8439 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8440 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8441 dst_reg->btf_id = aux->btf_var.btf_id;
8442 break;
8443 default:
8444 verbose(env, "bpf verifier is misconfigured\n");
8445 return -EFAULT;
8446 }
8447 return 0;
8448 }
8449
69c087ba
YS
8450 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8451 struct bpf_prog_aux *aux = env->prog->aux;
8452 u32 subprogno = insn[1].imm;
8453
8454 if (!aux->func_info) {
8455 verbose(env, "missing btf func_info\n");
8456 return -EINVAL;
8457 }
8458 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8459 verbose(env, "callback function not static\n");
8460 return -EINVAL;
8461 }
8462
8463 dst_reg->type = PTR_TO_FUNC;
8464 dst_reg->subprogno = subprogno;
8465 return 0;
8466 }
8467
d8eca5bb
DB
8468 map = env->used_maps[aux->map_index];
8469 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8470 dst_reg->map_ptr = map;
d8eca5bb
DB
8471
8472 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
8473 dst_reg->type = PTR_TO_MAP_VALUE;
8474 dst_reg->off = aux->map_off;
d8eca5bb 8475 if (map_value_has_spin_lock(map))
4976b718 8476 dst_reg->id = ++env->id_gen;
d8eca5bb 8477 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 8478 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8479 } else {
8480 verbose(env, "bpf verifier is misconfigured\n");
8481 return -EINVAL;
8482 }
17a52670 8483
17a52670
AS
8484 return 0;
8485}
8486
96be4325
DB
8487static bool may_access_skb(enum bpf_prog_type type)
8488{
8489 switch (type) {
8490 case BPF_PROG_TYPE_SOCKET_FILTER:
8491 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 8492 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
8493 return true;
8494 default:
8495 return false;
8496 }
8497}
8498
ddd872bc
AS
8499/* verify safety of LD_ABS|LD_IND instructions:
8500 * - they can only appear in the programs where ctx == skb
8501 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8502 * preserve R6-R9, and store return value into R0
8503 *
8504 * Implicit input:
8505 * ctx == skb == R6 == CTX
8506 *
8507 * Explicit input:
8508 * SRC == any register
8509 * IMM == 32-bit immediate
8510 *
8511 * Output:
8512 * R0 - 8/16/32-bit skb data converted to cpu endianness
8513 */
58e2af8b 8514static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 8515{
638f5b90 8516 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 8517 static const int ctx_reg = BPF_REG_6;
ddd872bc 8518 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
8519 int i, err;
8520
7e40781c 8521 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 8522 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
8523 return -EINVAL;
8524 }
8525
e0cea7ce
DB
8526 if (!env->ops->gen_ld_abs) {
8527 verbose(env, "bpf verifier is misconfigured\n");
8528 return -EINVAL;
8529 }
8530
ddd872bc 8531 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 8532 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 8533 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 8534 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
8535 return -EINVAL;
8536 }
8537
8538 /* check whether implicit source operand (register R6) is readable */
6d4f151a 8539 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
8540 if (err)
8541 return err;
8542
fd978bf7
JS
8543 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8544 * gen_ld_abs() may terminate the program at runtime, leading to
8545 * reference leak.
8546 */
8547 err = check_reference_leak(env);
8548 if (err) {
8549 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8550 return err;
8551 }
8552
d83525ca
AS
8553 if (env->cur_state->active_spin_lock) {
8554 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8555 return -EINVAL;
8556 }
8557
6d4f151a 8558 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
8559 verbose(env,
8560 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
8561 return -EINVAL;
8562 }
8563
8564 if (mode == BPF_IND) {
8565 /* check explicit source operand */
dc503a8a 8566 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
8567 if (err)
8568 return err;
8569 }
8570
6d4f151a
DB
8571 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8572 if (err < 0)
8573 return err;
8574
ddd872bc 8575 /* reset caller saved regs to unreadable */
dc503a8a 8576 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 8577 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
8578 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8579 }
ddd872bc
AS
8580
8581 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
8582 * the value fetched from the packet.
8583 * Already marked as written above.
ddd872bc 8584 */
61bd5218 8585 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
8586 /* ld_abs load up to 32-bit skb data. */
8587 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
8588 return 0;
8589}
8590
390ee7e2
AS
8591static int check_return_code(struct bpf_verifier_env *env)
8592{
5cf1e914 8593 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 8594 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
8595 struct bpf_reg_state *reg;
8596 struct tnum range = tnum_range(0, 1);
7e40781c 8597 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 8598 int err;
f782e2c3 8599 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 8600
9e4e01df 8601 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
8602 if (!is_subprog &&
8603 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 8604 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
8605 !prog->aux->attach_func_proto->type)
8606 return 0;
8607
8608 /* eBPF calling convetion is such that R0 is used
8609 * to return the value from eBPF program.
8610 * Make sure that it's readable at this time
8611 * of bpf_exit, which means that program wrote
8612 * something into it earlier
8613 */
8614 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8615 if (err)
8616 return err;
8617
8618 if (is_pointer_value(env, BPF_REG_0)) {
8619 verbose(env, "R0 leaks addr as return value\n");
8620 return -EACCES;
8621 }
390ee7e2 8622
f782e2c3
DB
8623 reg = cur_regs(env) + BPF_REG_0;
8624 if (is_subprog) {
8625 if (reg->type != SCALAR_VALUE) {
8626 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8627 reg_type_str[reg->type]);
8628 return -EINVAL;
8629 }
8630 return 0;
8631 }
8632
7e40781c 8633 switch (prog_type) {
983695fa
DB
8634 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8635 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
8636 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8637 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8638 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8639 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8640 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 8641 range = tnum_range(1, 1);
77241217
SF
8642 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8643 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8644 range = tnum_range(0, 3);
ed4ed404 8645 break;
390ee7e2 8646 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 8647 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8648 range = tnum_range(0, 3);
8649 enforce_attach_type_range = tnum_range(2, 3);
8650 }
ed4ed404 8651 break;
390ee7e2
AS
8652 case BPF_PROG_TYPE_CGROUP_SOCK:
8653 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 8654 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 8655 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 8656 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 8657 break;
15ab09bd
AS
8658 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8659 if (!env->prog->aux->attach_btf_id)
8660 return 0;
8661 range = tnum_const(0);
8662 break;
15d83c4d 8663 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
8664 switch (env->prog->expected_attach_type) {
8665 case BPF_TRACE_FENTRY:
8666 case BPF_TRACE_FEXIT:
8667 range = tnum_const(0);
8668 break;
8669 case BPF_TRACE_RAW_TP:
8670 case BPF_MODIFY_RETURN:
15d83c4d 8671 return 0;
2ec0616e
DB
8672 case BPF_TRACE_ITER:
8673 break;
e92888c7
YS
8674 default:
8675 return -ENOTSUPP;
8676 }
15d83c4d 8677 break;
e9ddbb77
JS
8678 case BPF_PROG_TYPE_SK_LOOKUP:
8679 range = tnum_range(SK_DROP, SK_PASS);
8680 break;
e92888c7
YS
8681 case BPF_PROG_TYPE_EXT:
8682 /* freplace program can return anything as its return value
8683 * depends on the to-be-replaced kernel func or bpf program.
8684 */
390ee7e2
AS
8685 default:
8686 return 0;
8687 }
8688
390ee7e2 8689 if (reg->type != SCALAR_VALUE) {
61bd5218 8690 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
8691 reg_type_str[reg->type]);
8692 return -EINVAL;
8693 }
8694
8695 if (!tnum_in(range, reg->var_off)) {
bc2591d6 8696 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
8697 return -EINVAL;
8698 }
5cf1e914 8699
8700 if (!tnum_is_unknown(enforce_attach_type_range) &&
8701 tnum_in(enforce_attach_type_range, reg->var_off))
8702 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
8703 return 0;
8704}
8705
475fb78f
AS
8706/* non-recursive DFS pseudo code
8707 * 1 procedure DFS-iterative(G,v):
8708 * 2 label v as discovered
8709 * 3 let S be a stack
8710 * 4 S.push(v)
8711 * 5 while S is not empty
8712 * 6 t <- S.pop()
8713 * 7 if t is what we're looking for:
8714 * 8 return t
8715 * 9 for all edges e in G.adjacentEdges(t) do
8716 * 10 if edge e is already labelled
8717 * 11 continue with the next edge
8718 * 12 w <- G.adjacentVertex(t,e)
8719 * 13 if vertex w is not discovered and not explored
8720 * 14 label e as tree-edge
8721 * 15 label w as discovered
8722 * 16 S.push(w)
8723 * 17 continue at 5
8724 * 18 else if vertex w is discovered
8725 * 19 label e as back-edge
8726 * 20 else
8727 * 21 // vertex w is explored
8728 * 22 label e as forward- or cross-edge
8729 * 23 label t as explored
8730 * 24 S.pop()
8731 *
8732 * convention:
8733 * 0x10 - discovered
8734 * 0x11 - discovered and fall-through edge labelled
8735 * 0x12 - discovered and fall-through and branch edges labelled
8736 * 0x20 - explored
8737 */
8738
8739enum {
8740 DISCOVERED = 0x10,
8741 EXPLORED = 0x20,
8742 FALLTHROUGH = 1,
8743 BRANCH = 2,
8744};
8745
dc2a4ebc
AS
8746static u32 state_htab_size(struct bpf_verifier_env *env)
8747{
8748 return env->prog->len;
8749}
8750
5d839021
AS
8751static struct bpf_verifier_state_list **explored_state(
8752 struct bpf_verifier_env *env,
8753 int idx)
8754{
dc2a4ebc
AS
8755 struct bpf_verifier_state *cur = env->cur_state;
8756 struct bpf_func_state *state = cur->frame[cur->curframe];
8757
8758 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
8759}
8760
8761static void init_explored_state(struct bpf_verifier_env *env, int idx)
8762{
a8f500af 8763 env->insn_aux_data[idx].prune_point = true;
5d839021 8764}
f1bca824 8765
59e2e27d
WAF
8766enum {
8767 DONE_EXPLORING = 0,
8768 KEEP_EXPLORING = 1,
8769};
8770
475fb78f
AS
8771/* t, w, e - match pseudo-code above:
8772 * t - index of current instruction
8773 * w - next instruction
8774 * e - edge
8775 */
2589726d
AS
8776static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8777 bool loop_ok)
475fb78f 8778{
7df737e9
AS
8779 int *insn_stack = env->cfg.insn_stack;
8780 int *insn_state = env->cfg.insn_state;
8781
475fb78f 8782 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 8783 return DONE_EXPLORING;
475fb78f
AS
8784
8785 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 8786 return DONE_EXPLORING;
475fb78f
AS
8787
8788 if (w < 0 || w >= env->prog->len) {
d9762e84 8789 verbose_linfo(env, t, "%d: ", t);
61bd5218 8790 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
8791 return -EINVAL;
8792 }
8793
f1bca824
AS
8794 if (e == BRANCH)
8795 /* mark branch target for state pruning */
5d839021 8796 init_explored_state(env, w);
f1bca824 8797
475fb78f
AS
8798 if (insn_state[w] == 0) {
8799 /* tree-edge */
8800 insn_state[t] = DISCOVERED | e;
8801 insn_state[w] = DISCOVERED;
7df737e9 8802 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 8803 return -E2BIG;
7df737e9 8804 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 8805 return KEEP_EXPLORING;
475fb78f 8806 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 8807 if (loop_ok && env->bpf_capable)
59e2e27d 8808 return DONE_EXPLORING;
d9762e84
MKL
8809 verbose_linfo(env, t, "%d: ", t);
8810 verbose_linfo(env, w, "%d: ", w);
61bd5218 8811 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
8812 return -EINVAL;
8813 } else if (insn_state[w] == EXPLORED) {
8814 /* forward- or cross-edge */
8815 insn_state[t] = DISCOVERED | e;
8816 } else {
61bd5218 8817 verbose(env, "insn state internal bug\n");
475fb78f
AS
8818 return -EFAULT;
8819 }
59e2e27d
WAF
8820 return DONE_EXPLORING;
8821}
8822
efdb22de
YS
8823static int visit_func_call_insn(int t, int insn_cnt,
8824 struct bpf_insn *insns,
8825 struct bpf_verifier_env *env,
8826 bool visit_callee)
8827{
8828 int ret;
8829
8830 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8831 if (ret)
8832 return ret;
8833
8834 if (t + 1 < insn_cnt)
8835 init_explored_state(env, t + 1);
8836 if (visit_callee) {
8837 init_explored_state(env, t);
8838 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8839 env, false);
8840 }
8841 return ret;
8842}
8843
59e2e27d
WAF
8844/* Visits the instruction at index t and returns one of the following:
8845 * < 0 - an error occurred
8846 * DONE_EXPLORING - the instruction was fully explored
8847 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8848 */
8849static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8850{
8851 struct bpf_insn *insns = env->prog->insnsi;
8852 int ret;
8853
69c087ba
YS
8854 if (bpf_pseudo_func(insns + t))
8855 return visit_func_call_insn(t, insn_cnt, insns, env, true);
8856
59e2e27d
WAF
8857 /* All non-branch instructions have a single fall-through edge. */
8858 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8859 BPF_CLASS(insns[t].code) != BPF_JMP32)
8860 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8861
8862 switch (BPF_OP(insns[t].code)) {
8863 case BPF_EXIT:
8864 return DONE_EXPLORING;
8865
8866 case BPF_CALL:
efdb22de
YS
8867 return visit_func_call_insn(t, insn_cnt, insns, env,
8868 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
8869
8870 case BPF_JA:
8871 if (BPF_SRC(insns[t].code) != BPF_K)
8872 return -EINVAL;
8873
8874 /* unconditional jump with single edge */
8875 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8876 true);
8877 if (ret)
8878 return ret;
8879
8880 /* unconditional jmp is not a good pruning point,
8881 * but it's marked, since backtracking needs
8882 * to record jmp history in is_state_visited().
8883 */
8884 init_explored_state(env, t + insns[t].off + 1);
8885 /* tell verifier to check for equivalent states
8886 * after every call and jump
8887 */
8888 if (t + 1 < insn_cnt)
8889 init_explored_state(env, t + 1);
8890
8891 return ret;
8892
8893 default:
8894 /* conditional jump with two edges */
8895 init_explored_state(env, t);
8896 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8897 if (ret)
8898 return ret;
8899
8900 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8901 }
475fb78f
AS
8902}
8903
8904/* non-recursive depth-first-search to detect loops in BPF program
8905 * loop == back-edge in directed graph
8906 */
58e2af8b 8907static int check_cfg(struct bpf_verifier_env *env)
475fb78f 8908{
475fb78f 8909 int insn_cnt = env->prog->len;
7df737e9 8910 int *insn_stack, *insn_state;
475fb78f 8911 int ret = 0;
59e2e27d 8912 int i;
475fb78f 8913
7df737e9 8914 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
8915 if (!insn_state)
8916 return -ENOMEM;
8917
7df737e9 8918 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 8919 if (!insn_stack) {
71dde681 8920 kvfree(insn_state);
475fb78f
AS
8921 return -ENOMEM;
8922 }
8923
8924 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8925 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 8926 env->cfg.cur_stack = 1;
475fb78f 8927
59e2e27d
WAF
8928 while (env->cfg.cur_stack > 0) {
8929 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 8930
59e2e27d
WAF
8931 ret = visit_insn(t, insn_cnt, env);
8932 switch (ret) {
8933 case DONE_EXPLORING:
8934 insn_state[t] = EXPLORED;
8935 env->cfg.cur_stack--;
8936 break;
8937 case KEEP_EXPLORING:
8938 break;
8939 default:
8940 if (ret > 0) {
8941 verbose(env, "visit_insn internal bug\n");
8942 ret = -EFAULT;
475fb78f 8943 }
475fb78f 8944 goto err_free;
59e2e27d 8945 }
475fb78f
AS
8946 }
8947
59e2e27d 8948 if (env->cfg.cur_stack < 0) {
61bd5218 8949 verbose(env, "pop stack internal bug\n");
475fb78f
AS
8950 ret = -EFAULT;
8951 goto err_free;
8952 }
475fb78f 8953
475fb78f
AS
8954 for (i = 0; i < insn_cnt; i++) {
8955 if (insn_state[i] != EXPLORED) {
61bd5218 8956 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
8957 ret = -EINVAL;
8958 goto err_free;
8959 }
8960 }
8961 ret = 0; /* cfg looks good */
8962
8963err_free:
71dde681
AS
8964 kvfree(insn_state);
8965 kvfree(insn_stack);
7df737e9 8966 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
8967 return ret;
8968}
8969
09b28d76
AS
8970static int check_abnormal_return(struct bpf_verifier_env *env)
8971{
8972 int i;
8973
8974 for (i = 1; i < env->subprog_cnt; i++) {
8975 if (env->subprog_info[i].has_ld_abs) {
8976 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8977 return -EINVAL;
8978 }
8979 if (env->subprog_info[i].has_tail_call) {
8980 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8981 return -EINVAL;
8982 }
8983 }
8984 return 0;
8985}
8986
838e9690
YS
8987/* The minimum supported BTF func info size */
8988#define MIN_BPF_FUNCINFO_SIZE 8
8989#define MAX_FUNCINFO_REC_SIZE 252
8990
c454a46b
MKL
8991static int check_btf_func(struct bpf_verifier_env *env,
8992 const union bpf_attr *attr,
8993 union bpf_attr __user *uattr)
838e9690 8994{
09b28d76 8995 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 8996 u32 i, nfuncs, urec_size, min_size;
838e9690 8997 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 8998 struct bpf_func_info *krecord;
8c1b6e69 8999 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
9000 struct bpf_prog *prog;
9001 const struct btf *btf;
838e9690 9002 void __user *urecord;
d0b2818e 9003 u32 prev_offset = 0;
09b28d76 9004 bool scalar_return;
e7ed83d6 9005 int ret = -ENOMEM;
838e9690
YS
9006
9007 nfuncs = attr->func_info_cnt;
09b28d76
AS
9008 if (!nfuncs) {
9009 if (check_abnormal_return(env))
9010 return -EINVAL;
838e9690 9011 return 0;
09b28d76 9012 }
838e9690
YS
9013
9014 if (nfuncs != env->subprog_cnt) {
9015 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9016 return -EINVAL;
9017 }
9018
9019 urec_size = attr->func_info_rec_size;
9020 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9021 urec_size > MAX_FUNCINFO_REC_SIZE ||
9022 urec_size % sizeof(u32)) {
9023 verbose(env, "invalid func info rec size %u\n", urec_size);
9024 return -EINVAL;
9025 }
9026
c454a46b
MKL
9027 prog = env->prog;
9028 btf = prog->aux->btf;
838e9690
YS
9029
9030 urecord = u64_to_user_ptr(attr->func_info);
9031 min_size = min_t(u32, krec_size, urec_size);
9032
ba64e7d8 9033 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
9034 if (!krecord)
9035 return -ENOMEM;
8c1b6e69
AS
9036 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9037 if (!info_aux)
9038 goto err_free;
ba64e7d8 9039
838e9690
YS
9040 for (i = 0; i < nfuncs; i++) {
9041 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9042 if (ret) {
9043 if (ret == -E2BIG) {
9044 verbose(env, "nonzero tailing record in func info");
9045 /* set the size kernel expects so loader can zero
9046 * out the rest of the record.
9047 */
9048 if (put_user(min_size, &uattr->func_info_rec_size))
9049 ret = -EFAULT;
9050 }
c454a46b 9051 goto err_free;
838e9690
YS
9052 }
9053
ba64e7d8 9054 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 9055 ret = -EFAULT;
c454a46b 9056 goto err_free;
838e9690
YS
9057 }
9058
d30d42e0 9059 /* check insn_off */
09b28d76 9060 ret = -EINVAL;
838e9690 9061 if (i == 0) {
d30d42e0 9062 if (krecord[i].insn_off) {
838e9690 9063 verbose(env,
d30d42e0
MKL
9064 "nonzero insn_off %u for the first func info record",
9065 krecord[i].insn_off);
c454a46b 9066 goto err_free;
838e9690 9067 }
d30d42e0 9068 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
9069 verbose(env,
9070 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 9071 krecord[i].insn_off, prev_offset);
c454a46b 9072 goto err_free;
838e9690
YS
9073 }
9074
d30d42e0 9075 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 9076 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 9077 goto err_free;
838e9690
YS
9078 }
9079
9080 /* check type_id */
ba64e7d8 9081 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 9082 if (!type || !btf_type_is_func(type)) {
838e9690 9083 verbose(env, "invalid type id %d in func info",
ba64e7d8 9084 krecord[i].type_id);
c454a46b 9085 goto err_free;
838e9690 9086 }
51c39bb1 9087 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
9088
9089 func_proto = btf_type_by_id(btf, type->type);
9090 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9091 /* btf_func_check() already verified it during BTF load */
9092 goto err_free;
9093 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9094 scalar_return =
9095 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9096 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9097 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9098 goto err_free;
9099 }
9100 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9101 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9102 goto err_free;
9103 }
9104
d30d42e0 9105 prev_offset = krecord[i].insn_off;
838e9690
YS
9106 urecord += urec_size;
9107 }
9108
ba64e7d8
YS
9109 prog->aux->func_info = krecord;
9110 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 9111 prog->aux->func_info_aux = info_aux;
838e9690
YS
9112 return 0;
9113
c454a46b 9114err_free:
ba64e7d8 9115 kvfree(krecord);
8c1b6e69 9116 kfree(info_aux);
838e9690
YS
9117 return ret;
9118}
9119
ba64e7d8
YS
9120static void adjust_btf_func(struct bpf_verifier_env *env)
9121{
8c1b6e69 9122 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
9123 int i;
9124
8c1b6e69 9125 if (!aux->func_info)
ba64e7d8
YS
9126 return;
9127
9128 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 9129 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
9130}
9131
c454a46b
MKL
9132#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9133 sizeof(((struct bpf_line_info *)(0))->line_col))
9134#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9135
9136static int check_btf_line(struct bpf_verifier_env *env,
9137 const union bpf_attr *attr,
9138 union bpf_attr __user *uattr)
9139{
9140 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9141 struct bpf_subprog_info *sub;
9142 struct bpf_line_info *linfo;
9143 struct bpf_prog *prog;
9144 const struct btf *btf;
9145 void __user *ulinfo;
9146 int err;
9147
9148 nr_linfo = attr->line_info_cnt;
9149 if (!nr_linfo)
9150 return 0;
9151
9152 rec_size = attr->line_info_rec_size;
9153 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9154 rec_size > MAX_LINEINFO_REC_SIZE ||
9155 rec_size & (sizeof(u32) - 1))
9156 return -EINVAL;
9157
9158 /* Need to zero it in case the userspace may
9159 * pass in a smaller bpf_line_info object.
9160 */
9161 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9162 GFP_KERNEL | __GFP_NOWARN);
9163 if (!linfo)
9164 return -ENOMEM;
9165
9166 prog = env->prog;
9167 btf = prog->aux->btf;
9168
9169 s = 0;
9170 sub = env->subprog_info;
9171 ulinfo = u64_to_user_ptr(attr->line_info);
9172 expected_size = sizeof(struct bpf_line_info);
9173 ncopy = min_t(u32, expected_size, rec_size);
9174 for (i = 0; i < nr_linfo; i++) {
9175 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9176 if (err) {
9177 if (err == -E2BIG) {
9178 verbose(env, "nonzero tailing record in line_info");
9179 if (put_user(expected_size,
9180 &uattr->line_info_rec_size))
9181 err = -EFAULT;
9182 }
9183 goto err_free;
9184 }
9185
9186 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9187 err = -EFAULT;
9188 goto err_free;
9189 }
9190
9191 /*
9192 * Check insn_off to ensure
9193 * 1) strictly increasing AND
9194 * 2) bounded by prog->len
9195 *
9196 * The linfo[0].insn_off == 0 check logically falls into
9197 * the later "missing bpf_line_info for func..." case
9198 * because the first linfo[0].insn_off must be the
9199 * first sub also and the first sub must have
9200 * subprog_info[0].start == 0.
9201 */
9202 if ((i && linfo[i].insn_off <= prev_offset) ||
9203 linfo[i].insn_off >= prog->len) {
9204 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9205 i, linfo[i].insn_off, prev_offset,
9206 prog->len);
9207 err = -EINVAL;
9208 goto err_free;
9209 }
9210
fdbaa0be
MKL
9211 if (!prog->insnsi[linfo[i].insn_off].code) {
9212 verbose(env,
9213 "Invalid insn code at line_info[%u].insn_off\n",
9214 i);
9215 err = -EINVAL;
9216 goto err_free;
9217 }
9218
23127b33
MKL
9219 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9220 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
9221 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9222 err = -EINVAL;
9223 goto err_free;
9224 }
9225
9226 if (s != env->subprog_cnt) {
9227 if (linfo[i].insn_off == sub[s].start) {
9228 sub[s].linfo_idx = i;
9229 s++;
9230 } else if (sub[s].start < linfo[i].insn_off) {
9231 verbose(env, "missing bpf_line_info for func#%u\n", s);
9232 err = -EINVAL;
9233 goto err_free;
9234 }
9235 }
9236
9237 prev_offset = linfo[i].insn_off;
9238 ulinfo += rec_size;
9239 }
9240
9241 if (s != env->subprog_cnt) {
9242 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9243 env->subprog_cnt - s, s);
9244 err = -EINVAL;
9245 goto err_free;
9246 }
9247
9248 prog->aux->linfo = linfo;
9249 prog->aux->nr_linfo = nr_linfo;
9250
9251 return 0;
9252
9253err_free:
9254 kvfree(linfo);
9255 return err;
9256}
9257
9258static int check_btf_info(struct bpf_verifier_env *env,
9259 const union bpf_attr *attr,
9260 union bpf_attr __user *uattr)
9261{
9262 struct btf *btf;
9263 int err;
9264
09b28d76
AS
9265 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9266 if (check_abnormal_return(env))
9267 return -EINVAL;
c454a46b 9268 return 0;
09b28d76 9269 }
c454a46b
MKL
9270
9271 btf = btf_get_by_fd(attr->prog_btf_fd);
9272 if (IS_ERR(btf))
9273 return PTR_ERR(btf);
350a5c4d
AS
9274 if (btf_is_kernel(btf)) {
9275 btf_put(btf);
9276 return -EACCES;
9277 }
c454a46b
MKL
9278 env->prog->aux->btf = btf;
9279
9280 err = check_btf_func(env, attr, uattr);
9281 if (err)
9282 return err;
9283
9284 err = check_btf_line(env, attr, uattr);
9285 if (err)
9286 return err;
9287
9288 return 0;
ba64e7d8
YS
9289}
9290
f1174f77
EC
9291/* check %cur's range satisfies %old's */
9292static bool range_within(struct bpf_reg_state *old,
9293 struct bpf_reg_state *cur)
9294{
b03c9f9f
EC
9295 return old->umin_value <= cur->umin_value &&
9296 old->umax_value >= cur->umax_value &&
9297 old->smin_value <= cur->smin_value &&
fd675184
DB
9298 old->smax_value >= cur->smax_value &&
9299 old->u32_min_value <= cur->u32_min_value &&
9300 old->u32_max_value >= cur->u32_max_value &&
9301 old->s32_min_value <= cur->s32_min_value &&
9302 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9303}
9304
9305/* Maximum number of register states that can exist at once */
9306#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9307struct idpair {
9308 u32 old;
9309 u32 cur;
9310};
9311
9312/* If in the old state two registers had the same id, then they need to have
9313 * the same id in the new state as well. But that id could be different from
9314 * the old state, so we need to track the mapping from old to new ids.
9315 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9316 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9317 * regs with a different old id could still have new id 9, we don't care about
9318 * that.
9319 * So we look through our idmap to see if this old id has been seen before. If
9320 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9321 */
f1174f77 9322static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 9323{
f1174f77 9324 unsigned int i;
969bf05e 9325
f1174f77
EC
9326 for (i = 0; i < ID_MAP_SIZE; i++) {
9327 if (!idmap[i].old) {
9328 /* Reached an empty slot; haven't seen this id before */
9329 idmap[i].old = old_id;
9330 idmap[i].cur = cur_id;
9331 return true;
9332 }
9333 if (idmap[i].old == old_id)
9334 return idmap[i].cur == cur_id;
9335 }
9336 /* We ran out of idmap slots, which should be impossible */
9337 WARN_ON_ONCE(1);
9338 return false;
9339}
9340
9242b5f5
AS
9341static void clean_func_state(struct bpf_verifier_env *env,
9342 struct bpf_func_state *st)
9343{
9344 enum bpf_reg_liveness live;
9345 int i, j;
9346
9347 for (i = 0; i < BPF_REG_FP; i++) {
9348 live = st->regs[i].live;
9349 /* liveness must not touch this register anymore */
9350 st->regs[i].live |= REG_LIVE_DONE;
9351 if (!(live & REG_LIVE_READ))
9352 /* since the register is unused, clear its state
9353 * to make further comparison simpler
9354 */
f54c7898 9355 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9356 }
9357
9358 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9359 live = st->stack[i].spilled_ptr.live;
9360 /* liveness must not touch this stack slot anymore */
9361 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9362 if (!(live & REG_LIVE_READ)) {
f54c7898 9363 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9364 for (j = 0; j < BPF_REG_SIZE; j++)
9365 st->stack[i].slot_type[j] = STACK_INVALID;
9366 }
9367 }
9368}
9369
9370static void clean_verifier_state(struct bpf_verifier_env *env,
9371 struct bpf_verifier_state *st)
9372{
9373 int i;
9374
9375 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9376 /* all regs in this state in all frames were already marked */
9377 return;
9378
9379 for (i = 0; i <= st->curframe; i++)
9380 clean_func_state(env, st->frame[i]);
9381}
9382
9383/* the parentage chains form a tree.
9384 * the verifier states are added to state lists at given insn and
9385 * pushed into state stack for future exploration.
9386 * when the verifier reaches bpf_exit insn some of the verifer states
9387 * stored in the state lists have their final liveness state already,
9388 * but a lot of states will get revised from liveness point of view when
9389 * the verifier explores other branches.
9390 * Example:
9391 * 1: r0 = 1
9392 * 2: if r1 == 100 goto pc+1
9393 * 3: r0 = 2
9394 * 4: exit
9395 * when the verifier reaches exit insn the register r0 in the state list of
9396 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9397 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9398 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9399 *
9400 * Since the verifier pushes the branch states as it sees them while exploring
9401 * the program the condition of walking the branch instruction for the second
9402 * time means that all states below this branch were already explored and
9403 * their final liveness markes are already propagated.
9404 * Hence when the verifier completes the search of state list in is_state_visited()
9405 * we can call this clean_live_states() function to mark all liveness states
9406 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9407 * will not be used.
9408 * This function also clears the registers and stack for states that !READ
9409 * to simplify state merging.
9410 *
9411 * Important note here that walking the same branch instruction in the callee
9412 * doesn't meant that the states are DONE. The verifier has to compare
9413 * the callsites
9414 */
9415static void clean_live_states(struct bpf_verifier_env *env, int insn,
9416 struct bpf_verifier_state *cur)
9417{
9418 struct bpf_verifier_state_list *sl;
9419 int i;
9420
5d839021 9421 sl = *explored_state(env, insn);
a8f500af 9422 while (sl) {
2589726d
AS
9423 if (sl->state.branches)
9424 goto next;
dc2a4ebc
AS
9425 if (sl->state.insn_idx != insn ||
9426 sl->state.curframe != cur->curframe)
9242b5f5
AS
9427 goto next;
9428 for (i = 0; i <= cur->curframe; i++)
9429 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9430 goto next;
9431 clean_verifier_state(env, &sl->state);
9432next:
9433 sl = sl->next;
9434 }
9435}
9436
f1174f77 9437/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
9438static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9439 struct idpair *idmap)
f1174f77 9440{
f4d7e40a
AS
9441 bool equal;
9442
dc503a8a
EC
9443 if (!(rold->live & REG_LIVE_READ))
9444 /* explored state didn't use this */
9445 return true;
9446
679c782d 9447 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9448
9449 if (rold->type == PTR_TO_STACK)
9450 /* two stack pointers are equal only if they're pointing to
9451 * the same stack frame, since fp-8 in foo != fp-8 in bar
9452 */
9453 return equal && rold->frameno == rcur->frameno;
9454
9455 if (equal)
969bf05e
AS
9456 return true;
9457
f1174f77
EC
9458 if (rold->type == NOT_INIT)
9459 /* explored state can't have used this */
969bf05e 9460 return true;
f1174f77
EC
9461 if (rcur->type == NOT_INIT)
9462 return false;
9463 switch (rold->type) {
9464 case SCALAR_VALUE:
9465 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9466 if (!rold->precise && !rcur->precise)
9467 return true;
f1174f77
EC
9468 /* new val must satisfy old val knowledge */
9469 return range_within(rold, rcur) &&
9470 tnum_in(rold->var_off, rcur->var_off);
9471 } else {
179d1c56
JH
9472 /* We're trying to use a pointer in place of a scalar.
9473 * Even if the scalar was unbounded, this could lead to
9474 * pointer leaks because scalars are allowed to leak
9475 * while pointers are not. We could make this safe in
9476 * special cases if root is calling us, but it's
9477 * probably not worth the hassle.
f1174f77 9478 */
179d1c56 9479 return false;
f1174f77 9480 }
69c087ba 9481 case PTR_TO_MAP_KEY:
f1174f77 9482 case PTR_TO_MAP_VALUE:
1b688a19
EC
9483 /* If the new min/max/var_off satisfy the old ones and
9484 * everything else matches, we are OK.
d83525ca
AS
9485 * 'id' is not compared, since it's only used for maps with
9486 * bpf_spin_lock inside map element and in such cases if
9487 * the rest of the prog is valid for one map element then
9488 * it's valid for all map elements regardless of the key
9489 * used in bpf_map_lookup()
1b688a19
EC
9490 */
9491 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9492 range_within(rold, rcur) &&
9493 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
9494 case PTR_TO_MAP_VALUE_OR_NULL:
9495 /* a PTR_TO_MAP_VALUE could be safe to use as a
9496 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9497 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9498 * checked, doing so could have affected others with the same
9499 * id, and we can't check for that because we lost the id when
9500 * we converted to a PTR_TO_MAP_VALUE.
9501 */
9502 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9503 return false;
9504 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9505 return false;
9506 /* Check our ids match any regs they're supposed to */
9507 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 9508 case PTR_TO_PACKET_META:
f1174f77 9509 case PTR_TO_PACKET:
de8f3a83 9510 if (rcur->type != rold->type)
f1174f77
EC
9511 return false;
9512 /* We must have at least as much range as the old ptr
9513 * did, so that any accesses which were safe before are
9514 * still safe. This is true even if old range < old off,
9515 * since someone could have accessed through (ptr - k), or
9516 * even done ptr -= k in a register, to get a safe access.
9517 */
9518 if (rold->range > rcur->range)
9519 return false;
9520 /* If the offsets don't match, we can't trust our alignment;
9521 * nor can we be sure that we won't fall out of range.
9522 */
9523 if (rold->off != rcur->off)
9524 return false;
9525 /* id relations must be preserved */
9526 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9527 return false;
9528 /* new val must satisfy old val knowledge */
9529 return range_within(rold, rcur) &&
9530 tnum_in(rold->var_off, rcur->var_off);
9531 case PTR_TO_CTX:
9532 case CONST_PTR_TO_MAP:
f1174f77 9533 case PTR_TO_PACKET_END:
d58e468b 9534 case PTR_TO_FLOW_KEYS:
c64b7983
JS
9535 case PTR_TO_SOCKET:
9536 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9537 case PTR_TO_SOCK_COMMON:
9538 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9539 case PTR_TO_TCP_SOCK:
9540 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9541 case PTR_TO_XDP_SOCK:
f1174f77
EC
9542 /* Only valid matches are exact, which memcmp() above
9543 * would have accepted
9544 */
9545 default:
9546 /* Don't know what's going on, just say it's not safe */
9547 return false;
9548 }
969bf05e 9549
f1174f77
EC
9550 /* Shouldn't get here; if we do, say it's not safe */
9551 WARN_ON_ONCE(1);
969bf05e
AS
9552 return false;
9553}
9554
f4d7e40a
AS
9555static bool stacksafe(struct bpf_func_state *old,
9556 struct bpf_func_state *cur,
638f5b90
AS
9557 struct idpair *idmap)
9558{
9559 int i, spi;
9560
638f5b90
AS
9561 /* walk slots of the explored stack and ignore any additional
9562 * slots in the current stack, since explored(safe) state
9563 * didn't use them
9564 */
9565 for (i = 0; i < old->allocated_stack; i++) {
9566 spi = i / BPF_REG_SIZE;
9567
b233920c
AS
9568 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9569 i += BPF_REG_SIZE - 1;
cc2b14d5 9570 /* explored state didn't use this */
fd05e57b 9571 continue;
b233920c 9572 }
cc2b14d5 9573
638f5b90
AS
9574 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9575 continue;
19e2dbb7
AS
9576
9577 /* explored stack has more populated slots than current stack
9578 * and these slots were used
9579 */
9580 if (i >= cur->allocated_stack)
9581 return false;
9582
cc2b14d5
AS
9583 /* if old state was safe with misc data in the stack
9584 * it will be safe with zero-initialized stack.
9585 * The opposite is not true
9586 */
9587 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9588 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9589 continue;
638f5b90
AS
9590 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9591 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9592 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 9593 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
9594 * this verifier states are not equivalent,
9595 * return false to continue verification of this path
9596 */
9597 return false;
9598 if (i % BPF_REG_SIZE)
9599 continue;
9600 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9601 continue;
9602 if (!regsafe(&old->stack[spi].spilled_ptr,
9603 &cur->stack[spi].spilled_ptr,
9604 idmap))
9605 /* when explored and current stack slot are both storing
9606 * spilled registers, check that stored pointers types
9607 * are the same as well.
9608 * Ex: explored safe path could have stored
9609 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9610 * but current path has stored:
9611 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9612 * such verifier states are not equivalent.
9613 * return false to continue verification of this path
9614 */
9615 return false;
9616 }
9617 return true;
9618}
9619
fd978bf7
JS
9620static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9621{
9622 if (old->acquired_refs != cur->acquired_refs)
9623 return false;
9624 return !memcmp(old->refs, cur->refs,
9625 sizeof(*old->refs) * old->acquired_refs);
9626}
9627
f1bca824
AS
9628/* compare two verifier states
9629 *
9630 * all states stored in state_list are known to be valid, since
9631 * verifier reached 'bpf_exit' instruction through them
9632 *
9633 * this function is called when verifier exploring different branches of
9634 * execution popped from the state stack. If it sees an old state that has
9635 * more strict register state and more strict stack state then this execution
9636 * branch doesn't need to be explored further, since verifier already
9637 * concluded that more strict state leads to valid finish.
9638 *
9639 * Therefore two states are equivalent if register state is more conservative
9640 * and explored stack state is more conservative than the current one.
9641 * Example:
9642 * explored current
9643 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9644 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9645 *
9646 * In other words if current stack state (one being explored) has more
9647 * valid slots than old one that already passed validation, it means
9648 * the verifier can stop exploring and conclude that current state is valid too
9649 *
9650 * Similarly with registers. If explored state has register type as invalid
9651 * whereas register type in current state is meaningful, it means that
9652 * the current state will reach 'bpf_exit' instruction safely
9653 */
f4d7e40a
AS
9654static bool func_states_equal(struct bpf_func_state *old,
9655 struct bpf_func_state *cur)
f1bca824 9656{
f1174f77
EC
9657 struct idpair *idmap;
9658 bool ret = false;
f1bca824
AS
9659 int i;
9660
f1174f77
EC
9661 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9662 /* If we failed to allocate the idmap, just say it's not safe */
9663 if (!idmap)
1a0dc1ac 9664 return false;
f1174f77
EC
9665
9666 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 9667 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 9668 goto out_free;
f1bca824
AS
9669 }
9670
638f5b90
AS
9671 if (!stacksafe(old, cur, idmap))
9672 goto out_free;
fd978bf7
JS
9673
9674 if (!refsafe(old, cur))
9675 goto out_free;
f1174f77
EC
9676 ret = true;
9677out_free:
9678 kfree(idmap);
9679 return ret;
f1bca824
AS
9680}
9681
f4d7e40a
AS
9682static bool states_equal(struct bpf_verifier_env *env,
9683 struct bpf_verifier_state *old,
9684 struct bpf_verifier_state *cur)
9685{
9686 int i;
9687
9688 if (old->curframe != cur->curframe)
9689 return false;
9690
979d63d5
DB
9691 /* Verification state from speculative execution simulation
9692 * must never prune a non-speculative execution one.
9693 */
9694 if (old->speculative && !cur->speculative)
9695 return false;
9696
d83525ca
AS
9697 if (old->active_spin_lock != cur->active_spin_lock)
9698 return false;
9699
f4d7e40a
AS
9700 /* for states to be equal callsites have to be the same
9701 * and all frame states need to be equivalent
9702 */
9703 for (i = 0; i <= old->curframe; i++) {
9704 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9705 return false;
9706 if (!func_states_equal(old->frame[i], cur->frame[i]))
9707 return false;
9708 }
9709 return true;
9710}
9711
5327ed3d
JW
9712/* Return 0 if no propagation happened. Return negative error code if error
9713 * happened. Otherwise, return the propagated bit.
9714 */
55e7f3b5
JW
9715static int propagate_liveness_reg(struct bpf_verifier_env *env,
9716 struct bpf_reg_state *reg,
9717 struct bpf_reg_state *parent_reg)
9718{
5327ed3d
JW
9719 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9720 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
9721 int err;
9722
5327ed3d
JW
9723 /* When comes here, read flags of PARENT_REG or REG could be any of
9724 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9725 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9726 */
9727 if (parent_flag == REG_LIVE_READ64 ||
9728 /* Or if there is no read flag from REG. */
9729 !flag ||
9730 /* Or if the read flag from REG is the same as PARENT_REG. */
9731 parent_flag == flag)
55e7f3b5
JW
9732 return 0;
9733
5327ed3d 9734 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
9735 if (err)
9736 return err;
9737
5327ed3d 9738 return flag;
55e7f3b5
JW
9739}
9740
8e9cd9ce 9741/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
9742 * straight-line code between a state and its parent. When we arrive at an
9743 * equivalent state (jump target or such) we didn't arrive by the straight-line
9744 * code, so read marks in the state must propagate to the parent regardless
9745 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 9746 * in mark_reg_read() is for.
8e9cd9ce 9747 */
f4d7e40a
AS
9748static int propagate_liveness(struct bpf_verifier_env *env,
9749 const struct bpf_verifier_state *vstate,
9750 struct bpf_verifier_state *vparent)
dc503a8a 9751{
3f8cafa4 9752 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 9753 struct bpf_func_state *state, *parent;
3f8cafa4 9754 int i, frame, err = 0;
dc503a8a 9755
f4d7e40a
AS
9756 if (vparent->curframe != vstate->curframe) {
9757 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9758 vparent->curframe, vstate->curframe);
9759 return -EFAULT;
9760 }
dc503a8a
EC
9761 /* Propagate read liveness of registers... */
9762 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 9763 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
9764 parent = vparent->frame[frame];
9765 state = vstate->frame[frame];
9766 parent_reg = parent->regs;
9767 state_reg = state->regs;
83d16312
JK
9768 /* We don't need to worry about FP liveness, it's read-only */
9769 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
9770 err = propagate_liveness_reg(env, &state_reg[i],
9771 &parent_reg[i]);
5327ed3d 9772 if (err < 0)
3f8cafa4 9773 return err;
5327ed3d
JW
9774 if (err == REG_LIVE_READ64)
9775 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 9776 }
f4d7e40a 9777
1b04aee7 9778 /* Propagate stack slots. */
f4d7e40a
AS
9779 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9780 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
9781 parent_reg = &parent->stack[i].spilled_ptr;
9782 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
9783 err = propagate_liveness_reg(env, state_reg,
9784 parent_reg);
5327ed3d 9785 if (err < 0)
3f8cafa4 9786 return err;
dc503a8a
EC
9787 }
9788 }
5327ed3d 9789 return 0;
dc503a8a
EC
9790}
9791
a3ce685d
AS
9792/* find precise scalars in the previous equivalent state and
9793 * propagate them into the current state
9794 */
9795static int propagate_precision(struct bpf_verifier_env *env,
9796 const struct bpf_verifier_state *old)
9797{
9798 struct bpf_reg_state *state_reg;
9799 struct bpf_func_state *state;
9800 int i, err = 0;
9801
9802 state = old->frame[old->curframe];
9803 state_reg = state->regs;
9804 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9805 if (state_reg->type != SCALAR_VALUE ||
9806 !state_reg->precise)
9807 continue;
9808 if (env->log.level & BPF_LOG_LEVEL2)
9809 verbose(env, "propagating r%d\n", i);
9810 err = mark_chain_precision(env, i);
9811 if (err < 0)
9812 return err;
9813 }
9814
9815 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9816 if (state->stack[i].slot_type[0] != STACK_SPILL)
9817 continue;
9818 state_reg = &state->stack[i].spilled_ptr;
9819 if (state_reg->type != SCALAR_VALUE ||
9820 !state_reg->precise)
9821 continue;
9822 if (env->log.level & BPF_LOG_LEVEL2)
9823 verbose(env, "propagating fp%d\n",
9824 (-i - 1) * BPF_REG_SIZE);
9825 err = mark_chain_precision_stack(env, i);
9826 if (err < 0)
9827 return err;
9828 }
9829 return 0;
9830}
9831
2589726d
AS
9832static bool states_maybe_looping(struct bpf_verifier_state *old,
9833 struct bpf_verifier_state *cur)
9834{
9835 struct bpf_func_state *fold, *fcur;
9836 int i, fr = cur->curframe;
9837
9838 if (old->curframe != fr)
9839 return false;
9840
9841 fold = old->frame[fr];
9842 fcur = cur->frame[fr];
9843 for (i = 0; i < MAX_BPF_REG; i++)
9844 if (memcmp(&fold->regs[i], &fcur->regs[i],
9845 offsetof(struct bpf_reg_state, parent)))
9846 return false;
9847 return true;
9848}
9849
9850
58e2af8b 9851static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 9852{
58e2af8b 9853 struct bpf_verifier_state_list *new_sl;
9f4686c4 9854 struct bpf_verifier_state_list *sl, **pprev;
679c782d 9855 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 9856 int i, j, err, states_cnt = 0;
10d274e8 9857 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 9858
b5dc0163 9859 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 9860 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
9861 /* this 'insn_idx' instruction wasn't marked, so we will not
9862 * be doing state search here
9863 */
9864 return 0;
9865
2589726d
AS
9866 /* bpf progs typically have pruning point every 4 instructions
9867 * http://vger.kernel.org/bpfconf2019.html#session-1
9868 * Do not add new state for future pruning if the verifier hasn't seen
9869 * at least 2 jumps and at least 8 instructions.
9870 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9871 * In tests that amounts to up to 50% reduction into total verifier
9872 * memory consumption and 20% verifier time speedup.
9873 */
9874 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9875 env->insn_processed - env->prev_insn_processed >= 8)
9876 add_new_state = true;
9877
a8f500af
AS
9878 pprev = explored_state(env, insn_idx);
9879 sl = *pprev;
9880
9242b5f5
AS
9881 clean_live_states(env, insn_idx, cur);
9882
a8f500af 9883 while (sl) {
dc2a4ebc
AS
9884 states_cnt++;
9885 if (sl->state.insn_idx != insn_idx)
9886 goto next;
2589726d
AS
9887 if (sl->state.branches) {
9888 if (states_maybe_looping(&sl->state, cur) &&
9889 states_equal(env, &sl->state, cur)) {
9890 verbose_linfo(env, insn_idx, "; ");
9891 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9892 return -EINVAL;
9893 }
9894 /* if the verifier is processing a loop, avoid adding new state
9895 * too often, since different loop iterations have distinct
9896 * states and may not help future pruning.
9897 * This threshold shouldn't be too low to make sure that
9898 * a loop with large bound will be rejected quickly.
9899 * The most abusive loop will be:
9900 * r1 += 1
9901 * if r1 < 1000000 goto pc-2
9902 * 1M insn_procssed limit / 100 == 10k peak states.
9903 * This threshold shouldn't be too high either, since states
9904 * at the end of the loop are likely to be useful in pruning.
9905 */
9906 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9907 env->insn_processed - env->prev_insn_processed < 100)
9908 add_new_state = false;
9909 goto miss;
9910 }
638f5b90 9911 if (states_equal(env, &sl->state, cur)) {
9f4686c4 9912 sl->hit_cnt++;
f1bca824 9913 /* reached equivalent register/stack state,
dc503a8a
EC
9914 * prune the search.
9915 * Registers read by the continuation are read by us.
8e9cd9ce
EC
9916 * If we have any write marks in env->cur_state, they
9917 * will prevent corresponding reads in the continuation
9918 * from reaching our parent (an explored_state). Our
9919 * own state will get the read marks recorded, but
9920 * they'll be immediately forgotten as we're pruning
9921 * this state and will pop a new one.
f1bca824 9922 */
f4d7e40a 9923 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
9924
9925 /* if previous state reached the exit with precision and
9926 * current state is equivalent to it (except precsion marks)
9927 * the precision needs to be propagated back in
9928 * the current state.
9929 */
9930 err = err ? : push_jmp_history(env, cur);
9931 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
9932 if (err)
9933 return err;
f1bca824 9934 return 1;
dc503a8a 9935 }
2589726d
AS
9936miss:
9937 /* when new state is not going to be added do not increase miss count.
9938 * Otherwise several loop iterations will remove the state
9939 * recorded earlier. The goal of these heuristics is to have
9940 * states from some iterations of the loop (some in the beginning
9941 * and some at the end) to help pruning.
9942 */
9943 if (add_new_state)
9944 sl->miss_cnt++;
9f4686c4
AS
9945 /* heuristic to determine whether this state is beneficial
9946 * to keep checking from state equivalence point of view.
9947 * Higher numbers increase max_states_per_insn and verification time,
9948 * but do not meaningfully decrease insn_processed.
9949 */
9950 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9951 /* the state is unlikely to be useful. Remove it to
9952 * speed up verification
9953 */
9954 *pprev = sl->next;
9955 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
9956 u32 br = sl->state.branches;
9957
9958 WARN_ONCE(br,
9959 "BUG live_done but branches_to_explore %d\n",
9960 br);
9f4686c4
AS
9961 free_verifier_state(&sl->state, false);
9962 kfree(sl);
9963 env->peak_states--;
9964 } else {
9965 /* cannot free this state, since parentage chain may
9966 * walk it later. Add it for free_list instead to
9967 * be freed at the end of verification
9968 */
9969 sl->next = env->free_list;
9970 env->free_list = sl;
9971 }
9972 sl = *pprev;
9973 continue;
9974 }
dc2a4ebc 9975next:
9f4686c4
AS
9976 pprev = &sl->next;
9977 sl = *pprev;
f1bca824
AS
9978 }
9979
06ee7115
AS
9980 if (env->max_states_per_insn < states_cnt)
9981 env->max_states_per_insn = states_cnt;
9982
2c78ee89 9983 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 9984 return push_jmp_history(env, cur);
ceefbc96 9985
2589726d 9986 if (!add_new_state)
b5dc0163 9987 return push_jmp_history(env, cur);
ceefbc96 9988
2589726d
AS
9989 /* There were no equivalent states, remember the current one.
9990 * Technically the current state is not proven to be safe yet,
f4d7e40a 9991 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 9992 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 9993 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
9994 * again on the way to bpf_exit.
9995 * When looping the sl->state.branches will be > 0 and this state
9996 * will not be considered for equivalence until branches == 0.
f1bca824 9997 */
638f5b90 9998 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
9999 if (!new_sl)
10000 return -ENOMEM;
06ee7115
AS
10001 env->total_states++;
10002 env->peak_states++;
2589726d
AS
10003 env->prev_jmps_processed = env->jmps_processed;
10004 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
10005
10006 /* add new state to the head of linked list */
679c782d
EC
10007 new = &new_sl->state;
10008 err = copy_verifier_state(new, cur);
1969db47 10009 if (err) {
679c782d 10010 free_verifier_state(new, false);
1969db47
AS
10011 kfree(new_sl);
10012 return err;
10013 }
dc2a4ebc 10014 new->insn_idx = insn_idx;
2589726d
AS
10015 WARN_ONCE(new->branches != 1,
10016 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 10017
2589726d 10018 cur->parent = new;
b5dc0163
AS
10019 cur->first_insn_idx = insn_idx;
10020 clear_jmp_history(cur);
5d839021
AS
10021 new_sl->next = *explored_state(env, insn_idx);
10022 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
10023 /* connect new state to parentage chain. Current frame needs all
10024 * registers connected. Only r6 - r9 of the callers are alive (pushed
10025 * to the stack implicitly by JITs) so in callers' frames connect just
10026 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10027 * the state of the call instruction (with WRITTEN set), and r0 comes
10028 * from callee with its full parentage chain, anyway.
10029 */
8e9cd9ce
EC
10030 /* clear write marks in current state: the writes we did are not writes
10031 * our child did, so they don't screen off its reads from us.
10032 * (There are no read marks in current state, because reads always mark
10033 * their parent and current state never has children yet. Only
10034 * explored_states can get read marks.)
10035 */
eea1c227
AS
10036 for (j = 0; j <= cur->curframe; j++) {
10037 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10038 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10039 for (i = 0; i < BPF_REG_FP; i++)
10040 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10041 }
f4d7e40a
AS
10042
10043 /* all stack frames are accessible from callee, clear them all */
10044 for (j = 0; j <= cur->curframe; j++) {
10045 struct bpf_func_state *frame = cur->frame[j];
679c782d 10046 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 10047
679c782d 10048 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 10049 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
10050 frame->stack[i].spilled_ptr.parent =
10051 &newframe->stack[i].spilled_ptr;
10052 }
f4d7e40a 10053 }
f1bca824
AS
10054 return 0;
10055}
10056
c64b7983
JS
10057/* Return true if it's OK to have the same insn return a different type. */
10058static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10059{
10060 switch (type) {
10061 case PTR_TO_CTX:
10062 case PTR_TO_SOCKET:
10063 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10064 case PTR_TO_SOCK_COMMON:
10065 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10066 case PTR_TO_TCP_SOCK:
10067 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10068 case PTR_TO_XDP_SOCK:
2a02759e 10069 case PTR_TO_BTF_ID:
b121b341 10070 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
10071 return false;
10072 default:
10073 return true;
10074 }
10075}
10076
10077/* If an instruction was previously used with particular pointer types, then we
10078 * need to be careful to avoid cases such as the below, where it may be ok
10079 * for one branch accessing the pointer, but not ok for the other branch:
10080 *
10081 * R1 = sock_ptr
10082 * goto X;
10083 * ...
10084 * R1 = some_other_valid_ptr;
10085 * goto X;
10086 * ...
10087 * R2 = *(u32 *)(R1 + 0);
10088 */
10089static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10090{
10091 return src != prev && (!reg_type_mismatch_ok(src) ||
10092 !reg_type_mismatch_ok(prev));
10093}
10094
58e2af8b 10095static int do_check(struct bpf_verifier_env *env)
17a52670 10096{
6f8a57cc 10097 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 10098 struct bpf_verifier_state *state = env->cur_state;
17a52670 10099 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 10100 struct bpf_reg_state *regs;
06ee7115 10101 int insn_cnt = env->prog->len;
17a52670 10102 bool do_print_state = false;
b5dc0163 10103 int prev_insn_idx = -1;
17a52670 10104
17a52670
AS
10105 for (;;) {
10106 struct bpf_insn *insn;
10107 u8 class;
10108 int err;
10109
b5dc0163 10110 env->prev_insn_idx = prev_insn_idx;
c08435ec 10111 if (env->insn_idx >= insn_cnt) {
61bd5218 10112 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 10113 env->insn_idx, insn_cnt);
17a52670
AS
10114 return -EFAULT;
10115 }
10116
c08435ec 10117 insn = &insns[env->insn_idx];
17a52670
AS
10118 class = BPF_CLASS(insn->code);
10119
06ee7115 10120 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
10121 verbose(env,
10122 "BPF program is too large. Processed %d insn\n",
06ee7115 10123 env->insn_processed);
17a52670
AS
10124 return -E2BIG;
10125 }
10126
c08435ec 10127 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
10128 if (err < 0)
10129 return err;
10130 if (err == 1) {
10131 /* found equivalent state, can prune the search */
06ee7115 10132 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 10133 if (do_print_state)
979d63d5
DB
10134 verbose(env, "\nfrom %d to %d%s: safe\n",
10135 env->prev_insn_idx, env->insn_idx,
10136 env->cur_state->speculative ?
10137 " (speculative execution)" : "");
f1bca824 10138 else
c08435ec 10139 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
10140 }
10141 goto process_bpf_exit;
10142 }
10143
c3494801
AS
10144 if (signal_pending(current))
10145 return -EAGAIN;
10146
3c2ce60b
DB
10147 if (need_resched())
10148 cond_resched();
10149
06ee7115
AS
10150 if (env->log.level & BPF_LOG_LEVEL2 ||
10151 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10152 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 10153 verbose(env, "%d:", env->insn_idx);
c5fc9692 10154 else
979d63d5
DB
10155 verbose(env, "\nfrom %d to %d%s:",
10156 env->prev_insn_idx, env->insn_idx,
10157 env->cur_state->speculative ?
10158 " (speculative execution)" : "");
f4d7e40a 10159 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
10160 do_print_state = false;
10161 }
10162
06ee7115 10163 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
10164 const struct bpf_insn_cbs cbs = {
10165 .cb_print = verbose,
abe08840 10166 .private_data = env,
7105e828
DB
10167 };
10168
c08435ec
DB
10169 verbose_linfo(env, env->insn_idx, "; ");
10170 verbose(env, "%d: ", env->insn_idx);
abe08840 10171 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
10172 }
10173
cae1927c 10174 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
10175 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10176 env->prev_insn_idx);
cae1927c
JK
10177 if (err)
10178 return err;
10179 }
13a27dfc 10180
638f5b90 10181 regs = cur_regs(env);
51c39bb1 10182 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 10183 prev_insn_idx = env->insn_idx;
fd978bf7 10184
17a52670 10185 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 10186 err = check_alu_op(env, insn);
17a52670
AS
10187 if (err)
10188 return err;
10189
10190 } else if (class == BPF_LDX) {
3df126f3 10191 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
10192
10193 /* check for reserved fields is already done */
10194
17a52670 10195 /* check src operand */
dc503a8a 10196 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10197 if (err)
10198 return err;
10199
dc503a8a 10200 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10201 if (err)
10202 return err;
10203
725f9dcd
AS
10204 src_reg_type = regs[insn->src_reg].type;
10205
17a52670
AS
10206 /* check that memory (src_reg + off) is readable,
10207 * the state of dst_reg will be updated by this func
10208 */
c08435ec
DB
10209 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10210 insn->off, BPF_SIZE(insn->code),
10211 BPF_READ, insn->dst_reg, false);
17a52670
AS
10212 if (err)
10213 return err;
10214
c08435ec 10215 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10216
10217 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
10218 /* saw a valid insn
10219 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 10220 * save type to validate intersecting paths
9bac3d6d 10221 */
3df126f3 10222 *prev_src_type = src_reg_type;
9bac3d6d 10223
c64b7983 10224 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
10225 /* ABuser program is trying to use the same insn
10226 * dst_reg = *(u32*) (src_reg + off)
10227 * with different pointer types:
10228 * src_reg == ctx in one branch and
10229 * src_reg == stack|map in some other branch.
10230 * Reject it.
10231 */
61bd5218 10232 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
10233 return -EINVAL;
10234 }
10235
17a52670 10236 } else if (class == BPF_STX) {
3df126f3 10237 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 10238
91c960b0
BJ
10239 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10240 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
10241 if (err)
10242 return err;
c08435ec 10243 env->insn_idx++;
17a52670
AS
10244 continue;
10245 }
10246
5ca419f2
BJ
10247 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10248 verbose(env, "BPF_STX uses reserved fields\n");
10249 return -EINVAL;
10250 }
10251
17a52670 10252 /* check src1 operand */
dc503a8a 10253 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10254 if (err)
10255 return err;
10256 /* check src2 operand */
dc503a8a 10257 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10258 if (err)
10259 return err;
10260
d691f9e8
AS
10261 dst_reg_type = regs[insn->dst_reg].type;
10262
17a52670 10263 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10264 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10265 insn->off, BPF_SIZE(insn->code),
10266 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10267 if (err)
10268 return err;
10269
c08435ec 10270 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10271
10272 if (*prev_dst_type == NOT_INIT) {
10273 *prev_dst_type = dst_reg_type;
c64b7983 10274 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10275 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10276 return -EINVAL;
10277 }
10278
17a52670
AS
10279 } else if (class == BPF_ST) {
10280 if (BPF_MODE(insn->code) != BPF_MEM ||
10281 insn->src_reg != BPF_REG_0) {
61bd5218 10282 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10283 return -EINVAL;
10284 }
10285 /* check src operand */
dc503a8a 10286 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10287 if (err)
10288 return err;
10289
f37a8cb8 10290 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10291 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10292 insn->dst_reg,
10293 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10294 return -EACCES;
10295 }
10296
17a52670 10297 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10298 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10299 insn->off, BPF_SIZE(insn->code),
10300 BPF_WRITE, -1, false);
17a52670
AS
10301 if (err)
10302 return err;
10303
092ed096 10304 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10305 u8 opcode = BPF_OP(insn->code);
10306
2589726d 10307 env->jmps_processed++;
17a52670
AS
10308 if (opcode == BPF_CALL) {
10309 if (BPF_SRC(insn->code) != BPF_K ||
10310 insn->off != 0 ||
f4d7e40a
AS
10311 (insn->src_reg != BPF_REG_0 &&
10312 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
10313 insn->dst_reg != BPF_REG_0 ||
10314 class == BPF_JMP32) {
61bd5218 10315 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10316 return -EINVAL;
10317 }
10318
d83525ca
AS
10319 if (env->cur_state->active_spin_lock &&
10320 (insn->src_reg == BPF_PSEUDO_CALL ||
10321 insn->imm != BPF_FUNC_spin_unlock)) {
10322 verbose(env, "function calls are not allowed while holding a lock\n");
10323 return -EINVAL;
10324 }
f4d7e40a 10325 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10326 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 10327 else
69c087ba 10328 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
10329 if (err)
10330 return err;
17a52670
AS
10331 } else if (opcode == BPF_JA) {
10332 if (BPF_SRC(insn->code) != BPF_K ||
10333 insn->imm != 0 ||
10334 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10335 insn->dst_reg != BPF_REG_0 ||
10336 class == BPF_JMP32) {
61bd5218 10337 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10338 return -EINVAL;
10339 }
10340
c08435ec 10341 env->insn_idx += insn->off + 1;
17a52670
AS
10342 continue;
10343
10344 } else if (opcode == BPF_EXIT) {
10345 if (BPF_SRC(insn->code) != BPF_K ||
10346 insn->imm != 0 ||
10347 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10348 insn->dst_reg != BPF_REG_0 ||
10349 class == BPF_JMP32) {
61bd5218 10350 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10351 return -EINVAL;
10352 }
10353
d83525ca
AS
10354 if (env->cur_state->active_spin_lock) {
10355 verbose(env, "bpf_spin_unlock is missing\n");
10356 return -EINVAL;
10357 }
10358
f4d7e40a
AS
10359 if (state->curframe) {
10360 /* exit from nested function */
c08435ec 10361 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10362 if (err)
10363 return err;
10364 do_print_state = true;
10365 continue;
10366 }
10367
fd978bf7
JS
10368 err = check_reference_leak(env);
10369 if (err)
10370 return err;
10371
390ee7e2
AS
10372 err = check_return_code(env);
10373 if (err)
10374 return err;
f1bca824 10375process_bpf_exit:
2589726d 10376 update_branch_counts(env, env->cur_state);
b5dc0163 10377 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10378 &env->insn_idx, pop_log);
638f5b90
AS
10379 if (err < 0) {
10380 if (err != -ENOENT)
10381 return err;
17a52670
AS
10382 break;
10383 } else {
10384 do_print_state = true;
10385 continue;
10386 }
10387 } else {
c08435ec 10388 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10389 if (err)
10390 return err;
10391 }
10392 } else if (class == BPF_LD) {
10393 u8 mode = BPF_MODE(insn->code);
10394
10395 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10396 err = check_ld_abs(env, insn);
10397 if (err)
10398 return err;
10399
17a52670
AS
10400 } else if (mode == BPF_IMM) {
10401 err = check_ld_imm(env, insn);
10402 if (err)
10403 return err;
10404
c08435ec 10405 env->insn_idx++;
51c39bb1 10406 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 10407 } else {
61bd5218 10408 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10409 return -EINVAL;
10410 }
10411 } else {
61bd5218 10412 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10413 return -EINVAL;
10414 }
10415
c08435ec 10416 env->insn_idx++;
17a52670
AS
10417 }
10418
10419 return 0;
10420}
10421
541c3bad
AN
10422static int find_btf_percpu_datasec(struct btf *btf)
10423{
10424 const struct btf_type *t;
10425 const char *tname;
10426 int i, n;
10427
10428 /*
10429 * Both vmlinux and module each have their own ".data..percpu"
10430 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10431 * types to look at only module's own BTF types.
10432 */
10433 n = btf_nr_types(btf);
10434 if (btf_is_module(btf))
10435 i = btf_nr_types(btf_vmlinux);
10436 else
10437 i = 1;
10438
10439 for(; i < n; i++) {
10440 t = btf_type_by_id(btf, i);
10441 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10442 continue;
10443
10444 tname = btf_name_by_offset(btf, t->name_off);
10445 if (!strcmp(tname, ".data..percpu"))
10446 return i;
10447 }
10448
10449 return -ENOENT;
10450}
10451
4976b718
HL
10452/* replace pseudo btf_id with kernel symbol address */
10453static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10454 struct bpf_insn *insn,
10455 struct bpf_insn_aux_data *aux)
10456{
eaa6bcb7
HL
10457 const struct btf_var_secinfo *vsi;
10458 const struct btf_type *datasec;
541c3bad 10459 struct btf_mod_pair *btf_mod;
4976b718
HL
10460 const struct btf_type *t;
10461 const char *sym_name;
eaa6bcb7 10462 bool percpu = false;
f16e6313 10463 u32 type, id = insn->imm;
541c3bad 10464 struct btf *btf;
f16e6313 10465 s32 datasec_id;
4976b718 10466 u64 addr;
541c3bad 10467 int i, btf_fd, err;
4976b718 10468
541c3bad
AN
10469 btf_fd = insn[1].imm;
10470 if (btf_fd) {
10471 btf = btf_get_by_fd(btf_fd);
10472 if (IS_ERR(btf)) {
10473 verbose(env, "invalid module BTF object FD specified.\n");
10474 return -EINVAL;
10475 }
10476 } else {
10477 if (!btf_vmlinux) {
10478 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10479 return -EINVAL;
10480 }
10481 btf = btf_vmlinux;
10482 btf_get(btf);
4976b718
HL
10483 }
10484
541c3bad 10485 t = btf_type_by_id(btf, id);
4976b718
HL
10486 if (!t) {
10487 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
10488 err = -ENOENT;
10489 goto err_put;
4976b718
HL
10490 }
10491
10492 if (!btf_type_is_var(t)) {
541c3bad
AN
10493 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10494 err = -EINVAL;
10495 goto err_put;
4976b718
HL
10496 }
10497
541c3bad 10498 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10499 addr = kallsyms_lookup_name(sym_name);
10500 if (!addr) {
10501 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10502 sym_name);
541c3bad
AN
10503 err = -ENOENT;
10504 goto err_put;
4976b718
HL
10505 }
10506
541c3bad 10507 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 10508 if (datasec_id > 0) {
541c3bad 10509 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
10510 for_each_vsi(i, datasec, vsi) {
10511 if (vsi->type == id) {
10512 percpu = true;
10513 break;
10514 }
10515 }
10516 }
10517
4976b718
HL
10518 insn[0].imm = (u32)addr;
10519 insn[1].imm = addr >> 32;
10520
10521 type = t->type;
541c3bad 10522 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7
HL
10523 if (percpu) {
10524 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
541c3bad 10525 aux->btf_var.btf = btf;
eaa6bcb7
HL
10526 aux->btf_var.btf_id = type;
10527 } else if (!btf_type_is_struct(t)) {
4976b718
HL
10528 const struct btf_type *ret;
10529 const char *tname;
10530 u32 tsize;
10531
10532 /* resolve the type size of ksym. */
541c3bad 10533 ret = btf_resolve_size(btf, t, &tsize);
4976b718 10534 if (IS_ERR(ret)) {
541c3bad 10535 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10536 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10537 tname, PTR_ERR(ret));
541c3bad
AN
10538 err = -EINVAL;
10539 goto err_put;
4976b718
HL
10540 }
10541 aux->btf_var.reg_type = PTR_TO_MEM;
10542 aux->btf_var.mem_size = tsize;
10543 } else {
10544 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 10545 aux->btf_var.btf = btf;
4976b718
HL
10546 aux->btf_var.btf_id = type;
10547 }
541c3bad
AN
10548
10549 /* check whether we recorded this BTF (and maybe module) already */
10550 for (i = 0; i < env->used_btf_cnt; i++) {
10551 if (env->used_btfs[i].btf == btf) {
10552 btf_put(btf);
10553 return 0;
10554 }
10555 }
10556
10557 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10558 err = -E2BIG;
10559 goto err_put;
10560 }
10561
10562 btf_mod = &env->used_btfs[env->used_btf_cnt];
10563 btf_mod->btf = btf;
10564 btf_mod->module = NULL;
10565
10566 /* if we reference variables from kernel module, bump its refcount */
10567 if (btf_is_module(btf)) {
10568 btf_mod->module = btf_try_get_module(btf);
10569 if (!btf_mod->module) {
10570 err = -ENXIO;
10571 goto err_put;
10572 }
10573 }
10574
10575 env->used_btf_cnt++;
10576
4976b718 10577 return 0;
541c3bad
AN
10578err_put:
10579 btf_put(btf);
10580 return err;
4976b718
HL
10581}
10582
56f668df
MKL
10583static int check_map_prealloc(struct bpf_map *map)
10584{
10585 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
10586 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10587 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
10588 !(map->map_flags & BPF_F_NO_PREALLOC);
10589}
10590
d83525ca
AS
10591static bool is_tracing_prog_type(enum bpf_prog_type type)
10592{
10593 switch (type) {
10594 case BPF_PROG_TYPE_KPROBE:
10595 case BPF_PROG_TYPE_TRACEPOINT:
10596 case BPF_PROG_TYPE_PERF_EVENT:
10597 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10598 return true;
10599 default:
10600 return false;
10601 }
10602}
10603
94dacdbd
TG
10604static bool is_preallocated_map(struct bpf_map *map)
10605{
10606 if (!check_map_prealloc(map))
10607 return false;
10608 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10609 return false;
10610 return true;
10611}
10612
61bd5218
JK
10613static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10614 struct bpf_map *map,
fdc15d38
AS
10615 struct bpf_prog *prog)
10616
10617{
7e40781c 10618 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
10619 /*
10620 * Validate that trace type programs use preallocated hash maps.
10621 *
10622 * For programs attached to PERF events this is mandatory as the
10623 * perf NMI can hit any arbitrary code sequence.
10624 *
10625 * All other trace types using preallocated hash maps are unsafe as
10626 * well because tracepoint or kprobes can be inside locked regions
10627 * of the memory allocator or at a place where a recursion into the
10628 * memory allocator would see inconsistent state.
10629 *
2ed905c5
TG
10630 * On RT enabled kernels run-time allocation of all trace type
10631 * programs is strictly prohibited due to lock type constraints. On
10632 * !RT kernels it is allowed for backwards compatibility reasons for
10633 * now, but warnings are emitted so developers are made aware of
10634 * the unsafety and can fix their programs before this is enforced.
56f668df 10635 */
7e40781c
UP
10636 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10637 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 10638 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
10639 return -EINVAL;
10640 }
2ed905c5
TG
10641 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10642 verbose(env, "trace type programs can only use preallocated hash map\n");
10643 return -EINVAL;
10644 }
94dacdbd
TG
10645 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10646 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 10647 }
a3884572 10648
9e7a4d98
KS
10649 if (map_value_has_spin_lock(map)) {
10650 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10651 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10652 return -EINVAL;
10653 }
10654
10655 if (is_tracing_prog_type(prog_type)) {
10656 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10657 return -EINVAL;
10658 }
10659
10660 if (prog->aux->sleepable) {
10661 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10662 return -EINVAL;
10663 }
d83525ca
AS
10664 }
10665
a3884572 10666 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 10667 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
10668 verbose(env, "offload device mismatch between prog and map\n");
10669 return -EINVAL;
10670 }
10671
85d33df3
MKL
10672 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10673 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10674 return -EINVAL;
10675 }
10676
1e6c62a8
AS
10677 if (prog->aux->sleepable)
10678 switch (map->map_type) {
10679 case BPF_MAP_TYPE_HASH:
10680 case BPF_MAP_TYPE_LRU_HASH:
10681 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
10682 case BPF_MAP_TYPE_PERCPU_HASH:
10683 case BPF_MAP_TYPE_PERCPU_ARRAY:
10684 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10685 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10686 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
10687 if (!is_preallocated_map(map)) {
10688 verbose(env,
638e4b82 10689 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
10690 return -EINVAL;
10691 }
10692 break;
ba90c2cc
KS
10693 case BPF_MAP_TYPE_RINGBUF:
10694 break;
1e6c62a8
AS
10695 default:
10696 verbose(env,
ba90c2cc 10697 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
10698 return -EINVAL;
10699 }
10700
fdc15d38
AS
10701 return 0;
10702}
10703
b741f163
RG
10704static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10705{
10706 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10707 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10708}
10709
4976b718
HL
10710/* find and rewrite pseudo imm in ld_imm64 instructions:
10711 *
10712 * 1. if it accesses map FD, replace it with actual map pointer.
10713 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10714 *
10715 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 10716 */
4976b718 10717static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
10718{
10719 struct bpf_insn *insn = env->prog->insnsi;
10720 int insn_cnt = env->prog->len;
fdc15d38 10721 int i, j, err;
0246e64d 10722
f1f7714e 10723 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
10724 if (err)
10725 return err;
10726
0246e64d 10727 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 10728 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 10729 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 10730 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
10731 return -EINVAL;
10732 }
10733
0246e64d 10734 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 10735 struct bpf_insn_aux_data *aux;
0246e64d
AS
10736 struct bpf_map *map;
10737 struct fd f;
d8eca5bb 10738 u64 addr;
0246e64d
AS
10739
10740 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10741 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10742 insn[1].off != 0) {
61bd5218 10743 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
10744 return -EINVAL;
10745 }
10746
d8eca5bb 10747 if (insn[0].src_reg == 0)
0246e64d
AS
10748 /* valid generic load 64-bit imm */
10749 goto next_insn;
10750
4976b718
HL
10751 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10752 aux = &env->insn_aux_data[i];
10753 err = check_pseudo_btf_id(env, insn, aux);
10754 if (err)
10755 return err;
10756 goto next_insn;
10757 }
10758
69c087ba
YS
10759 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
10760 aux = &env->insn_aux_data[i];
10761 aux->ptr_type = PTR_TO_FUNC;
10762 goto next_insn;
10763 }
10764
d8eca5bb
DB
10765 /* In final convert_pseudo_ld_imm64() step, this is
10766 * converted into regular 64-bit imm load insn.
10767 */
10768 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10769 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10770 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10771 insn[1].imm != 0)) {
10772 verbose(env,
10773 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
10774 return -EINVAL;
10775 }
10776
20182390 10777 f = fdget(insn[0].imm);
c2101297 10778 map = __bpf_map_get(f);
0246e64d 10779 if (IS_ERR(map)) {
61bd5218 10780 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 10781 insn[0].imm);
0246e64d
AS
10782 return PTR_ERR(map);
10783 }
10784
61bd5218 10785 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
10786 if (err) {
10787 fdput(f);
10788 return err;
10789 }
10790
d8eca5bb
DB
10791 aux = &env->insn_aux_data[i];
10792 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10793 addr = (unsigned long)map;
10794 } else {
10795 u32 off = insn[1].imm;
10796
10797 if (off >= BPF_MAX_VAR_OFF) {
10798 verbose(env, "direct value offset of %u is not allowed\n", off);
10799 fdput(f);
10800 return -EINVAL;
10801 }
10802
10803 if (!map->ops->map_direct_value_addr) {
10804 verbose(env, "no direct value access support for this map type\n");
10805 fdput(f);
10806 return -EINVAL;
10807 }
10808
10809 err = map->ops->map_direct_value_addr(map, &addr, off);
10810 if (err) {
10811 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10812 map->value_size, off);
10813 fdput(f);
10814 return err;
10815 }
10816
10817 aux->map_off = off;
10818 addr += off;
10819 }
10820
10821 insn[0].imm = (u32)addr;
10822 insn[1].imm = addr >> 32;
0246e64d
AS
10823
10824 /* check whether we recorded this map already */
d8eca5bb 10825 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 10826 if (env->used_maps[j] == map) {
d8eca5bb 10827 aux->map_index = j;
0246e64d
AS
10828 fdput(f);
10829 goto next_insn;
10830 }
d8eca5bb 10831 }
0246e64d
AS
10832
10833 if (env->used_map_cnt >= MAX_USED_MAPS) {
10834 fdput(f);
10835 return -E2BIG;
10836 }
10837
0246e64d
AS
10838 /* hold the map. If the program is rejected by verifier,
10839 * the map will be released by release_maps() or it
10840 * will be used by the valid program until it's unloaded
ab7f5bf0 10841 * and all maps are released in free_used_maps()
0246e64d 10842 */
1e0bd5a0 10843 bpf_map_inc(map);
d8eca5bb
DB
10844
10845 aux->map_index = env->used_map_cnt;
92117d84
AS
10846 env->used_maps[env->used_map_cnt++] = map;
10847
b741f163 10848 if (bpf_map_is_cgroup_storage(map) &&
e4730423 10849 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 10850 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
10851 fdput(f);
10852 return -EBUSY;
10853 }
10854
0246e64d
AS
10855 fdput(f);
10856next_insn:
10857 insn++;
10858 i++;
5e581dad
DB
10859 continue;
10860 }
10861
10862 /* Basic sanity check before we invest more work here. */
10863 if (!bpf_opcode_in_insntable(insn->code)) {
10864 verbose(env, "unknown opcode %02x\n", insn->code);
10865 return -EINVAL;
0246e64d
AS
10866 }
10867 }
10868
10869 /* now all pseudo BPF_LD_IMM64 instructions load valid
10870 * 'struct bpf_map *' into a register instead of user map_fd.
10871 * These pointers will be used later by verifier to validate map access.
10872 */
10873 return 0;
10874}
10875
10876/* drop refcnt of maps used by the rejected program */
58e2af8b 10877static void release_maps(struct bpf_verifier_env *env)
0246e64d 10878{
a2ea0746
DB
10879 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10880 env->used_map_cnt);
0246e64d
AS
10881}
10882
541c3bad
AN
10883/* drop refcnt of maps used by the rejected program */
10884static void release_btfs(struct bpf_verifier_env *env)
10885{
10886 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10887 env->used_btf_cnt);
10888}
10889
0246e64d 10890/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 10891static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
10892{
10893 struct bpf_insn *insn = env->prog->insnsi;
10894 int insn_cnt = env->prog->len;
10895 int i;
10896
69c087ba
YS
10897 for (i = 0; i < insn_cnt; i++, insn++) {
10898 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
10899 continue;
10900 if (insn->src_reg == BPF_PSEUDO_FUNC)
10901 continue;
10902 insn->src_reg = 0;
10903 }
0246e64d
AS
10904}
10905
8041902d
AS
10906/* single env->prog->insni[off] instruction was replaced with the range
10907 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10908 * [0, off) and [off, end) to new locations, so the patched range stays zero
10909 */
b325fbca
JW
10910static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10911 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
10912{
10913 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
10914 struct bpf_insn *insn = new_prog->insnsi;
10915 u32 prog_len;
c131187d 10916 int i;
8041902d 10917
b325fbca
JW
10918 /* aux info at OFF always needs adjustment, no matter fast path
10919 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10920 * original insn at old prog.
10921 */
10922 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10923
8041902d
AS
10924 if (cnt == 1)
10925 return 0;
b325fbca 10926 prog_len = new_prog->len;
fad953ce
KC
10927 new_data = vzalloc(array_size(prog_len,
10928 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
10929 if (!new_data)
10930 return -ENOMEM;
10931 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10932 memcpy(new_data + off + cnt - 1, old_data + off,
10933 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 10934 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 10935 new_data[i].seen = env->pass_cnt;
b325fbca
JW
10936 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10937 }
8041902d
AS
10938 env->insn_aux_data = new_data;
10939 vfree(old_data);
10940 return 0;
10941}
10942
cc8b0b92
AS
10943static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10944{
10945 int i;
10946
10947 if (len == 1)
10948 return;
4cb3d99c
JW
10949 /* NOTE: fake 'exit' subprog should be updated as well. */
10950 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 10951 if (env->subprog_info[i].start <= off)
cc8b0b92 10952 continue;
9c8105bd 10953 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
10954 }
10955}
10956
a748c697
MF
10957static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10958{
10959 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10960 int i, sz = prog->aux->size_poke_tab;
10961 struct bpf_jit_poke_descriptor *desc;
10962
10963 for (i = 0; i < sz; i++) {
10964 desc = &tab[i];
10965 desc->insn_idx += len - 1;
10966 }
10967}
10968
8041902d
AS
10969static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10970 const struct bpf_insn *patch, u32 len)
10971{
10972 struct bpf_prog *new_prog;
10973
10974 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
10975 if (IS_ERR(new_prog)) {
10976 if (PTR_ERR(new_prog) == -ERANGE)
10977 verbose(env,
10978 "insn %d cannot be patched due to 16-bit range\n",
10979 env->insn_aux_data[off].orig_idx);
8041902d 10980 return NULL;
4f73379e 10981 }
b325fbca 10982 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 10983 return NULL;
cc8b0b92 10984 adjust_subprog_starts(env, off, len);
a748c697 10985 adjust_poke_descs(new_prog, len);
8041902d
AS
10986 return new_prog;
10987}
10988
52875a04
JK
10989static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10990 u32 off, u32 cnt)
10991{
10992 int i, j;
10993
10994 /* find first prog starting at or after off (first to remove) */
10995 for (i = 0; i < env->subprog_cnt; i++)
10996 if (env->subprog_info[i].start >= off)
10997 break;
10998 /* find first prog starting at or after off + cnt (first to stay) */
10999 for (j = i; j < env->subprog_cnt; j++)
11000 if (env->subprog_info[j].start >= off + cnt)
11001 break;
11002 /* if j doesn't start exactly at off + cnt, we are just removing
11003 * the front of previous prog
11004 */
11005 if (env->subprog_info[j].start != off + cnt)
11006 j--;
11007
11008 if (j > i) {
11009 struct bpf_prog_aux *aux = env->prog->aux;
11010 int move;
11011
11012 /* move fake 'exit' subprog as well */
11013 move = env->subprog_cnt + 1 - j;
11014
11015 memmove(env->subprog_info + i,
11016 env->subprog_info + j,
11017 sizeof(*env->subprog_info) * move);
11018 env->subprog_cnt -= j - i;
11019
11020 /* remove func_info */
11021 if (aux->func_info) {
11022 move = aux->func_info_cnt - j;
11023
11024 memmove(aux->func_info + i,
11025 aux->func_info + j,
11026 sizeof(*aux->func_info) * move);
11027 aux->func_info_cnt -= j - i;
11028 /* func_info->insn_off is set after all code rewrites,
11029 * in adjust_btf_func() - no need to adjust
11030 */
11031 }
11032 } else {
11033 /* convert i from "first prog to remove" to "first to adjust" */
11034 if (env->subprog_info[i].start == off)
11035 i++;
11036 }
11037
11038 /* update fake 'exit' subprog as well */
11039 for (; i <= env->subprog_cnt; i++)
11040 env->subprog_info[i].start -= cnt;
11041
11042 return 0;
11043}
11044
11045static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11046 u32 cnt)
11047{
11048 struct bpf_prog *prog = env->prog;
11049 u32 i, l_off, l_cnt, nr_linfo;
11050 struct bpf_line_info *linfo;
11051
11052 nr_linfo = prog->aux->nr_linfo;
11053 if (!nr_linfo)
11054 return 0;
11055
11056 linfo = prog->aux->linfo;
11057
11058 /* find first line info to remove, count lines to be removed */
11059 for (i = 0; i < nr_linfo; i++)
11060 if (linfo[i].insn_off >= off)
11061 break;
11062
11063 l_off = i;
11064 l_cnt = 0;
11065 for (; i < nr_linfo; i++)
11066 if (linfo[i].insn_off < off + cnt)
11067 l_cnt++;
11068 else
11069 break;
11070
11071 /* First live insn doesn't match first live linfo, it needs to "inherit"
11072 * last removed linfo. prog is already modified, so prog->len == off
11073 * means no live instructions after (tail of the program was removed).
11074 */
11075 if (prog->len != off && l_cnt &&
11076 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11077 l_cnt--;
11078 linfo[--i].insn_off = off + cnt;
11079 }
11080
11081 /* remove the line info which refer to the removed instructions */
11082 if (l_cnt) {
11083 memmove(linfo + l_off, linfo + i,
11084 sizeof(*linfo) * (nr_linfo - i));
11085
11086 prog->aux->nr_linfo -= l_cnt;
11087 nr_linfo = prog->aux->nr_linfo;
11088 }
11089
11090 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11091 for (i = l_off; i < nr_linfo; i++)
11092 linfo[i].insn_off -= cnt;
11093
11094 /* fix up all subprogs (incl. 'exit') which start >= off */
11095 for (i = 0; i <= env->subprog_cnt; i++)
11096 if (env->subprog_info[i].linfo_idx > l_off) {
11097 /* program may have started in the removed region but
11098 * may not be fully removed
11099 */
11100 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11101 env->subprog_info[i].linfo_idx -= l_cnt;
11102 else
11103 env->subprog_info[i].linfo_idx = l_off;
11104 }
11105
11106 return 0;
11107}
11108
11109static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11110{
11111 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11112 unsigned int orig_prog_len = env->prog->len;
11113 int err;
11114
08ca90af
JK
11115 if (bpf_prog_is_dev_bound(env->prog->aux))
11116 bpf_prog_offload_remove_insns(env, off, cnt);
11117
52875a04
JK
11118 err = bpf_remove_insns(env->prog, off, cnt);
11119 if (err)
11120 return err;
11121
11122 err = adjust_subprog_starts_after_remove(env, off, cnt);
11123 if (err)
11124 return err;
11125
11126 err = bpf_adj_linfo_after_remove(env, off, cnt);
11127 if (err)
11128 return err;
11129
11130 memmove(aux_data + off, aux_data + off + cnt,
11131 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11132
11133 return 0;
11134}
11135
2a5418a1
DB
11136/* The verifier does more data flow analysis than llvm and will not
11137 * explore branches that are dead at run time. Malicious programs can
11138 * have dead code too. Therefore replace all dead at-run-time code
11139 * with 'ja -1'.
11140 *
11141 * Just nops are not optimal, e.g. if they would sit at the end of the
11142 * program and through another bug we would manage to jump there, then
11143 * we'd execute beyond program memory otherwise. Returning exception
11144 * code also wouldn't work since we can have subprogs where the dead
11145 * code could be located.
c131187d
AS
11146 */
11147static void sanitize_dead_code(struct bpf_verifier_env *env)
11148{
11149 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 11150 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
11151 struct bpf_insn *insn = env->prog->insnsi;
11152 const int insn_cnt = env->prog->len;
11153 int i;
11154
11155 for (i = 0; i < insn_cnt; i++) {
11156 if (aux_data[i].seen)
11157 continue;
2a5418a1 11158 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
11159 }
11160}
11161
e2ae4ca2
JK
11162static bool insn_is_cond_jump(u8 code)
11163{
11164 u8 op;
11165
092ed096
JW
11166 if (BPF_CLASS(code) == BPF_JMP32)
11167 return true;
11168
e2ae4ca2
JK
11169 if (BPF_CLASS(code) != BPF_JMP)
11170 return false;
11171
11172 op = BPF_OP(code);
11173 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11174}
11175
11176static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11177{
11178 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11179 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11180 struct bpf_insn *insn = env->prog->insnsi;
11181 const int insn_cnt = env->prog->len;
11182 int i;
11183
11184 for (i = 0; i < insn_cnt; i++, insn++) {
11185 if (!insn_is_cond_jump(insn->code))
11186 continue;
11187
11188 if (!aux_data[i + 1].seen)
11189 ja.off = insn->off;
11190 else if (!aux_data[i + 1 + insn->off].seen)
11191 ja.off = 0;
11192 else
11193 continue;
11194
08ca90af
JK
11195 if (bpf_prog_is_dev_bound(env->prog->aux))
11196 bpf_prog_offload_replace_insn(env, i, &ja);
11197
e2ae4ca2
JK
11198 memcpy(insn, &ja, sizeof(ja));
11199 }
11200}
11201
52875a04
JK
11202static int opt_remove_dead_code(struct bpf_verifier_env *env)
11203{
11204 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11205 int insn_cnt = env->prog->len;
11206 int i, err;
11207
11208 for (i = 0; i < insn_cnt; i++) {
11209 int j;
11210
11211 j = 0;
11212 while (i + j < insn_cnt && !aux_data[i + j].seen)
11213 j++;
11214 if (!j)
11215 continue;
11216
11217 err = verifier_remove_insns(env, i, j);
11218 if (err)
11219 return err;
11220 insn_cnt = env->prog->len;
11221 }
11222
11223 return 0;
11224}
11225
a1b14abc
JK
11226static int opt_remove_nops(struct bpf_verifier_env *env)
11227{
11228 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11229 struct bpf_insn *insn = env->prog->insnsi;
11230 int insn_cnt = env->prog->len;
11231 int i, err;
11232
11233 for (i = 0; i < insn_cnt; i++) {
11234 if (memcmp(&insn[i], &ja, sizeof(ja)))
11235 continue;
11236
11237 err = verifier_remove_insns(env, i, 1);
11238 if (err)
11239 return err;
11240 insn_cnt--;
11241 i--;
11242 }
11243
11244 return 0;
11245}
11246
d6c2308c
JW
11247static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11248 const union bpf_attr *attr)
a4b1d3c1 11249{
d6c2308c 11250 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 11251 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 11252 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 11253 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 11254 struct bpf_prog *new_prog;
d6c2308c 11255 bool rnd_hi32;
a4b1d3c1 11256
d6c2308c 11257 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 11258 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
11259 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11260 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11261 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
11262 for (i = 0; i < len; i++) {
11263 int adj_idx = i + delta;
11264 struct bpf_insn insn;
83a28819 11265 int load_reg;
a4b1d3c1 11266
d6c2308c 11267 insn = insns[adj_idx];
83a28819 11268 load_reg = insn_def_regno(&insn);
d6c2308c
JW
11269 if (!aux[adj_idx].zext_dst) {
11270 u8 code, class;
11271 u32 imm_rnd;
11272
11273 if (!rnd_hi32)
11274 continue;
11275
11276 code = insn.code;
11277 class = BPF_CLASS(code);
83a28819 11278 if (load_reg == -1)
d6c2308c
JW
11279 continue;
11280
11281 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
11282 * BPF_STX + SRC_OP, so it is safe to pass NULL
11283 * here.
d6c2308c 11284 */
83a28819 11285 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
11286 if (class == BPF_LD &&
11287 BPF_MODE(code) == BPF_IMM)
11288 i++;
11289 continue;
11290 }
11291
11292 /* ctx load could be transformed into wider load. */
11293 if (class == BPF_LDX &&
11294 aux[adj_idx].ptr_type == PTR_TO_CTX)
11295 continue;
11296
11297 imm_rnd = get_random_int();
11298 rnd_hi32_patch[0] = insn;
11299 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 11300 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
11301 patch = rnd_hi32_patch;
11302 patch_len = 4;
11303 goto apply_patch_buffer;
11304 }
11305
39491867
BJ
11306 /* Add in an zero-extend instruction if a) the JIT has requested
11307 * it or b) it's a CMPXCHG.
11308 *
11309 * The latter is because: BPF_CMPXCHG always loads a value into
11310 * R0, therefore always zero-extends. However some archs'
11311 * equivalent instruction only does this load when the
11312 * comparison is successful. This detail of CMPXCHG is
11313 * orthogonal to the general zero-extension behaviour of the
11314 * CPU, so it's treated independently of bpf_jit_needs_zext.
11315 */
11316 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
11317 continue;
11318
83a28819
IL
11319 if (WARN_ON(load_reg == -1)) {
11320 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11321 return -EFAULT;
b2e37a71
IL
11322 }
11323
a4b1d3c1 11324 zext_patch[0] = insn;
b2e37a71
IL
11325 zext_patch[1].dst_reg = load_reg;
11326 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
11327 patch = zext_patch;
11328 patch_len = 2;
11329apply_patch_buffer:
11330 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
11331 if (!new_prog)
11332 return -ENOMEM;
11333 env->prog = new_prog;
11334 insns = new_prog->insnsi;
11335 aux = env->insn_aux_data;
d6c2308c 11336 delta += patch_len - 1;
a4b1d3c1
JW
11337 }
11338
11339 return 0;
11340}
11341
c64b7983
JS
11342/* convert load instructions that access fields of a context type into a
11343 * sequence of instructions that access fields of the underlying structure:
11344 * struct __sk_buff -> struct sk_buff
11345 * struct bpf_sock_ops -> struct sock
9bac3d6d 11346 */
58e2af8b 11347static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 11348{
00176a34 11349 const struct bpf_verifier_ops *ops = env->ops;
f96da094 11350 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 11351 const int insn_cnt = env->prog->len;
36bbef52 11352 struct bpf_insn insn_buf[16], *insn;
46f53a65 11353 u32 target_size, size_default, off;
9bac3d6d 11354 struct bpf_prog *new_prog;
d691f9e8 11355 enum bpf_access_type type;
f96da094 11356 bool is_narrower_load;
9bac3d6d 11357
b09928b9
DB
11358 if (ops->gen_prologue || env->seen_direct_write) {
11359 if (!ops->gen_prologue) {
11360 verbose(env, "bpf verifier is misconfigured\n");
11361 return -EINVAL;
11362 }
36bbef52
DB
11363 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11364 env->prog);
11365 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11366 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11367 return -EINVAL;
11368 } else if (cnt) {
8041902d 11369 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11370 if (!new_prog)
11371 return -ENOMEM;
8041902d 11372
36bbef52 11373 env->prog = new_prog;
3df126f3 11374 delta += cnt - 1;
36bbef52
DB
11375 }
11376 }
11377
c64b7983 11378 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11379 return 0;
11380
3df126f3 11381 insn = env->prog->insnsi + delta;
36bbef52 11382
9bac3d6d 11383 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11384 bpf_convert_ctx_access_t convert_ctx_access;
11385
62c7989b
DB
11386 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11387 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11388 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11389 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11390 type = BPF_READ;
62c7989b
DB
11391 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11392 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11393 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11394 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11395 type = BPF_WRITE;
11396 else
9bac3d6d
AS
11397 continue;
11398
af86ca4e
AS
11399 if (type == BPF_WRITE &&
11400 env->insn_aux_data[i + delta].sanitize_stack_off) {
11401 struct bpf_insn patch[] = {
11402 /* Sanitize suspicious stack slot with zero.
11403 * There are no memory dependencies for this store,
11404 * since it's only using frame pointer and immediate
11405 * constant of zero
11406 */
11407 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11408 env->insn_aux_data[i + delta].sanitize_stack_off,
11409 0),
11410 /* the original STX instruction will immediately
11411 * overwrite the same stack slot with appropriate value
11412 */
11413 *insn,
11414 };
11415
11416 cnt = ARRAY_SIZE(patch);
11417 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11418 if (!new_prog)
11419 return -ENOMEM;
11420
11421 delta += cnt - 1;
11422 env->prog = new_prog;
11423 insn = new_prog->insnsi + i + delta;
11424 continue;
11425 }
11426
c64b7983
JS
11427 switch (env->insn_aux_data[i + delta].ptr_type) {
11428 case PTR_TO_CTX:
11429 if (!ops->convert_ctx_access)
11430 continue;
11431 convert_ctx_access = ops->convert_ctx_access;
11432 break;
11433 case PTR_TO_SOCKET:
46f8bc92 11434 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11435 convert_ctx_access = bpf_sock_convert_ctx_access;
11436 break;
655a51e5
MKL
11437 case PTR_TO_TCP_SOCK:
11438 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11439 break;
fada7fdc
JL
11440 case PTR_TO_XDP_SOCK:
11441 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11442 break;
2a02759e 11443 case PTR_TO_BTF_ID:
27ae7997
MKL
11444 if (type == BPF_READ) {
11445 insn->code = BPF_LDX | BPF_PROBE_MEM |
11446 BPF_SIZE((insn)->code);
11447 env->prog->aux->num_exentries++;
7e40781c 11448 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11449 verbose(env, "Writes through BTF pointers are not allowed\n");
11450 return -EINVAL;
11451 }
2a02759e 11452 continue;
c64b7983 11453 default:
9bac3d6d 11454 continue;
c64b7983 11455 }
9bac3d6d 11456
31fd8581 11457 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11458 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11459
11460 /* If the read access is a narrower load of the field,
11461 * convert to a 4/8-byte load, to minimum program type specific
11462 * convert_ctx_access changes. If conversion is successful,
11463 * we will apply proper mask to the result.
11464 */
f96da094 11465 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11466 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11467 off = insn->off;
31fd8581 11468 if (is_narrower_load) {
f96da094
DB
11469 u8 size_code;
11470
11471 if (type == BPF_WRITE) {
61bd5218 11472 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
11473 return -EINVAL;
11474 }
31fd8581 11475
f96da094 11476 size_code = BPF_H;
31fd8581
YS
11477 if (ctx_field_size == 4)
11478 size_code = BPF_W;
11479 else if (ctx_field_size == 8)
11480 size_code = BPF_DW;
f96da094 11481
bc23105c 11482 insn->off = off & ~(size_default - 1);
31fd8581
YS
11483 insn->code = BPF_LDX | BPF_MEM | size_code;
11484 }
f96da094
DB
11485
11486 target_size = 0;
c64b7983
JS
11487 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11488 &target_size);
f96da094
DB
11489 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11490 (ctx_field_size && !target_size)) {
61bd5218 11491 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
11492 return -EINVAL;
11493 }
f96da094
DB
11494
11495 if (is_narrower_load && size < target_size) {
d895a0f1
IL
11496 u8 shift = bpf_ctx_narrow_access_offset(
11497 off, size, size_default) * 8;
46f53a65
AI
11498 if (ctx_field_size <= 4) {
11499 if (shift)
11500 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11501 insn->dst_reg,
11502 shift);
31fd8581 11503 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 11504 (1 << size * 8) - 1);
46f53a65
AI
11505 } else {
11506 if (shift)
11507 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11508 insn->dst_reg,
11509 shift);
31fd8581 11510 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 11511 (1ULL << size * 8) - 1);
46f53a65 11512 }
31fd8581 11513 }
9bac3d6d 11514
8041902d 11515 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
11516 if (!new_prog)
11517 return -ENOMEM;
11518
3df126f3 11519 delta += cnt - 1;
9bac3d6d
AS
11520
11521 /* keep walking new program and skip insns we just inserted */
11522 env->prog = new_prog;
3df126f3 11523 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
11524 }
11525
11526 return 0;
11527}
11528
1c2a088a
AS
11529static int jit_subprogs(struct bpf_verifier_env *env)
11530{
11531 struct bpf_prog *prog = env->prog, **func, *tmp;
11532 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 11533 struct bpf_map *map_ptr;
7105e828 11534 struct bpf_insn *insn;
1c2a088a 11535 void *old_bpf_func;
c4c0bdc0 11536 int err, num_exentries;
1c2a088a 11537
f910cefa 11538 if (env->subprog_cnt <= 1)
1c2a088a
AS
11539 return 0;
11540
7105e828 11541 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11542 if (bpf_pseudo_func(insn)) {
11543 env->insn_aux_data[i].call_imm = insn->imm;
11544 /* subprog is encoded in insn[1].imm */
11545 continue;
11546 }
11547
23a2d70c 11548 if (!bpf_pseudo_call(insn))
1c2a088a 11549 continue;
c7a89784
DB
11550 /* Upon error here we cannot fall back to interpreter but
11551 * need a hard reject of the program. Thus -EFAULT is
11552 * propagated in any case.
11553 */
1c2a088a
AS
11554 subprog = find_subprog(env, i + insn->imm + 1);
11555 if (subprog < 0) {
11556 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11557 i + insn->imm + 1);
11558 return -EFAULT;
11559 }
11560 /* temporarily remember subprog id inside insn instead of
11561 * aux_data, since next loop will split up all insns into funcs
11562 */
f910cefa 11563 insn->off = subprog;
1c2a088a
AS
11564 /* remember original imm in case JIT fails and fallback
11565 * to interpreter will be needed
11566 */
11567 env->insn_aux_data[i].call_imm = insn->imm;
11568 /* point imm to __bpf_call_base+1 from JITs point of view */
11569 insn->imm = 1;
11570 }
11571
c454a46b
MKL
11572 err = bpf_prog_alloc_jited_linfo(prog);
11573 if (err)
11574 goto out_undo_insn;
11575
11576 err = -ENOMEM;
6396bb22 11577 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 11578 if (!func)
c7a89784 11579 goto out_undo_insn;
1c2a088a 11580
f910cefa 11581 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 11582 subprog_start = subprog_end;
4cb3d99c 11583 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
11584
11585 len = subprog_end - subprog_start;
492ecee8
AS
11586 /* BPF_PROG_RUN doesn't call subprogs directly,
11587 * hence main prog stats include the runtime of subprogs.
11588 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 11589 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
11590 */
11591 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
11592 if (!func[i])
11593 goto out_free;
11594 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11595 len * sizeof(struct bpf_insn));
4f74d809 11596 func[i]->type = prog->type;
1c2a088a 11597 func[i]->len = len;
4f74d809
DB
11598 if (bpf_prog_calc_tag(func[i]))
11599 goto out_free;
1c2a088a 11600 func[i]->is_func = 1;
ba64e7d8
YS
11601 func[i]->aux->func_idx = i;
11602 /* the btf and func_info will be freed only at prog->aux */
11603 func[i]->aux->btf = prog->aux->btf;
11604 func[i]->aux->func_info = prog->aux->func_info;
11605
a748c697
MF
11606 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11607 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11608 int ret;
11609
11610 if (!(insn_idx >= subprog_start &&
11611 insn_idx <= subprog_end))
11612 continue;
11613
11614 ret = bpf_jit_add_poke_descriptor(func[i],
11615 &prog->aux->poke_tab[j]);
11616 if (ret < 0) {
11617 verbose(env, "adding tail call poke descriptor failed\n");
11618 goto out_free;
11619 }
11620
11621 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11622
11623 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11624 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11625 if (ret < 0) {
11626 verbose(env, "tracking tail call prog failed\n");
11627 goto out_free;
11628 }
11629 }
11630
1c2a088a
AS
11631 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11632 * Long term would need debug info to populate names
11633 */
11634 func[i]->aux->name[0] = 'F';
9c8105bd 11635 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 11636 func[i]->jit_requested = 1;
c454a46b
MKL
11637 func[i]->aux->linfo = prog->aux->linfo;
11638 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11639 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11640 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
11641 num_exentries = 0;
11642 insn = func[i]->insnsi;
11643 for (j = 0; j < func[i]->len; j++, insn++) {
11644 if (BPF_CLASS(insn->code) == BPF_LDX &&
11645 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11646 num_exentries++;
11647 }
11648 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 11649 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
11650 func[i] = bpf_int_jit_compile(func[i]);
11651 if (!func[i]->jited) {
11652 err = -ENOTSUPP;
11653 goto out_free;
11654 }
11655 cond_resched();
11656 }
a748c697
MF
11657
11658 /* Untrack main program's aux structs so that during map_poke_run()
11659 * we will not stumble upon the unfilled poke descriptors; each
11660 * of the main program's poke descs got distributed across subprogs
11661 * and got tracked onto map, so we are sure that none of them will
11662 * be missed after the operation below
11663 */
11664 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11665 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11666
11667 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11668 }
11669
1c2a088a
AS
11670 /* at this point all bpf functions were successfully JITed
11671 * now populate all bpf_calls with correct addresses and
11672 * run last pass of JIT
11673 */
f910cefa 11674 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11675 insn = func[i]->insnsi;
11676 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba
YS
11677 if (bpf_pseudo_func(insn)) {
11678 subprog = insn[1].imm;
11679 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
11680 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
11681 continue;
11682 }
23a2d70c 11683 if (!bpf_pseudo_call(insn))
1c2a088a
AS
11684 continue;
11685 subprog = insn->off;
0d306c31
PB
11686 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11687 __bpf_call_base;
1c2a088a 11688 }
2162fed4
SD
11689
11690 /* we use the aux data to keep a list of the start addresses
11691 * of the JITed images for each function in the program
11692 *
11693 * for some architectures, such as powerpc64, the imm field
11694 * might not be large enough to hold the offset of the start
11695 * address of the callee's JITed image from __bpf_call_base
11696 *
11697 * in such cases, we can lookup the start address of a callee
11698 * by using its subprog id, available from the off field of
11699 * the call instruction, as an index for this list
11700 */
11701 func[i]->aux->func = func;
11702 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 11703 }
f910cefa 11704 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11705 old_bpf_func = func[i]->bpf_func;
11706 tmp = bpf_int_jit_compile(func[i]);
11707 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11708 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 11709 err = -ENOTSUPP;
1c2a088a
AS
11710 goto out_free;
11711 }
11712 cond_resched();
11713 }
11714
11715 /* finally lock prog and jit images for all functions and
11716 * populate kallsysm
11717 */
f910cefa 11718 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11719 bpf_prog_lock_ro(func[i]);
11720 bpf_prog_kallsyms_add(func[i]);
11721 }
7105e828
DB
11722
11723 /* Last step: make now unused interpreter insns from main
11724 * prog consistent for later dump requests, so they can
11725 * later look the same as if they were interpreted only.
11726 */
11727 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11728 if (bpf_pseudo_func(insn)) {
11729 insn[0].imm = env->insn_aux_data[i].call_imm;
11730 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
11731 continue;
11732 }
23a2d70c 11733 if (!bpf_pseudo_call(insn))
7105e828
DB
11734 continue;
11735 insn->off = env->insn_aux_data[i].call_imm;
11736 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 11737 insn->imm = subprog;
7105e828
DB
11738 }
11739
1c2a088a
AS
11740 prog->jited = 1;
11741 prog->bpf_func = func[0]->bpf_func;
11742 prog->aux->func = func;
f910cefa 11743 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 11744 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
11745 return 0;
11746out_free:
a748c697
MF
11747 for (i = 0; i < env->subprog_cnt; i++) {
11748 if (!func[i])
11749 continue;
11750
11751 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11752 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11753 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11754 }
11755 bpf_jit_free(func[i]);
11756 }
1c2a088a 11757 kfree(func);
c7a89784 11758out_undo_insn:
1c2a088a
AS
11759 /* cleanup main prog to be interpreted */
11760 prog->jit_requested = 0;
11761 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 11762 if (!bpf_pseudo_call(insn))
1c2a088a
AS
11763 continue;
11764 insn->off = 0;
11765 insn->imm = env->insn_aux_data[i].call_imm;
11766 }
c454a46b 11767 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
11768 return err;
11769}
11770
1ea47e01
AS
11771static int fixup_call_args(struct bpf_verifier_env *env)
11772{
19d28fbd 11773#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
11774 struct bpf_prog *prog = env->prog;
11775 struct bpf_insn *insn = prog->insnsi;
11776 int i, depth;
19d28fbd 11777#endif
e4052d06 11778 int err = 0;
1ea47e01 11779
e4052d06
QM
11780 if (env->prog->jit_requested &&
11781 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
11782 err = jit_subprogs(env);
11783 if (err == 0)
1c2a088a 11784 return 0;
c7a89784
DB
11785 if (err == -EFAULT)
11786 return err;
19d28fbd
DM
11787 }
11788#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
11789 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11790 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11791 * have to be rejected, since interpreter doesn't support them yet.
11792 */
11793 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11794 return -EINVAL;
11795 }
1ea47e01 11796 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
11797 if (bpf_pseudo_func(insn)) {
11798 /* When JIT fails the progs with callback calls
11799 * have to be rejected, since interpreter doesn't support them yet.
11800 */
11801 verbose(env, "callbacks are not allowed in non-JITed programs\n");
11802 return -EINVAL;
11803 }
11804
23a2d70c 11805 if (!bpf_pseudo_call(insn))
1ea47e01
AS
11806 continue;
11807 depth = get_callee_stack_depth(env, insn, i);
11808 if (depth < 0)
11809 return depth;
11810 bpf_patch_call_args(insn, depth);
11811 }
19d28fbd
DM
11812 err = 0;
11813#endif
11814 return err;
1ea47e01
AS
11815}
11816
e6ac5933
BJ
11817/* Do various post-verification rewrites in a single program pass.
11818 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 11819 */
e6ac5933 11820static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 11821{
79741b3b 11822 struct bpf_prog *prog = env->prog;
d2e4c1e6 11823 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 11824 struct bpf_insn *insn = prog->insnsi;
e245c5c6 11825 const struct bpf_func_proto *fn;
79741b3b 11826 const int insn_cnt = prog->len;
09772d92 11827 const struct bpf_map_ops *ops;
c93552c4 11828 struct bpf_insn_aux_data *aux;
81ed18ab
AS
11829 struct bpf_insn insn_buf[16];
11830 struct bpf_prog *new_prog;
11831 struct bpf_map *map_ptr;
d2e4c1e6 11832 int i, ret, cnt, delta = 0;
e245c5c6 11833
79741b3b 11834 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 11835 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
11836 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11837 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11838 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 11839 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 11840 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
11841 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11842 struct bpf_insn *patchlet;
11843 struct bpf_insn chk_and_div[] = {
9b00f1b7 11844 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
11845 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11846 BPF_JNE | BPF_K, insn->src_reg,
11847 0, 2, 0),
f6b1b3bf
DB
11848 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11849 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11850 *insn,
11851 };
e88b2c6e 11852 struct bpf_insn chk_and_mod[] = {
9b00f1b7 11853 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
11854 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11855 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 11856 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 11857 *insn,
9b00f1b7
DB
11858 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11859 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 11860 };
f6b1b3bf 11861
e88b2c6e
DB
11862 patchlet = isdiv ? chk_and_div : chk_and_mod;
11863 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 11864 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
11865
11866 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
11867 if (!new_prog)
11868 return -ENOMEM;
11869
11870 delta += cnt - 1;
11871 env->prog = prog = new_prog;
11872 insn = new_prog->insnsi + i + delta;
11873 continue;
11874 }
11875
e6ac5933 11876 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
11877 if (BPF_CLASS(insn->code) == BPF_LD &&
11878 (BPF_MODE(insn->code) == BPF_ABS ||
11879 BPF_MODE(insn->code) == BPF_IND)) {
11880 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11881 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11882 verbose(env, "bpf verifier is misconfigured\n");
11883 return -EINVAL;
11884 }
11885
11886 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11887 if (!new_prog)
11888 return -ENOMEM;
11889
11890 delta += cnt - 1;
11891 env->prog = prog = new_prog;
11892 insn = new_prog->insnsi + i + delta;
11893 continue;
11894 }
11895
e6ac5933 11896 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
11897 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11898 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11899 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11900 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5
DB
11901 struct bpf_insn *patch = &insn_buf[0];
11902 bool issrc, isneg;
11903 u32 off_reg;
11904
11905 aux = &env->insn_aux_data[i + delta];
3612af78
DB
11906 if (!aux->alu_state ||
11907 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
11908 continue;
11909
11910 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11911 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11912 BPF_ALU_SANITIZE_SRC;
11913
11914 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11915 if (isneg)
11916 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
b5871dca 11917 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
979d63d5
DB
11918 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11919 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11920 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11921 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11922 if (issrc) {
11923 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11924 off_reg);
11925 insn->src_reg = BPF_REG_AX;
11926 } else {
11927 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11928 BPF_REG_AX);
11929 }
11930 if (isneg)
11931 insn->code = insn->code == code_add ?
11932 code_sub : code_add;
11933 *patch++ = *insn;
11934 if (issrc && isneg)
11935 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11936 cnt = patch - insn_buf;
11937
11938 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11939 if (!new_prog)
11940 return -ENOMEM;
11941
11942 delta += cnt - 1;
11943 env->prog = prog = new_prog;
11944 insn = new_prog->insnsi + i + delta;
11945 continue;
11946 }
11947
79741b3b
AS
11948 if (insn->code != (BPF_JMP | BPF_CALL))
11949 continue;
cc8b0b92
AS
11950 if (insn->src_reg == BPF_PSEUDO_CALL)
11951 continue;
e245c5c6 11952
79741b3b
AS
11953 if (insn->imm == BPF_FUNC_get_route_realm)
11954 prog->dst_needed = 1;
11955 if (insn->imm == BPF_FUNC_get_prandom_u32)
11956 bpf_user_rnd_init_once();
9802d865
JB
11957 if (insn->imm == BPF_FUNC_override_return)
11958 prog->kprobe_override = 1;
79741b3b 11959 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
11960 /* If we tail call into other programs, we
11961 * cannot make any assumptions since they can
11962 * be replaced dynamically during runtime in
11963 * the program array.
11964 */
11965 prog->cb_access = 1;
e411901c
MF
11966 if (!allow_tail_call_in_subprogs(env))
11967 prog->aux->stack_depth = MAX_BPF_STACK;
11968 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 11969
79741b3b
AS
11970 /* mark bpf_tail_call as different opcode to avoid
11971 * conditional branch in the interpeter for every normal
11972 * call and to prevent accidental JITing by JIT compiler
11973 * that doesn't support bpf_tail_call yet
e245c5c6 11974 */
79741b3b 11975 insn->imm = 0;
71189fa9 11976 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 11977
c93552c4 11978 aux = &env->insn_aux_data[i + delta];
2c78ee89 11979 if (env->bpf_capable && !expect_blinding &&
cc52d914 11980 prog->jit_requested &&
d2e4c1e6
DB
11981 !bpf_map_key_poisoned(aux) &&
11982 !bpf_map_ptr_poisoned(aux) &&
11983 !bpf_map_ptr_unpriv(aux)) {
11984 struct bpf_jit_poke_descriptor desc = {
11985 .reason = BPF_POKE_REASON_TAIL_CALL,
11986 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11987 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 11988 .insn_idx = i + delta,
d2e4c1e6
DB
11989 };
11990
11991 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11992 if (ret < 0) {
11993 verbose(env, "adding tail call poke descriptor failed\n");
11994 return ret;
11995 }
11996
11997 insn->imm = ret + 1;
11998 continue;
11999 }
12000
c93552c4
DB
12001 if (!bpf_map_ptr_unpriv(aux))
12002 continue;
12003
b2157399
AS
12004 /* instead of changing every JIT dealing with tail_call
12005 * emit two extra insns:
12006 * if (index >= max_entries) goto out;
12007 * index &= array->index_mask;
12008 * to avoid out-of-bounds cpu speculation
12009 */
c93552c4 12010 if (bpf_map_ptr_poisoned(aux)) {
40950343 12011 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
12012 return -EINVAL;
12013 }
c93552c4 12014
d2e4c1e6 12015 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
12016 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12017 map_ptr->max_entries, 2);
12018 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12019 container_of(map_ptr,
12020 struct bpf_array,
12021 map)->index_mask);
12022 insn_buf[2] = *insn;
12023 cnt = 3;
12024 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12025 if (!new_prog)
12026 return -ENOMEM;
12027
12028 delta += cnt - 1;
12029 env->prog = prog = new_prog;
12030 insn = new_prog->insnsi + i + delta;
79741b3b
AS
12031 continue;
12032 }
e245c5c6 12033
89c63074 12034 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
12035 * and other inlining handlers are currently limited to 64 bit
12036 * only.
89c63074 12037 */
60b58afc 12038 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
12039 (insn->imm == BPF_FUNC_map_lookup_elem ||
12040 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
12041 insn->imm == BPF_FUNC_map_delete_elem ||
12042 insn->imm == BPF_FUNC_map_push_elem ||
12043 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f
BT
12044 insn->imm == BPF_FUNC_map_peek_elem ||
12045 insn->imm == BPF_FUNC_redirect_map)) {
c93552c4
DB
12046 aux = &env->insn_aux_data[i + delta];
12047 if (bpf_map_ptr_poisoned(aux))
12048 goto patch_call_imm;
12049
d2e4c1e6 12050 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
12051 ops = map_ptr->ops;
12052 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12053 ops->map_gen_lookup) {
12054 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
12055 if (cnt == -EOPNOTSUPP)
12056 goto patch_map_ops_generic;
12057 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
12058 verbose(env, "bpf verifier is misconfigured\n");
12059 return -EINVAL;
12060 }
81ed18ab 12061
09772d92
DB
12062 new_prog = bpf_patch_insn_data(env, i + delta,
12063 insn_buf, cnt);
12064 if (!new_prog)
12065 return -ENOMEM;
81ed18ab 12066
09772d92
DB
12067 delta += cnt - 1;
12068 env->prog = prog = new_prog;
12069 insn = new_prog->insnsi + i + delta;
12070 continue;
12071 }
81ed18ab 12072
09772d92
DB
12073 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12074 (void *(*)(struct bpf_map *map, void *key))NULL));
12075 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12076 (int (*)(struct bpf_map *map, void *key))NULL));
12077 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12078 (int (*)(struct bpf_map *map, void *key, void *value,
12079 u64 flags))NULL));
84430d42
DB
12080 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12081 (int (*)(struct bpf_map *map, void *value,
12082 u64 flags))NULL));
12083 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12084 (int (*)(struct bpf_map *map, void *value))NULL));
12085 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12086 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f
BT
12087 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12088 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12089
4a8f87e6 12090patch_map_ops_generic:
09772d92
DB
12091 switch (insn->imm) {
12092 case BPF_FUNC_map_lookup_elem:
12093 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12094 __bpf_call_base;
12095 continue;
12096 case BPF_FUNC_map_update_elem:
12097 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12098 __bpf_call_base;
12099 continue;
12100 case BPF_FUNC_map_delete_elem:
12101 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12102 __bpf_call_base;
12103 continue;
84430d42
DB
12104 case BPF_FUNC_map_push_elem:
12105 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12106 __bpf_call_base;
12107 continue;
12108 case BPF_FUNC_map_pop_elem:
12109 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12110 __bpf_call_base;
12111 continue;
12112 case BPF_FUNC_map_peek_elem:
12113 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12114 __bpf_call_base;
12115 continue;
e6a4750f
BT
12116 case BPF_FUNC_redirect_map:
12117 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12118 __bpf_call_base;
12119 continue;
09772d92 12120 }
81ed18ab 12121
09772d92 12122 goto patch_call_imm;
81ed18ab
AS
12123 }
12124
e6ac5933 12125 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
12126 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12127 insn->imm == BPF_FUNC_jiffies64) {
12128 struct bpf_insn ld_jiffies_addr[2] = {
12129 BPF_LD_IMM64(BPF_REG_0,
12130 (unsigned long)&jiffies),
12131 };
12132
12133 insn_buf[0] = ld_jiffies_addr[0];
12134 insn_buf[1] = ld_jiffies_addr[1];
12135 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12136 BPF_REG_0, 0);
12137 cnt = 3;
12138
12139 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12140 cnt);
12141 if (!new_prog)
12142 return -ENOMEM;
12143
12144 delta += cnt - 1;
12145 env->prog = prog = new_prog;
12146 insn = new_prog->insnsi + i + delta;
12147 continue;
12148 }
12149
81ed18ab 12150patch_call_imm:
5e43f899 12151 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
12152 /* all functions that have prototype and verifier allowed
12153 * programs to call them, must be real in-kernel functions
12154 */
12155 if (!fn->func) {
61bd5218
JK
12156 verbose(env,
12157 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
12158 func_id_name(insn->imm), insn->imm);
12159 return -EFAULT;
e245c5c6 12160 }
79741b3b 12161 insn->imm = fn->func - __bpf_call_base;
e245c5c6 12162 }
e245c5c6 12163
d2e4c1e6
DB
12164 /* Since poke tab is now finalized, publish aux to tracker. */
12165 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12166 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12167 if (!map_ptr->ops->map_poke_track ||
12168 !map_ptr->ops->map_poke_untrack ||
12169 !map_ptr->ops->map_poke_run) {
12170 verbose(env, "bpf verifier is misconfigured\n");
12171 return -EINVAL;
12172 }
12173
12174 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12175 if (ret < 0) {
12176 verbose(env, "tracking tail call prog failed\n");
12177 return ret;
12178 }
12179 }
12180
79741b3b
AS
12181 return 0;
12182}
e245c5c6 12183
58e2af8b 12184static void free_states(struct bpf_verifier_env *env)
f1bca824 12185{
58e2af8b 12186 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
12187 int i;
12188
9f4686c4
AS
12189 sl = env->free_list;
12190 while (sl) {
12191 sln = sl->next;
12192 free_verifier_state(&sl->state, false);
12193 kfree(sl);
12194 sl = sln;
12195 }
51c39bb1 12196 env->free_list = NULL;
9f4686c4 12197
f1bca824
AS
12198 if (!env->explored_states)
12199 return;
12200
dc2a4ebc 12201 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
12202 sl = env->explored_states[i];
12203
a8f500af
AS
12204 while (sl) {
12205 sln = sl->next;
12206 free_verifier_state(&sl->state, false);
12207 kfree(sl);
12208 sl = sln;
12209 }
51c39bb1 12210 env->explored_states[i] = NULL;
f1bca824 12211 }
51c39bb1 12212}
f1bca824 12213
51c39bb1
AS
12214/* The verifier is using insn_aux_data[] to store temporary data during
12215 * verification and to store information for passes that run after the
12216 * verification like dead code sanitization. do_check_common() for subprogram N
12217 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12218 * temporary data after do_check_common() finds that subprogram N cannot be
12219 * verified independently. pass_cnt counts the number of times
12220 * do_check_common() was run and insn->aux->seen tells the pass number
12221 * insn_aux_data was touched. These variables are compared to clear temporary
12222 * data from failed pass. For testing and experiments do_check_common() can be
12223 * run multiple times even when prior attempt to verify is unsuccessful.
12224 */
12225static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12226{
12227 struct bpf_insn *insn = env->prog->insnsi;
12228 struct bpf_insn_aux_data *aux;
12229 int i, class;
12230
12231 for (i = 0; i < env->prog->len; i++) {
12232 class = BPF_CLASS(insn[i].code);
12233 if (class != BPF_LDX && class != BPF_STX)
12234 continue;
12235 aux = &env->insn_aux_data[i];
12236 if (aux->seen != env->pass_cnt)
12237 continue;
12238 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12239 }
f1bca824
AS
12240}
12241
51c39bb1
AS
12242static int do_check_common(struct bpf_verifier_env *env, int subprog)
12243{
6f8a57cc 12244 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
12245 struct bpf_verifier_state *state;
12246 struct bpf_reg_state *regs;
12247 int ret, i;
12248
12249 env->prev_linfo = NULL;
12250 env->pass_cnt++;
12251
12252 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12253 if (!state)
12254 return -ENOMEM;
12255 state->curframe = 0;
12256 state->speculative = false;
12257 state->branches = 1;
12258 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12259 if (!state->frame[0]) {
12260 kfree(state);
12261 return -ENOMEM;
12262 }
12263 env->cur_state = state;
12264 init_func_state(env, state->frame[0],
12265 BPF_MAIN_FUNC /* callsite */,
12266 0 /* frameno */,
12267 subprog);
12268
12269 regs = state->frame[state->curframe]->regs;
be8704ff 12270 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
12271 ret = btf_prepare_func_args(env, subprog, regs);
12272 if (ret)
12273 goto out;
12274 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12275 if (regs[i].type == PTR_TO_CTX)
12276 mark_reg_known_zero(env, regs, i);
12277 else if (regs[i].type == SCALAR_VALUE)
12278 mark_reg_unknown(env, regs, i);
e5069b9c
DB
12279 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12280 const u32 mem_size = regs[i].mem_size;
12281
12282 mark_reg_known_zero(env, regs, i);
12283 regs[i].mem_size = mem_size;
12284 regs[i].id = ++env->id_gen;
12285 }
51c39bb1
AS
12286 }
12287 } else {
12288 /* 1st arg to a function */
12289 regs[BPF_REG_1].type = PTR_TO_CTX;
12290 mark_reg_known_zero(env, regs, BPF_REG_1);
12291 ret = btf_check_func_arg_match(env, subprog, regs);
12292 if (ret == -EFAULT)
12293 /* unlikely verifier bug. abort.
12294 * ret == 0 and ret < 0 are sadly acceptable for
12295 * main() function due to backward compatibility.
12296 * Like socket filter program may be written as:
12297 * int bpf_prog(struct pt_regs *ctx)
12298 * and never dereference that ctx in the program.
12299 * 'struct pt_regs' is a type mismatch for socket
12300 * filter that should be using 'struct __sk_buff'.
12301 */
12302 goto out;
12303 }
12304
12305 ret = do_check(env);
12306out:
f59bbfc2
AS
12307 /* check for NULL is necessary, since cur_state can be freed inside
12308 * do_check() under memory pressure.
12309 */
12310 if (env->cur_state) {
12311 free_verifier_state(env->cur_state, true);
12312 env->cur_state = NULL;
12313 }
6f8a57cc
AN
12314 while (!pop_stack(env, NULL, NULL, false));
12315 if (!ret && pop_log)
12316 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
12317 free_states(env);
12318 if (ret)
12319 /* clean aux data in case subprog was rejected */
12320 sanitize_insn_aux_data(env);
12321 return ret;
12322}
12323
12324/* Verify all global functions in a BPF program one by one based on their BTF.
12325 * All global functions must pass verification. Otherwise the whole program is rejected.
12326 * Consider:
12327 * int bar(int);
12328 * int foo(int f)
12329 * {
12330 * return bar(f);
12331 * }
12332 * int bar(int b)
12333 * {
12334 * ...
12335 * }
12336 * foo() will be verified first for R1=any_scalar_value. During verification it
12337 * will be assumed that bar() already verified successfully and call to bar()
12338 * from foo() will be checked for type match only. Later bar() will be verified
12339 * independently to check that it's safe for R1=any_scalar_value.
12340 */
12341static int do_check_subprogs(struct bpf_verifier_env *env)
12342{
12343 struct bpf_prog_aux *aux = env->prog->aux;
12344 int i, ret;
12345
12346 if (!aux->func_info)
12347 return 0;
12348
12349 for (i = 1; i < env->subprog_cnt; i++) {
12350 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12351 continue;
12352 env->insn_idx = env->subprog_info[i].start;
12353 WARN_ON_ONCE(env->insn_idx == 0);
12354 ret = do_check_common(env, i);
12355 if (ret) {
12356 return ret;
12357 } else if (env->log.level & BPF_LOG_LEVEL) {
12358 verbose(env,
12359 "Func#%d is safe for any args that match its prototype\n",
12360 i);
12361 }
12362 }
12363 return 0;
12364}
12365
12366static int do_check_main(struct bpf_verifier_env *env)
12367{
12368 int ret;
12369
12370 env->insn_idx = 0;
12371 ret = do_check_common(env, 0);
12372 if (!ret)
12373 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12374 return ret;
12375}
12376
12377
06ee7115
AS
12378static void print_verification_stats(struct bpf_verifier_env *env)
12379{
12380 int i;
12381
12382 if (env->log.level & BPF_LOG_STATS) {
12383 verbose(env, "verification time %lld usec\n",
12384 div_u64(env->verification_time, 1000));
12385 verbose(env, "stack depth ");
12386 for (i = 0; i < env->subprog_cnt; i++) {
12387 u32 depth = env->subprog_info[i].stack_depth;
12388
12389 verbose(env, "%d", depth);
12390 if (i + 1 < env->subprog_cnt)
12391 verbose(env, "+");
12392 }
12393 verbose(env, "\n");
12394 }
12395 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12396 "total_states %d peak_states %d mark_read %d\n",
12397 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12398 env->max_states_per_insn, env->total_states,
12399 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12400}
12401
27ae7997
MKL
12402static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12403{
12404 const struct btf_type *t, *func_proto;
12405 const struct bpf_struct_ops *st_ops;
12406 const struct btf_member *member;
12407 struct bpf_prog *prog = env->prog;
12408 u32 btf_id, member_idx;
12409 const char *mname;
12410
12411 btf_id = prog->aux->attach_btf_id;
12412 st_ops = bpf_struct_ops_find(btf_id);
12413 if (!st_ops) {
12414 verbose(env, "attach_btf_id %u is not a supported struct\n",
12415 btf_id);
12416 return -ENOTSUPP;
12417 }
12418
12419 t = st_ops->type;
12420 member_idx = prog->expected_attach_type;
12421 if (member_idx >= btf_type_vlen(t)) {
12422 verbose(env, "attach to invalid member idx %u of struct %s\n",
12423 member_idx, st_ops->name);
12424 return -EINVAL;
12425 }
12426
12427 member = &btf_type_member(t)[member_idx];
12428 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12429 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12430 NULL);
12431 if (!func_proto) {
12432 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12433 mname, member_idx, st_ops->name);
12434 return -EINVAL;
12435 }
12436
12437 if (st_ops->check_member) {
12438 int err = st_ops->check_member(t, member);
12439
12440 if (err) {
12441 verbose(env, "attach to unsupported member %s of struct %s\n",
12442 mname, st_ops->name);
12443 return err;
12444 }
12445 }
12446
12447 prog->aux->attach_func_proto = func_proto;
12448 prog->aux->attach_func_name = mname;
12449 env->ops = st_ops->verifier_ops;
12450
12451 return 0;
12452}
6ba43b76
KS
12453#define SECURITY_PREFIX "security_"
12454
f7b12b6f 12455static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12456{
69191754 12457 if (within_error_injection_list(addr) ||
f7b12b6f 12458 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12459 return 0;
6ba43b76 12460
6ba43b76
KS
12461 return -EINVAL;
12462}
27ae7997 12463
1e6c62a8
AS
12464/* list of non-sleepable functions that are otherwise on
12465 * ALLOW_ERROR_INJECTION list
12466 */
12467BTF_SET_START(btf_non_sleepable_error_inject)
12468/* Three functions below can be called from sleepable and non-sleepable context.
12469 * Assume non-sleepable from bpf safety point of view.
12470 */
12471BTF_ID(func, __add_to_page_cache_locked)
12472BTF_ID(func, should_fail_alloc_page)
12473BTF_ID(func, should_failslab)
12474BTF_SET_END(btf_non_sleepable_error_inject)
12475
12476static int check_non_sleepable_error_inject(u32 btf_id)
12477{
12478 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12479}
12480
f7b12b6f
THJ
12481int bpf_check_attach_target(struct bpf_verifier_log *log,
12482 const struct bpf_prog *prog,
12483 const struct bpf_prog *tgt_prog,
12484 u32 btf_id,
12485 struct bpf_attach_target_info *tgt_info)
38207291 12486{
be8704ff 12487 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 12488 const char prefix[] = "btf_trace_";
5b92a28a 12489 int ret = 0, subprog = -1, i;
38207291 12490 const struct btf_type *t;
5b92a28a 12491 bool conservative = true;
38207291 12492 const char *tname;
5b92a28a 12493 struct btf *btf;
f7b12b6f 12494 long addr = 0;
38207291 12495
f1b9509c 12496 if (!btf_id) {
efc68158 12497 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
12498 return -EINVAL;
12499 }
22dc4a0f 12500 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 12501 if (!btf) {
efc68158 12502 bpf_log(log,
5b92a28a
AS
12503 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12504 return -EINVAL;
12505 }
12506 t = btf_type_by_id(btf, btf_id);
f1b9509c 12507 if (!t) {
efc68158 12508 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
12509 return -EINVAL;
12510 }
5b92a28a 12511 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 12512 if (!tname) {
efc68158 12513 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
12514 return -EINVAL;
12515 }
5b92a28a
AS
12516 if (tgt_prog) {
12517 struct bpf_prog_aux *aux = tgt_prog->aux;
12518
12519 for (i = 0; i < aux->func_info_cnt; i++)
12520 if (aux->func_info[i].type_id == btf_id) {
12521 subprog = i;
12522 break;
12523 }
12524 if (subprog == -1) {
efc68158 12525 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
12526 return -EINVAL;
12527 }
12528 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
12529 if (prog_extension) {
12530 if (conservative) {
efc68158 12531 bpf_log(log,
be8704ff
AS
12532 "Cannot replace static functions\n");
12533 return -EINVAL;
12534 }
12535 if (!prog->jit_requested) {
efc68158 12536 bpf_log(log,
be8704ff
AS
12537 "Extension programs should be JITed\n");
12538 return -EINVAL;
12539 }
be8704ff
AS
12540 }
12541 if (!tgt_prog->jited) {
efc68158 12542 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
12543 return -EINVAL;
12544 }
12545 if (tgt_prog->type == prog->type) {
12546 /* Cannot fentry/fexit another fentry/fexit program.
12547 * Cannot attach program extension to another extension.
12548 * It's ok to attach fentry/fexit to extension program.
12549 */
efc68158 12550 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
12551 return -EINVAL;
12552 }
12553 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12554 prog_extension &&
12555 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12556 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12557 /* Program extensions can extend all program types
12558 * except fentry/fexit. The reason is the following.
12559 * The fentry/fexit programs are used for performance
12560 * analysis, stats and can be attached to any program
12561 * type except themselves. When extension program is
12562 * replacing XDP function it is necessary to allow
12563 * performance analysis of all functions. Both original
12564 * XDP program and its program extension. Hence
12565 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12566 * allowed. If extending of fentry/fexit was allowed it
12567 * would be possible to create long call chain
12568 * fentry->extension->fentry->extension beyond
12569 * reasonable stack size. Hence extending fentry is not
12570 * allowed.
12571 */
efc68158 12572 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
12573 return -EINVAL;
12574 }
5b92a28a 12575 } else {
be8704ff 12576 if (prog_extension) {
efc68158 12577 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
12578 return -EINVAL;
12579 }
5b92a28a 12580 }
f1b9509c
AS
12581
12582 switch (prog->expected_attach_type) {
12583 case BPF_TRACE_RAW_TP:
5b92a28a 12584 if (tgt_prog) {
efc68158 12585 bpf_log(log,
5b92a28a
AS
12586 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12587 return -EINVAL;
12588 }
38207291 12589 if (!btf_type_is_typedef(t)) {
efc68158 12590 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
12591 btf_id);
12592 return -EINVAL;
12593 }
f1b9509c 12594 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 12595 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
12596 btf_id, tname);
12597 return -EINVAL;
12598 }
12599 tname += sizeof(prefix) - 1;
5b92a28a 12600 t = btf_type_by_id(btf, t->type);
38207291
MKL
12601 if (!btf_type_is_ptr(t))
12602 /* should never happen in valid vmlinux build */
12603 return -EINVAL;
5b92a28a 12604 t = btf_type_by_id(btf, t->type);
38207291
MKL
12605 if (!btf_type_is_func_proto(t))
12606 /* should never happen in valid vmlinux build */
12607 return -EINVAL;
12608
f7b12b6f 12609 break;
15d83c4d
YS
12610 case BPF_TRACE_ITER:
12611 if (!btf_type_is_func(t)) {
efc68158 12612 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
12613 btf_id);
12614 return -EINVAL;
12615 }
12616 t = btf_type_by_id(btf, t->type);
12617 if (!btf_type_is_func_proto(t))
12618 return -EINVAL;
f7b12b6f
THJ
12619 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12620 if (ret)
12621 return ret;
12622 break;
be8704ff
AS
12623 default:
12624 if (!prog_extension)
12625 return -EINVAL;
df561f66 12626 fallthrough;
ae240823 12627 case BPF_MODIFY_RETURN:
9e4e01df 12628 case BPF_LSM_MAC:
fec56f58
AS
12629 case BPF_TRACE_FENTRY:
12630 case BPF_TRACE_FEXIT:
12631 if (!btf_type_is_func(t)) {
efc68158 12632 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
12633 btf_id);
12634 return -EINVAL;
12635 }
be8704ff 12636 if (prog_extension &&
efc68158 12637 btf_check_type_match(log, prog, btf, t))
be8704ff 12638 return -EINVAL;
5b92a28a 12639 t = btf_type_by_id(btf, t->type);
fec56f58
AS
12640 if (!btf_type_is_func_proto(t))
12641 return -EINVAL;
f7b12b6f 12642
4a1e7c0c
THJ
12643 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12644 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12645 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12646 return -EINVAL;
12647
f7b12b6f 12648 if (tgt_prog && conservative)
5b92a28a 12649 t = NULL;
f7b12b6f
THJ
12650
12651 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 12652 if (ret < 0)
f7b12b6f
THJ
12653 return ret;
12654
5b92a28a 12655 if (tgt_prog) {
e9eeec58
YS
12656 if (subprog == 0)
12657 addr = (long) tgt_prog->bpf_func;
12658 else
12659 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
12660 } else {
12661 addr = kallsyms_lookup_name(tname);
12662 if (!addr) {
efc68158 12663 bpf_log(log,
5b92a28a
AS
12664 "The address of function %s cannot be found\n",
12665 tname);
f7b12b6f 12666 return -ENOENT;
5b92a28a 12667 }
fec56f58 12668 }
18644cec 12669
1e6c62a8
AS
12670 if (prog->aux->sleepable) {
12671 ret = -EINVAL;
12672 switch (prog->type) {
12673 case BPF_PROG_TYPE_TRACING:
12674 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12675 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12676 */
12677 if (!check_non_sleepable_error_inject(btf_id) &&
12678 within_error_injection_list(addr))
12679 ret = 0;
12680 break;
12681 case BPF_PROG_TYPE_LSM:
12682 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12683 * Only some of them are sleepable.
12684 */
423f1610 12685 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
12686 ret = 0;
12687 break;
12688 default:
12689 break;
12690 }
f7b12b6f
THJ
12691 if (ret) {
12692 bpf_log(log, "%s is not sleepable\n", tname);
12693 return ret;
12694 }
1e6c62a8 12695 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 12696 if (tgt_prog) {
efc68158 12697 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
12698 return -EINVAL;
12699 }
12700 ret = check_attach_modify_return(addr, tname);
12701 if (ret) {
12702 bpf_log(log, "%s() is not modifiable\n", tname);
12703 return ret;
1af9270e 12704 }
18644cec 12705 }
f7b12b6f
THJ
12706
12707 break;
12708 }
12709 tgt_info->tgt_addr = addr;
12710 tgt_info->tgt_name = tname;
12711 tgt_info->tgt_type = t;
12712 return 0;
12713}
12714
12715static int check_attach_btf_id(struct bpf_verifier_env *env)
12716{
12717 struct bpf_prog *prog = env->prog;
3aac1ead 12718 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
12719 struct bpf_attach_target_info tgt_info = {};
12720 u32 btf_id = prog->aux->attach_btf_id;
12721 struct bpf_trampoline *tr;
12722 int ret;
12723 u64 key;
12724
12725 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12726 prog->type != BPF_PROG_TYPE_LSM) {
12727 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12728 return -EINVAL;
12729 }
12730
12731 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12732 return check_struct_ops_btf_id(env);
12733
12734 if (prog->type != BPF_PROG_TYPE_TRACING &&
12735 prog->type != BPF_PROG_TYPE_LSM &&
12736 prog->type != BPF_PROG_TYPE_EXT)
12737 return 0;
12738
12739 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12740 if (ret)
fec56f58 12741 return ret;
f7b12b6f
THJ
12742
12743 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
12744 /* to make freplace equivalent to their targets, they need to
12745 * inherit env->ops and expected_attach_type for the rest of the
12746 * verification
12747 */
f7b12b6f
THJ
12748 env->ops = bpf_verifier_ops[tgt_prog->type];
12749 prog->expected_attach_type = tgt_prog->expected_attach_type;
12750 }
12751
12752 /* store info about the attachment target that will be used later */
12753 prog->aux->attach_func_proto = tgt_info.tgt_type;
12754 prog->aux->attach_func_name = tgt_info.tgt_name;
12755
4a1e7c0c
THJ
12756 if (tgt_prog) {
12757 prog->aux->saved_dst_prog_type = tgt_prog->type;
12758 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12759 }
12760
f7b12b6f
THJ
12761 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12762 prog->aux->attach_btf_trace = true;
12763 return 0;
12764 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12765 if (!bpf_iter_prog_supported(prog))
12766 return -EINVAL;
12767 return 0;
12768 }
12769
12770 if (prog->type == BPF_PROG_TYPE_LSM) {
12771 ret = bpf_lsm_verify_prog(&env->log, prog);
12772 if (ret < 0)
12773 return ret;
38207291 12774 }
f7b12b6f 12775
22dc4a0f 12776 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
12777 tr = bpf_trampoline_get(key, &tgt_info);
12778 if (!tr)
12779 return -ENOMEM;
12780
3aac1ead 12781 prog->aux->dst_trampoline = tr;
f7b12b6f 12782 return 0;
38207291
MKL
12783}
12784
76654e67
AM
12785struct btf *bpf_get_btf_vmlinux(void)
12786{
12787 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12788 mutex_lock(&bpf_verifier_lock);
12789 if (!btf_vmlinux)
12790 btf_vmlinux = btf_parse_vmlinux();
12791 mutex_unlock(&bpf_verifier_lock);
12792 }
12793 return btf_vmlinux;
12794}
12795
838e9690
YS
12796int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12797 union bpf_attr __user *uattr)
51580e79 12798{
06ee7115 12799 u64 start_time = ktime_get_ns();
58e2af8b 12800 struct bpf_verifier_env *env;
b9193c1b 12801 struct bpf_verifier_log *log;
9e4c24e7 12802 int i, len, ret = -EINVAL;
e2ae4ca2 12803 bool is_priv;
51580e79 12804
eba0c929
AB
12805 /* no program is valid */
12806 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12807 return -EINVAL;
12808
58e2af8b 12809 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
12810 * allocate/free it every time bpf_check() is called
12811 */
58e2af8b 12812 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
12813 if (!env)
12814 return -ENOMEM;
61bd5218 12815 log = &env->log;
cbd35700 12816
9e4c24e7 12817 len = (*prog)->len;
fad953ce 12818 env->insn_aux_data =
9e4c24e7 12819 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
12820 ret = -ENOMEM;
12821 if (!env->insn_aux_data)
12822 goto err_free_env;
9e4c24e7
JK
12823 for (i = 0; i < len; i++)
12824 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 12825 env->prog = *prog;
00176a34 12826 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 12827 is_priv = bpf_capable();
0246e64d 12828
76654e67 12829 bpf_get_btf_vmlinux();
8580ac94 12830
cbd35700 12831 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
12832 if (!is_priv)
12833 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
12834
12835 if (attr->log_level || attr->log_buf || attr->log_size) {
12836 /* user requested verbose verifier output
12837 * and supplied buffer to store the verification trace
12838 */
e7bf8249
JK
12839 log->level = attr->log_level;
12840 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12841 log->len_total = attr->log_size;
cbd35700
AS
12842
12843 ret = -EINVAL;
e7bf8249 12844 /* log attributes have to be sane */
7a9f5c65 12845 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 12846 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 12847 goto err_unlock;
cbd35700 12848 }
1ad2f583 12849
8580ac94
AS
12850 if (IS_ERR(btf_vmlinux)) {
12851 /* Either gcc or pahole or kernel are broken. */
12852 verbose(env, "in-kernel BTF is malformed\n");
12853 ret = PTR_ERR(btf_vmlinux);
38207291 12854 goto skip_full_check;
8580ac94
AS
12855 }
12856
1ad2f583
DB
12857 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12858 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 12859 env->strict_alignment = true;
e9ee9efc
DM
12860 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12861 env->strict_alignment = false;
cbd35700 12862
2c78ee89 12863 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 12864 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 12865 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
12866 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12867 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12868 env->bpf_capable = bpf_capable();
e2ae4ca2 12869
10d274e8
AS
12870 if (is_priv)
12871 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12872
cae1927c 12873 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 12874 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 12875 if (ret)
f4e3ec0d 12876 goto skip_full_check;
ab3f0063
JK
12877 }
12878
dc2a4ebc 12879 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 12880 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
12881 GFP_USER);
12882 ret = -ENOMEM;
12883 if (!env->explored_states)
12884 goto skip_full_check;
12885
d9762e84 12886 ret = check_subprogs(env);
475fb78f
AS
12887 if (ret < 0)
12888 goto skip_full_check;
12889
c454a46b 12890 ret = check_btf_info(env, attr, uattr);
838e9690
YS
12891 if (ret < 0)
12892 goto skip_full_check;
12893
be8704ff
AS
12894 ret = check_attach_btf_id(env);
12895 if (ret)
12896 goto skip_full_check;
12897
4976b718
HL
12898 ret = resolve_pseudo_ldimm64(env);
12899 if (ret < 0)
12900 goto skip_full_check;
12901
d9762e84
MKL
12902 ret = check_cfg(env);
12903 if (ret < 0)
12904 goto skip_full_check;
12905
51c39bb1
AS
12906 ret = do_check_subprogs(env);
12907 ret = ret ?: do_check_main(env);
cbd35700 12908
c941ce9c
QM
12909 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12910 ret = bpf_prog_offload_finalize(env);
12911
0246e64d 12912skip_full_check:
51c39bb1 12913 kvfree(env->explored_states);
0246e64d 12914
c131187d 12915 if (ret == 0)
9b38c405 12916 ret = check_max_stack_depth(env);
c131187d 12917
9b38c405 12918 /* instruction rewrites happen after this point */
e2ae4ca2
JK
12919 if (is_priv) {
12920 if (ret == 0)
12921 opt_hard_wire_dead_code_branches(env);
52875a04
JK
12922 if (ret == 0)
12923 ret = opt_remove_dead_code(env);
a1b14abc
JK
12924 if (ret == 0)
12925 ret = opt_remove_nops(env);
52875a04
JK
12926 } else {
12927 if (ret == 0)
12928 sanitize_dead_code(env);
e2ae4ca2
JK
12929 }
12930
9bac3d6d
AS
12931 if (ret == 0)
12932 /* program is valid, convert *(u32*)(ctx + off) accesses */
12933 ret = convert_ctx_accesses(env);
12934
e245c5c6 12935 if (ret == 0)
e6ac5933 12936 ret = do_misc_fixups(env);
e245c5c6 12937
a4b1d3c1
JW
12938 /* do 32-bit optimization after insn patching has done so those patched
12939 * insns could be handled correctly.
12940 */
d6c2308c
JW
12941 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12942 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12943 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12944 : false;
a4b1d3c1
JW
12945 }
12946
1ea47e01
AS
12947 if (ret == 0)
12948 ret = fixup_call_args(env);
12949
06ee7115
AS
12950 env->verification_time = ktime_get_ns() - start_time;
12951 print_verification_stats(env);
12952
a2a7d570 12953 if (log->level && bpf_verifier_log_full(log))
cbd35700 12954 ret = -ENOSPC;
a2a7d570 12955 if (log->level && !log->ubuf) {
cbd35700 12956 ret = -EFAULT;
a2a7d570 12957 goto err_release_maps;
cbd35700
AS
12958 }
12959
541c3bad
AN
12960 if (ret)
12961 goto err_release_maps;
12962
12963 if (env->used_map_cnt) {
0246e64d 12964 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
12965 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12966 sizeof(env->used_maps[0]),
12967 GFP_KERNEL);
0246e64d 12968
9bac3d6d 12969 if (!env->prog->aux->used_maps) {
0246e64d 12970 ret = -ENOMEM;
a2a7d570 12971 goto err_release_maps;
0246e64d
AS
12972 }
12973
9bac3d6d 12974 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 12975 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 12976 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
12977 }
12978 if (env->used_btf_cnt) {
12979 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12980 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12981 sizeof(env->used_btfs[0]),
12982 GFP_KERNEL);
12983 if (!env->prog->aux->used_btfs) {
12984 ret = -ENOMEM;
12985 goto err_release_maps;
12986 }
0246e64d 12987
541c3bad
AN
12988 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12989 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12990 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12991 }
12992 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
12993 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12994 * bpf_ld_imm64 instructions
12995 */
12996 convert_pseudo_ld_imm64(env);
12997 }
cbd35700 12998
541c3bad 12999 adjust_btf_func(env);
ba64e7d8 13000
a2a7d570 13001err_release_maps:
9bac3d6d 13002 if (!env->prog->aux->used_maps)
0246e64d 13003 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 13004 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
13005 */
13006 release_maps(env);
541c3bad
AN
13007 if (!env->prog->aux->used_btfs)
13008 release_btfs(env);
03f87c0b
THJ
13009
13010 /* extension progs temporarily inherit the attach_type of their targets
13011 for verification purposes, so set it back to zero before returning
13012 */
13013 if (env->prog->type == BPF_PROG_TYPE_EXT)
13014 env->prog->expected_attach_type = 0;
13015
9bac3d6d 13016 *prog = env->prog;
3df126f3 13017err_unlock:
45a73c17
AS
13018 if (!is_priv)
13019 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
13020 vfree(env->insn_aux_data);
13021err_free_env:
13022 kfree(env);
51580e79
AS
13023 return ret;
13024}