bpf: Add bpf_for_each_map_elem() helper
[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
17a52670
AS
534/* string representation of 'enum bpf_reg_type' */
535static const char * const reg_type_str[] = {
536 [NOT_INIT] = "?",
f1174f77 537 [SCALAR_VALUE] = "inv",
17a52670
AS
538 [PTR_TO_CTX] = "ctx",
539 [CONST_PTR_TO_MAP] = "map_ptr",
540 [PTR_TO_MAP_VALUE] = "map_value",
541 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 542 [PTR_TO_STACK] = "fp",
969bf05e 543 [PTR_TO_PACKET] = "pkt",
de8f3a83 544 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 545 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 546 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
547 [PTR_TO_SOCKET] = "sock",
548 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
549 [PTR_TO_SOCK_COMMON] = "sock_common",
550 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
551 [PTR_TO_TCP_SOCK] = "tcp_sock",
552 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 553 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 554 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 555 [PTR_TO_BTF_ID] = "ptr_",
b121b341 556 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
eaa6bcb7 557 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
457f4436
AN
558 [PTR_TO_MEM] = "mem",
559 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
560 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
561 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
562 [PTR_TO_RDWR_BUF] = "rdwr_buf",
563 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
69c087ba
YS
564 [PTR_TO_FUNC] = "func",
565 [PTR_TO_MAP_KEY] = "map_key",
17a52670
AS
566};
567
8efea21d
EC
568static char slot_type_char[] = {
569 [STACK_INVALID] = '?',
570 [STACK_SPILL] = 'r',
571 [STACK_MISC] = 'm',
572 [STACK_ZERO] = '0',
573};
574
4e92024a
AS
575static void print_liveness(struct bpf_verifier_env *env,
576 enum bpf_reg_liveness live)
577{
9242b5f5 578 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
579 verbose(env, "_");
580 if (live & REG_LIVE_READ)
581 verbose(env, "r");
582 if (live & REG_LIVE_WRITTEN)
583 verbose(env, "w");
9242b5f5
AS
584 if (live & REG_LIVE_DONE)
585 verbose(env, "D");
4e92024a
AS
586}
587
f4d7e40a
AS
588static struct bpf_func_state *func(struct bpf_verifier_env *env,
589 const struct bpf_reg_state *reg)
590{
591 struct bpf_verifier_state *cur = env->cur_state;
592
593 return cur->frame[reg->frameno];
594}
595
22dc4a0f 596static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 597{
22dc4a0f 598 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
599}
600
61bd5218 601static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 602 const struct bpf_func_state *state)
17a52670 603{
f4d7e40a 604 const struct bpf_reg_state *reg;
17a52670
AS
605 enum bpf_reg_type t;
606 int i;
607
f4d7e40a
AS
608 if (state->frameno)
609 verbose(env, " frame%d:", state->frameno);
17a52670 610 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
611 reg = &state->regs[i];
612 t = reg->type;
17a52670
AS
613 if (t == NOT_INIT)
614 continue;
4e92024a
AS
615 verbose(env, " R%d", i);
616 print_liveness(env, reg->live);
617 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
618 if (t == SCALAR_VALUE && reg->precise)
619 verbose(env, "P");
f1174f77
EC
620 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
621 tnum_is_const(reg->var_off)) {
622 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 623 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 624 } else {
eaa6bcb7
HL
625 if (t == PTR_TO_BTF_ID ||
626 t == PTR_TO_BTF_ID_OR_NULL ||
627 t == PTR_TO_PERCPU_BTF_ID)
22dc4a0f 628 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
cba368c1
MKL
629 verbose(env, "(id=%d", reg->id);
630 if (reg_type_may_be_refcounted_or_null(t))
631 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 632 if (t != SCALAR_VALUE)
61bd5218 633 verbose(env, ",off=%d", reg->off);
de8f3a83 634 if (type_is_pkt_pointer(t))
61bd5218 635 verbose(env, ",r=%d", reg->range);
f1174f77 636 else if (t == CONST_PTR_TO_MAP ||
69c087ba 637 t == PTR_TO_MAP_KEY ||
f1174f77
EC
638 t == PTR_TO_MAP_VALUE ||
639 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 640 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
641 reg->map_ptr->key_size,
642 reg->map_ptr->value_size);
7d1238f2
EC
643 if (tnum_is_const(reg->var_off)) {
644 /* Typically an immediate SCALAR_VALUE, but
645 * could be a pointer whose offset is too big
646 * for reg->off
647 */
61bd5218 648 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
649 } else {
650 if (reg->smin_value != reg->umin_value &&
651 reg->smin_value != S64_MIN)
61bd5218 652 verbose(env, ",smin_value=%lld",
7d1238f2
EC
653 (long long)reg->smin_value);
654 if (reg->smax_value != reg->umax_value &&
655 reg->smax_value != S64_MAX)
61bd5218 656 verbose(env, ",smax_value=%lld",
7d1238f2
EC
657 (long long)reg->smax_value);
658 if (reg->umin_value != 0)
61bd5218 659 verbose(env, ",umin_value=%llu",
7d1238f2
EC
660 (unsigned long long)reg->umin_value);
661 if (reg->umax_value != U64_MAX)
61bd5218 662 verbose(env, ",umax_value=%llu",
7d1238f2
EC
663 (unsigned long long)reg->umax_value);
664 if (!tnum_is_unknown(reg->var_off)) {
665 char tn_buf[48];
f1174f77 666
7d1238f2 667 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 668 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 669 }
3f50f132
JF
670 if (reg->s32_min_value != reg->smin_value &&
671 reg->s32_min_value != S32_MIN)
672 verbose(env, ",s32_min_value=%d",
673 (int)(reg->s32_min_value));
674 if (reg->s32_max_value != reg->smax_value &&
675 reg->s32_max_value != S32_MAX)
676 verbose(env, ",s32_max_value=%d",
677 (int)(reg->s32_max_value));
678 if (reg->u32_min_value != reg->umin_value &&
679 reg->u32_min_value != U32_MIN)
680 verbose(env, ",u32_min_value=%d",
681 (int)(reg->u32_min_value));
682 if (reg->u32_max_value != reg->umax_value &&
683 reg->u32_max_value != U32_MAX)
684 verbose(env, ",u32_max_value=%d",
685 (int)(reg->u32_max_value));
f1174f77 686 }
61bd5218 687 verbose(env, ")");
f1174f77 688 }
17a52670 689 }
638f5b90 690 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
691 char types_buf[BPF_REG_SIZE + 1];
692 bool valid = false;
693 int j;
694
695 for (j = 0; j < BPF_REG_SIZE; j++) {
696 if (state->stack[i].slot_type[j] != STACK_INVALID)
697 valid = true;
698 types_buf[j] = slot_type_char[
699 state->stack[i].slot_type[j]];
700 }
701 types_buf[BPF_REG_SIZE] = 0;
702 if (!valid)
703 continue;
704 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
705 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
706 if (state->stack[i].slot_type[0] == STACK_SPILL) {
707 reg = &state->stack[i].spilled_ptr;
708 t = reg->type;
709 verbose(env, "=%s", reg_type_str[t]);
710 if (t == SCALAR_VALUE && reg->precise)
711 verbose(env, "P");
712 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
713 verbose(env, "%lld", reg->var_off.value + reg->off);
714 } else {
8efea21d 715 verbose(env, "=%s", types_buf);
b5dc0163 716 }
17a52670 717 }
fd978bf7
JS
718 if (state->acquired_refs && state->refs[0].id) {
719 verbose(env, " refs=%d", state->refs[0].id);
720 for (i = 1; i < state->acquired_refs; i++)
721 if (state->refs[i].id)
722 verbose(env, ",%d", state->refs[i].id);
723 }
61bd5218 724 verbose(env, "\n");
17a52670
AS
725}
726
84dbf350
JS
727#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
728static int copy_##NAME##_state(struct bpf_func_state *dst, \
729 const struct bpf_func_state *src) \
730{ \
731 if (!src->FIELD) \
732 return 0; \
733 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
734 /* internal bug, make state invalid to reject the program */ \
735 memset(dst, 0, sizeof(*dst)); \
736 return -EFAULT; \
737 } \
738 memcpy(dst->FIELD, src->FIELD, \
739 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
740 return 0; \
638f5b90 741}
fd978bf7
JS
742/* copy_reference_state() */
743COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
744/* copy_stack_state() */
745COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
746#undef COPY_STATE_FN
747
748#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
749static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
750 bool copy_old) \
751{ \
752 u32 old_size = state->COUNT; \
753 struct bpf_##NAME##_state *new_##FIELD; \
754 int slot = size / SIZE; \
755 \
756 if (size <= old_size || !size) { \
757 if (copy_old) \
758 return 0; \
759 state->COUNT = slot * SIZE; \
760 if (!size && old_size) { \
761 kfree(state->FIELD); \
762 state->FIELD = NULL; \
763 } \
764 return 0; \
765 } \
766 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
767 GFP_KERNEL); \
768 if (!new_##FIELD) \
769 return -ENOMEM; \
770 if (copy_old) { \
771 if (state->FIELD) \
772 memcpy(new_##FIELD, state->FIELD, \
773 sizeof(*new_##FIELD) * (old_size / SIZE)); \
774 memset(new_##FIELD + old_size / SIZE, 0, \
775 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
776 } \
777 state->COUNT = slot * SIZE; \
778 kfree(state->FIELD); \
779 state->FIELD = new_##FIELD; \
780 return 0; \
781}
fd978bf7
JS
782/* realloc_reference_state() */
783REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
784/* realloc_stack_state() */
785REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
786#undef REALLOC_STATE_FN
638f5b90
AS
787
788/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
789 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 790 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
791 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
792 * which realloc_stack_state() copies over. It points to previous
793 * bpf_verifier_state which is never reallocated.
638f5b90 794 */
fd978bf7
JS
795static int realloc_func_state(struct bpf_func_state *state, int stack_size,
796 int refs_size, bool copy_old)
638f5b90 797{
fd978bf7
JS
798 int err = realloc_reference_state(state, refs_size, copy_old);
799 if (err)
800 return err;
801 return realloc_stack_state(state, stack_size, copy_old);
802}
803
804/* Acquire a pointer id from the env and update the state->refs to include
805 * this new pointer reference.
806 * On success, returns a valid pointer id to associate with the register
807 * On failure, returns a negative errno.
638f5b90 808 */
fd978bf7 809static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 810{
fd978bf7
JS
811 struct bpf_func_state *state = cur_func(env);
812 int new_ofs = state->acquired_refs;
813 int id, err;
814
815 err = realloc_reference_state(state, state->acquired_refs + 1, true);
816 if (err)
817 return err;
818 id = ++env->id_gen;
819 state->refs[new_ofs].id = id;
820 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 821
fd978bf7
JS
822 return id;
823}
824
825/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 826static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
827{
828 int i, last_idx;
829
fd978bf7
JS
830 last_idx = state->acquired_refs - 1;
831 for (i = 0; i < state->acquired_refs; i++) {
832 if (state->refs[i].id == ptr_id) {
833 if (last_idx && i != last_idx)
834 memcpy(&state->refs[i], &state->refs[last_idx],
835 sizeof(*state->refs));
836 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
837 state->acquired_refs--;
638f5b90 838 return 0;
638f5b90 839 }
638f5b90 840 }
46f8bc92 841 return -EINVAL;
fd978bf7
JS
842}
843
844static int transfer_reference_state(struct bpf_func_state *dst,
845 struct bpf_func_state *src)
846{
847 int err = realloc_reference_state(dst, src->acquired_refs, false);
848 if (err)
849 return err;
850 err = copy_reference_state(dst, src);
851 if (err)
852 return err;
638f5b90
AS
853 return 0;
854}
855
f4d7e40a
AS
856static void free_func_state(struct bpf_func_state *state)
857{
5896351e
AS
858 if (!state)
859 return;
fd978bf7 860 kfree(state->refs);
f4d7e40a
AS
861 kfree(state->stack);
862 kfree(state);
863}
864
b5dc0163
AS
865static void clear_jmp_history(struct bpf_verifier_state *state)
866{
867 kfree(state->jmp_history);
868 state->jmp_history = NULL;
869 state->jmp_history_cnt = 0;
870}
871
1969db47
AS
872static void free_verifier_state(struct bpf_verifier_state *state,
873 bool free_self)
638f5b90 874{
f4d7e40a
AS
875 int i;
876
877 for (i = 0; i <= state->curframe; i++) {
878 free_func_state(state->frame[i]);
879 state->frame[i] = NULL;
880 }
b5dc0163 881 clear_jmp_history(state);
1969db47
AS
882 if (free_self)
883 kfree(state);
638f5b90
AS
884}
885
886/* copy verifier state from src to dst growing dst stack space
887 * when necessary to accommodate larger src stack
888 */
f4d7e40a
AS
889static int copy_func_state(struct bpf_func_state *dst,
890 const struct bpf_func_state *src)
638f5b90
AS
891{
892 int err;
893
fd978bf7
JS
894 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
895 false);
896 if (err)
897 return err;
898 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
899 err = copy_reference_state(dst, src);
638f5b90
AS
900 if (err)
901 return err;
638f5b90
AS
902 return copy_stack_state(dst, src);
903}
904
f4d7e40a
AS
905static int copy_verifier_state(struct bpf_verifier_state *dst_state,
906 const struct bpf_verifier_state *src)
907{
908 struct bpf_func_state *dst;
b5dc0163 909 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
910 int i, err;
911
b5dc0163
AS
912 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
913 kfree(dst_state->jmp_history);
914 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
915 if (!dst_state->jmp_history)
916 return -ENOMEM;
917 }
918 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
919 dst_state->jmp_history_cnt = src->jmp_history_cnt;
920
f4d7e40a
AS
921 /* if dst has more stack frames then src frame, free them */
922 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
923 free_func_state(dst_state->frame[i]);
924 dst_state->frame[i] = NULL;
925 }
979d63d5 926 dst_state->speculative = src->speculative;
f4d7e40a 927 dst_state->curframe = src->curframe;
d83525ca 928 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
929 dst_state->branches = src->branches;
930 dst_state->parent = src->parent;
b5dc0163
AS
931 dst_state->first_insn_idx = src->first_insn_idx;
932 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
933 for (i = 0; i <= src->curframe; i++) {
934 dst = dst_state->frame[i];
935 if (!dst) {
936 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
937 if (!dst)
938 return -ENOMEM;
939 dst_state->frame[i] = dst;
940 }
941 err = copy_func_state(dst, src->frame[i]);
942 if (err)
943 return err;
944 }
945 return 0;
946}
947
2589726d
AS
948static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
949{
950 while (st) {
951 u32 br = --st->branches;
952
953 /* WARN_ON(br > 1) technically makes sense here,
954 * but see comment in push_stack(), hence:
955 */
956 WARN_ONCE((int)br < 0,
957 "BUG update_branch_counts:branches_to_explore=%d\n",
958 br);
959 if (br)
960 break;
961 st = st->parent;
962 }
963}
964
638f5b90 965static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 966 int *insn_idx, bool pop_log)
638f5b90
AS
967{
968 struct bpf_verifier_state *cur = env->cur_state;
969 struct bpf_verifier_stack_elem *elem, *head = env->head;
970 int err;
17a52670
AS
971
972 if (env->head == NULL)
638f5b90 973 return -ENOENT;
17a52670 974
638f5b90
AS
975 if (cur) {
976 err = copy_verifier_state(cur, &head->st);
977 if (err)
978 return err;
979 }
6f8a57cc
AN
980 if (pop_log)
981 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
982 if (insn_idx)
983 *insn_idx = head->insn_idx;
17a52670 984 if (prev_insn_idx)
638f5b90
AS
985 *prev_insn_idx = head->prev_insn_idx;
986 elem = head->next;
1969db47 987 free_verifier_state(&head->st, false);
638f5b90 988 kfree(head);
17a52670
AS
989 env->head = elem;
990 env->stack_size--;
638f5b90 991 return 0;
17a52670
AS
992}
993
58e2af8b 994static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
995 int insn_idx, int prev_insn_idx,
996 bool speculative)
17a52670 997{
638f5b90 998 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 999 struct bpf_verifier_stack_elem *elem;
638f5b90 1000 int err;
17a52670 1001
638f5b90 1002 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1003 if (!elem)
1004 goto err;
1005
17a52670
AS
1006 elem->insn_idx = insn_idx;
1007 elem->prev_insn_idx = prev_insn_idx;
1008 elem->next = env->head;
6f8a57cc 1009 elem->log_pos = env->log.len_used;
17a52670
AS
1010 env->head = elem;
1011 env->stack_size++;
1969db47
AS
1012 err = copy_verifier_state(&elem->st, cur);
1013 if (err)
1014 goto err;
979d63d5 1015 elem->st.speculative |= speculative;
b285fcb7
AS
1016 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1017 verbose(env, "The sequence of %d jumps is too complex.\n",
1018 env->stack_size);
17a52670
AS
1019 goto err;
1020 }
2589726d
AS
1021 if (elem->st.parent) {
1022 ++elem->st.parent->branches;
1023 /* WARN_ON(branches > 2) technically makes sense here,
1024 * but
1025 * 1. speculative states will bump 'branches' for non-branch
1026 * instructions
1027 * 2. is_state_visited() heuristics may decide not to create
1028 * a new state for a sequence of branches and all such current
1029 * and cloned states will be pointing to a single parent state
1030 * which might have large 'branches' count.
1031 */
1032 }
17a52670
AS
1033 return &elem->st;
1034err:
5896351e
AS
1035 free_verifier_state(env->cur_state, true);
1036 env->cur_state = NULL;
17a52670 1037 /* pop all elements and return */
6f8a57cc 1038 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1039 return NULL;
1040}
1041
1042#define CALLER_SAVED_REGS 6
1043static const int caller_saved[CALLER_SAVED_REGS] = {
1044 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1045};
1046
f54c7898
DB
1047static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1048 struct bpf_reg_state *reg);
f1174f77 1049
e688c3db
AS
1050/* This helper doesn't clear reg->id */
1051static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1052{
b03c9f9f
EC
1053 reg->var_off = tnum_const(imm);
1054 reg->smin_value = (s64)imm;
1055 reg->smax_value = (s64)imm;
1056 reg->umin_value = imm;
1057 reg->umax_value = imm;
3f50f132
JF
1058
1059 reg->s32_min_value = (s32)imm;
1060 reg->s32_max_value = (s32)imm;
1061 reg->u32_min_value = (u32)imm;
1062 reg->u32_max_value = (u32)imm;
1063}
1064
e688c3db
AS
1065/* Mark the unknown part of a register (variable offset or scalar value) as
1066 * known to have the value @imm.
1067 */
1068static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1069{
1070 /* Clear id, off, and union(map_ptr, range) */
1071 memset(((u8 *)reg) + sizeof(reg->type), 0,
1072 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1073 ___mark_reg_known(reg, imm);
1074}
1075
3f50f132
JF
1076static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1077{
1078 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1079 reg->s32_min_value = (s32)imm;
1080 reg->s32_max_value = (s32)imm;
1081 reg->u32_min_value = (u32)imm;
1082 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1083}
1084
f1174f77
EC
1085/* Mark the 'variable offset' part of a register as zero. This should be
1086 * used only on registers holding a pointer type.
1087 */
1088static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1089{
b03c9f9f 1090 __mark_reg_known(reg, 0);
f1174f77 1091}
a9789ef9 1092
cc2b14d5
AS
1093static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1094{
1095 __mark_reg_known(reg, 0);
cc2b14d5
AS
1096 reg->type = SCALAR_VALUE;
1097}
1098
61bd5218
JK
1099static void mark_reg_known_zero(struct bpf_verifier_env *env,
1100 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1101{
1102 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1103 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1104 /* Something bad happened, let's kill all regs */
1105 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1106 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1107 return;
1108 }
1109 __mark_reg_known_zero(regs + regno);
1110}
1111
4ddb7416
DB
1112static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1113{
1114 switch (reg->type) {
1115 case PTR_TO_MAP_VALUE_OR_NULL: {
1116 const struct bpf_map *map = reg->map_ptr;
1117
1118 if (map->inner_map_meta) {
1119 reg->type = CONST_PTR_TO_MAP;
1120 reg->map_ptr = map->inner_map_meta;
1121 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1122 reg->type = PTR_TO_XDP_SOCK;
1123 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1124 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1125 reg->type = PTR_TO_SOCKET;
1126 } else {
1127 reg->type = PTR_TO_MAP_VALUE;
1128 }
1129 break;
1130 }
1131 case PTR_TO_SOCKET_OR_NULL:
1132 reg->type = PTR_TO_SOCKET;
1133 break;
1134 case PTR_TO_SOCK_COMMON_OR_NULL:
1135 reg->type = PTR_TO_SOCK_COMMON;
1136 break;
1137 case PTR_TO_TCP_SOCK_OR_NULL:
1138 reg->type = PTR_TO_TCP_SOCK;
1139 break;
1140 case PTR_TO_BTF_ID_OR_NULL:
1141 reg->type = PTR_TO_BTF_ID;
1142 break;
1143 case PTR_TO_MEM_OR_NULL:
1144 reg->type = PTR_TO_MEM;
1145 break;
1146 case PTR_TO_RDONLY_BUF_OR_NULL:
1147 reg->type = PTR_TO_RDONLY_BUF;
1148 break;
1149 case PTR_TO_RDWR_BUF_OR_NULL:
1150 reg->type = PTR_TO_RDWR_BUF;
1151 break;
1152 default:
1153 WARN_ON("unknown nullable register type");
1154 }
1155}
1156
de8f3a83
DB
1157static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1158{
1159 return type_is_pkt_pointer(reg->type);
1160}
1161
1162static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1163{
1164 return reg_is_pkt_pointer(reg) ||
1165 reg->type == PTR_TO_PACKET_END;
1166}
1167
1168/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1169static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1170 enum bpf_reg_type which)
1171{
1172 /* The register can already have a range from prior markings.
1173 * This is fine as long as it hasn't been advanced from its
1174 * origin.
1175 */
1176 return reg->type == which &&
1177 reg->id == 0 &&
1178 reg->off == 0 &&
1179 tnum_equals_const(reg->var_off, 0);
1180}
1181
3f50f132
JF
1182/* Reset the min/max bounds of a register */
1183static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1184{
1185 reg->smin_value = S64_MIN;
1186 reg->smax_value = S64_MAX;
1187 reg->umin_value = 0;
1188 reg->umax_value = U64_MAX;
1189
1190 reg->s32_min_value = S32_MIN;
1191 reg->s32_max_value = S32_MAX;
1192 reg->u32_min_value = 0;
1193 reg->u32_max_value = U32_MAX;
1194}
1195
1196static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1197{
1198 reg->smin_value = S64_MIN;
1199 reg->smax_value = S64_MAX;
1200 reg->umin_value = 0;
1201 reg->umax_value = U64_MAX;
1202}
1203
1204static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1205{
1206 reg->s32_min_value = S32_MIN;
1207 reg->s32_max_value = S32_MAX;
1208 reg->u32_min_value = 0;
1209 reg->u32_max_value = U32_MAX;
1210}
1211
1212static void __update_reg32_bounds(struct bpf_reg_state *reg)
1213{
1214 struct tnum var32_off = tnum_subreg(reg->var_off);
1215
1216 /* min signed is max(sign bit) | min(other bits) */
1217 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1218 var32_off.value | (var32_off.mask & S32_MIN));
1219 /* max signed is min(sign bit) | max(other bits) */
1220 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1221 var32_off.value | (var32_off.mask & S32_MAX));
1222 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1223 reg->u32_max_value = min(reg->u32_max_value,
1224 (u32)(var32_off.value | var32_off.mask));
1225}
1226
1227static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1228{
1229 /* min signed is max(sign bit) | min(other bits) */
1230 reg->smin_value = max_t(s64, reg->smin_value,
1231 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1232 /* max signed is min(sign bit) | max(other bits) */
1233 reg->smax_value = min_t(s64, reg->smax_value,
1234 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1235 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1236 reg->umax_value = min(reg->umax_value,
1237 reg->var_off.value | reg->var_off.mask);
1238}
1239
3f50f132
JF
1240static void __update_reg_bounds(struct bpf_reg_state *reg)
1241{
1242 __update_reg32_bounds(reg);
1243 __update_reg64_bounds(reg);
1244}
1245
b03c9f9f 1246/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1247static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1248{
1249 /* Learn sign from signed bounds.
1250 * If we cannot cross the sign boundary, then signed and unsigned bounds
1251 * are the same, so combine. This works even in the negative case, e.g.
1252 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1253 */
1254 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1255 reg->s32_min_value = reg->u32_min_value =
1256 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1257 reg->s32_max_value = reg->u32_max_value =
1258 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1259 return;
1260 }
1261 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1262 * boundary, so we must be careful.
1263 */
1264 if ((s32)reg->u32_max_value >= 0) {
1265 /* Positive. We can't learn anything from the smin, but smax
1266 * is positive, hence safe.
1267 */
1268 reg->s32_min_value = reg->u32_min_value;
1269 reg->s32_max_value = reg->u32_max_value =
1270 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1271 } else if ((s32)reg->u32_min_value < 0) {
1272 /* Negative. We can't learn anything from the smax, but smin
1273 * is negative, hence safe.
1274 */
1275 reg->s32_min_value = reg->u32_min_value =
1276 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1277 reg->s32_max_value = reg->u32_max_value;
1278 }
1279}
1280
1281static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1282{
1283 /* Learn sign from signed bounds.
1284 * If we cannot cross the sign boundary, then signed and unsigned bounds
1285 * are the same, so combine. This works even in the negative case, e.g.
1286 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1287 */
1288 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1289 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1290 reg->umin_value);
1291 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1292 reg->umax_value);
1293 return;
1294 }
1295 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1296 * boundary, so we must be careful.
1297 */
1298 if ((s64)reg->umax_value >= 0) {
1299 /* Positive. We can't learn anything from the smin, but smax
1300 * is positive, hence safe.
1301 */
1302 reg->smin_value = reg->umin_value;
1303 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1304 reg->umax_value);
1305 } else if ((s64)reg->umin_value < 0) {
1306 /* Negative. We can't learn anything from the smax, but smin
1307 * is negative, hence safe.
1308 */
1309 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1310 reg->umin_value);
1311 reg->smax_value = reg->umax_value;
1312 }
1313}
1314
3f50f132
JF
1315static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1316{
1317 __reg32_deduce_bounds(reg);
1318 __reg64_deduce_bounds(reg);
1319}
1320
b03c9f9f
EC
1321/* Attempts to improve var_off based on unsigned min/max information */
1322static void __reg_bound_offset(struct bpf_reg_state *reg)
1323{
3f50f132
JF
1324 struct tnum var64_off = tnum_intersect(reg->var_off,
1325 tnum_range(reg->umin_value,
1326 reg->umax_value));
1327 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1328 tnum_range(reg->u32_min_value,
1329 reg->u32_max_value));
1330
1331 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1332}
1333
3f50f132 1334static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1335{
3f50f132
JF
1336 reg->umin_value = reg->u32_min_value;
1337 reg->umax_value = reg->u32_max_value;
1338 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1339 * but must be positive otherwise set to worse case bounds
1340 * and refine later from tnum.
1341 */
3a71dc36 1342 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1343 reg->smax_value = reg->s32_max_value;
1344 else
1345 reg->smax_value = U32_MAX;
3a71dc36
JF
1346 if (reg->s32_min_value >= 0)
1347 reg->smin_value = reg->s32_min_value;
1348 else
1349 reg->smin_value = 0;
3f50f132
JF
1350}
1351
1352static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1353{
1354 /* special case when 64-bit register has upper 32-bit register
1355 * zeroed. Typically happens after zext or <<32, >>32 sequence
1356 * allowing us to use 32-bit bounds directly,
1357 */
1358 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1359 __reg_assign_32_into_64(reg);
1360 } else {
1361 /* Otherwise the best we can do is push lower 32bit known and
1362 * unknown bits into register (var_off set from jmp logic)
1363 * then learn as much as possible from the 64-bit tnum
1364 * known and unknown bits. The previous smin/smax bounds are
1365 * invalid here because of jmp32 compare so mark them unknown
1366 * so they do not impact tnum bounds calculation.
1367 */
1368 __mark_reg64_unbounded(reg);
1369 __update_reg_bounds(reg);
1370 }
1371
1372 /* Intersecting with the old var_off might have improved our bounds
1373 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1374 * then new var_off is (0; 0x7f...fc) which improves our umax.
1375 */
1376 __reg_deduce_bounds(reg);
1377 __reg_bound_offset(reg);
1378 __update_reg_bounds(reg);
1379}
1380
1381static bool __reg64_bound_s32(s64 a)
1382{
b0270958 1383 return a > S32_MIN && a < S32_MAX;
3f50f132
JF
1384}
1385
1386static bool __reg64_bound_u32(u64 a)
1387{
1388 if (a > U32_MIN && a < U32_MAX)
1389 return true;
1390 return false;
1391}
1392
1393static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1394{
1395 __mark_reg32_unbounded(reg);
1396
b0270958 1397 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1398 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1399 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1400 }
3f50f132
JF
1401 if (__reg64_bound_u32(reg->umin_value))
1402 reg->u32_min_value = (u32)reg->umin_value;
1403 if (__reg64_bound_u32(reg->umax_value))
1404 reg->u32_max_value = (u32)reg->umax_value;
1405
1406 /* Intersecting with the old var_off might have improved our bounds
1407 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1408 * then new var_off is (0; 0x7f...fc) which improves our umax.
1409 */
1410 __reg_deduce_bounds(reg);
1411 __reg_bound_offset(reg);
1412 __update_reg_bounds(reg);
b03c9f9f
EC
1413}
1414
f1174f77 1415/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1416static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1417 struct bpf_reg_state *reg)
f1174f77 1418{
a9c676bc
AS
1419 /*
1420 * Clear type, id, off, and union(map_ptr, range) and
1421 * padding between 'type' and union
1422 */
1423 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1424 reg->type = SCALAR_VALUE;
f1174f77 1425 reg->var_off = tnum_unknown;
f4d7e40a 1426 reg->frameno = 0;
2c78ee89 1427 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1428 __mark_reg_unbounded(reg);
f1174f77
EC
1429}
1430
61bd5218
JK
1431static void mark_reg_unknown(struct bpf_verifier_env *env,
1432 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1433{
1434 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1435 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1436 /* Something bad happened, let's kill all regs except FP */
1437 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1438 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1439 return;
1440 }
f54c7898 1441 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1442}
1443
f54c7898
DB
1444static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1445 struct bpf_reg_state *reg)
f1174f77 1446{
f54c7898 1447 __mark_reg_unknown(env, reg);
f1174f77
EC
1448 reg->type = NOT_INIT;
1449}
1450
61bd5218
JK
1451static void mark_reg_not_init(struct bpf_verifier_env *env,
1452 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1453{
1454 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1455 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1456 /* Something bad happened, let's kill all regs except FP */
1457 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1458 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1459 return;
1460 }
f54c7898 1461 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1462}
1463
41c48f3a
AI
1464static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1465 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1466 enum bpf_reg_type reg_type,
1467 struct btf *btf, u32 btf_id)
41c48f3a
AI
1468{
1469 if (reg_type == SCALAR_VALUE) {
1470 mark_reg_unknown(env, regs, regno);
1471 return;
1472 }
1473 mark_reg_known_zero(env, regs, regno);
1474 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1475 regs[regno].btf = btf;
41c48f3a
AI
1476 regs[regno].btf_id = btf_id;
1477}
1478
5327ed3d 1479#define DEF_NOT_SUBREG (0)
61bd5218 1480static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1481 struct bpf_func_state *state)
17a52670 1482{
f4d7e40a 1483 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1484 int i;
1485
dc503a8a 1486 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1487 mark_reg_not_init(env, regs, i);
dc503a8a 1488 regs[i].live = REG_LIVE_NONE;
679c782d 1489 regs[i].parent = NULL;
5327ed3d 1490 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1491 }
17a52670
AS
1492
1493 /* frame pointer */
f1174f77 1494 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1495 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1496 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1497}
1498
f4d7e40a
AS
1499#define BPF_MAIN_FUNC (-1)
1500static void init_func_state(struct bpf_verifier_env *env,
1501 struct bpf_func_state *state,
1502 int callsite, int frameno, int subprogno)
1503{
1504 state->callsite = callsite;
1505 state->frameno = frameno;
1506 state->subprogno = subprogno;
1507 init_reg_state(env, state);
1508}
1509
17a52670
AS
1510enum reg_arg_type {
1511 SRC_OP, /* register is used as source operand */
1512 DST_OP, /* register is used as destination operand */
1513 DST_OP_NO_MARK /* same as above, check only, don't mark */
1514};
1515
cc8b0b92
AS
1516static int cmp_subprogs(const void *a, const void *b)
1517{
9c8105bd
JW
1518 return ((struct bpf_subprog_info *)a)->start -
1519 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1520}
1521
1522static int find_subprog(struct bpf_verifier_env *env, int off)
1523{
9c8105bd 1524 struct bpf_subprog_info *p;
cc8b0b92 1525
9c8105bd
JW
1526 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1527 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1528 if (!p)
1529 return -ENOENT;
9c8105bd 1530 return p - env->subprog_info;
cc8b0b92
AS
1531
1532}
1533
1534static int add_subprog(struct bpf_verifier_env *env, int off)
1535{
1536 int insn_cnt = env->prog->len;
1537 int ret;
1538
1539 if (off >= insn_cnt || off < 0) {
1540 verbose(env, "call to invalid destination\n");
1541 return -EINVAL;
1542 }
1543 ret = find_subprog(env, off);
1544 if (ret >= 0)
282a0f46 1545 return ret;
4cb3d99c 1546 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1547 verbose(env, "too many subprograms\n");
1548 return -E2BIG;
1549 }
9c8105bd
JW
1550 env->subprog_info[env->subprog_cnt++].start = off;
1551 sort(env->subprog_info, env->subprog_cnt,
1552 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1553 return env->subprog_cnt - 1;
cc8b0b92
AS
1554}
1555
1556static int check_subprogs(struct bpf_verifier_env *env)
1557{
1558 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1559 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1560 struct bpf_insn *insn = env->prog->insnsi;
1561 int insn_cnt = env->prog->len;
1562
f910cefa
JW
1563 /* Add entry function. */
1564 ret = add_subprog(env, 0);
1565 if (ret < 0)
1566 return ret;
1567
cc8b0b92
AS
1568 /* determine subprog starts. The end is one before the next starts */
1569 for (i = 0; i < insn_cnt; i++) {
69c087ba
YS
1570 if (bpf_pseudo_func(insn + i)) {
1571 if (!env->bpf_capable) {
1572 verbose(env,
1573 "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1574 return -EPERM;
1575 }
1576 ret = add_subprog(env, i + insn[i].imm + 1);
1577 if (ret < 0)
1578 return ret;
1579 /* remember subprog */
1580 insn[i + 1].imm = ret;
1581 continue;
1582 }
23a2d70c 1583 if (!bpf_pseudo_call(insn + i))
cc8b0b92 1584 continue;
2c78ee89
AS
1585 if (!env->bpf_capable) {
1586 verbose(env,
1587 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1588 return -EPERM;
1589 }
cc8b0b92
AS
1590 ret = add_subprog(env, i + insn[i].imm + 1);
1591 if (ret < 0)
1592 return ret;
1593 }
1594
4cb3d99c
JW
1595 /* Add a fake 'exit' subprog which could simplify subprog iteration
1596 * logic. 'subprog_cnt' should not be increased.
1597 */
1598 subprog[env->subprog_cnt].start = insn_cnt;
1599
06ee7115 1600 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1601 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1602 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1603
1604 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1605 subprog_start = subprog[cur_subprog].start;
1606 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1607 for (i = 0; i < insn_cnt; i++) {
1608 u8 code = insn[i].code;
1609
7f6e4312
MF
1610 if (code == (BPF_JMP | BPF_CALL) &&
1611 insn[i].imm == BPF_FUNC_tail_call &&
1612 insn[i].src_reg != BPF_PSEUDO_CALL)
1613 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1614 if (BPF_CLASS(code) == BPF_LD &&
1615 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1616 subprog[cur_subprog].has_ld_abs = true;
092ed096 1617 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1618 goto next;
1619 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1620 goto next;
1621 off = i + insn[i].off + 1;
1622 if (off < subprog_start || off >= subprog_end) {
1623 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1624 return -EINVAL;
1625 }
1626next:
1627 if (i == subprog_end - 1) {
1628 /* to avoid fall-through from one subprog into another
1629 * the last insn of the subprog should be either exit
1630 * or unconditional jump back
1631 */
1632 if (code != (BPF_JMP | BPF_EXIT) &&
1633 code != (BPF_JMP | BPF_JA)) {
1634 verbose(env, "last insn is not an exit or jmp\n");
1635 return -EINVAL;
1636 }
1637 subprog_start = subprog_end;
4cb3d99c
JW
1638 cur_subprog++;
1639 if (cur_subprog < env->subprog_cnt)
9c8105bd 1640 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1641 }
1642 }
1643 return 0;
1644}
1645
679c782d
EC
1646/* Parentage chain of this register (or stack slot) should take care of all
1647 * issues like callee-saved registers, stack slot allocation time, etc.
1648 */
f4d7e40a 1649static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1650 const struct bpf_reg_state *state,
5327ed3d 1651 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1652{
1653 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1654 int cnt = 0;
dc503a8a
EC
1655
1656 while (parent) {
1657 /* if read wasn't screened by an earlier write ... */
679c782d 1658 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1659 break;
9242b5f5
AS
1660 if (parent->live & REG_LIVE_DONE) {
1661 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1662 reg_type_str[parent->type],
1663 parent->var_off.value, parent->off);
1664 return -EFAULT;
1665 }
5327ed3d
JW
1666 /* The first condition is more likely to be true than the
1667 * second, checked it first.
1668 */
1669 if ((parent->live & REG_LIVE_READ) == flag ||
1670 parent->live & REG_LIVE_READ64)
25af32da
AS
1671 /* The parentage chain never changes and
1672 * this parent was already marked as LIVE_READ.
1673 * There is no need to keep walking the chain again and
1674 * keep re-marking all parents as LIVE_READ.
1675 * This case happens when the same register is read
1676 * multiple times without writes into it in-between.
5327ed3d
JW
1677 * Also, if parent has the stronger REG_LIVE_READ64 set,
1678 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1679 */
1680 break;
dc503a8a 1681 /* ... then we depend on parent's value */
5327ed3d
JW
1682 parent->live |= flag;
1683 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1684 if (flag == REG_LIVE_READ64)
1685 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1686 state = parent;
1687 parent = state->parent;
f4d7e40a 1688 writes = true;
06ee7115 1689 cnt++;
dc503a8a 1690 }
06ee7115
AS
1691
1692 if (env->longest_mark_read_walk < cnt)
1693 env->longest_mark_read_walk = cnt;
f4d7e40a 1694 return 0;
dc503a8a
EC
1695}
1696
5327ed3d
JW
1697/* This function is supposed to be used by the following 32-bit optimization
1698 * code only. It returns TRUE if the source or destination register operates
1699 * on 64-bit, otherwise return FALSE.
1700 */
1701static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1702 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1703{
1704 u8 code, class, op;
1705
1706 code = insn->code;
1707 class = BPF_CLASS(code);
1708 op = BPF_OP(code);
1709 if (class == BPF_JMP) {
1710 /* BPF_EXIT for "main" will reach here. Return TRUE
1711 * conservatively.
1712 */
1713 if (op == BPF_EXIT)
1714 return true;
1715 if (op == BPF_CALL) {
1716 /* BPF to BPF call will reach here because of marking
1717 * caller saved clobber with DST_OP_NO_MARK for which we
1718 * don't care the register def because they are anyway
1719 * marked as NOT_INIT already.
1720 */
1721 if (insn->src_reg == BPF_PSEUDO_CALL)
1722 return false;
1723 /* Helper call will reach here because of arg type
1724 * check, conservatively return TRUE.
1725 */
1726 if (t == SRC_OP)
1727 return true;
1728
1729 return false;
1730 }
1731 }
1732
1733 if (class == BPF_ALU64 || class == BPF_JMP ||
1734 /* BPF_END always use BPF_ALU class. */
1735 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1736 return true;
1737
1738 if (class == BPF_ALU || class == BPF_JMP32)
1739 return false;
1740
1741 if (class == BPF_LDX) {
1742 if (t != SRC_OP)
1743 return BPF_SIZE(code) == BPF_DW;
1744 /* LDX source must be ptr. */
1745 return true;
1746 }
1747
1748 if (class == BPF_STX) {
1749 if (reg->type != SCALAR_VALUE)
1750 return true;
1751 return BPF_SIZE(code) == BPF_DW;
1752 }
1753
1754 if (class == BPF_LD) {
1755 u8 mode = BPF_MODE(code);
1756
1757 /* LD_IMM64 */
1758 if (mode == BPF_IMM)
1759 return true;
1760
1761 /* Both LD_IND and LD_ABS return 32-bit data. */
1762 if (t != SRC_OP)
1763 return false;
1764
1765 /* Implicit ctx ptr. */
1766 if (regno == BPF_REG_6)
1767 return true;
1768
1769 /* Explicit source could be any width. */
1770 return true;
1771 }
1772
1773 if (class == BPF_ST)
1774 /* The only source register for BPF_ST is a ptr. */
1775 return true;
1776
1777 /* Conservatively return true at default. */
1778 return true;
1779}
1780
b325fbca
JW
1781/* Return TRUE if INSN doesn't have explicit value define. */
1782static bool insn_no_def(struct bpf_insn *insn)
1783{
1784 u8 class = BPF_CLASS(insn->code);
1785
1786 return (class == BPF_JMP || class == BPF_JMP32 ||
1787 class == BPF_STX || class == BPF_ST);
1788}
1789
1790/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1791static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1792{
1793 if (insn_no_def(insn))
1794 return false;
1795
1796 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1797}
1798
5327ed3d
JW
1799static void mark_insn_zext(struct bpf_verifier_env *env,
1800 struct bpf_reg_state *reg)
1801{
1802 s32 def_idx = reg->subreg_def;
1803
1804 if (def_idx == DEF_NOT_SUBREG)
1805 return;
1806
1807 env->insn_aux_data[def_idx - 1].zext_dst = true;
1808 /* The dst will be zero extended, so won't be sub-register anymore. */
1809 reg->subreg_def = DEF_NOT_SUBREG;
1810}
1811
dc503a8a 1812static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1813 enum reg_arg_type t)
1814{
f4d7e40a
AS
1815 struct bpf_verifier_state *vstate = env->cur_state;
1816 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1817 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1818 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1819 bool rw64;
dc503a8a 1820
17a52670 1821 if (regno >= MAX_BPF_REG) {
61bd5218 1822 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1823 return -EINVAL;
1824 }
1825
c342dc10 1826 reg = &regs[regno];
5327ed3d 1827 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1828 if (t == SRC_OP) {
1829 /* check whether register used as source operand can be read */
c342dc10 1830 if (reg->type == NOT_INIT) {
61bd5218 1831 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1832 return -EACCES;
1833 }
679c782d 1834 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1835 if (regno == BPF_REG_FP)
1836 return 0;
1837
5327ed3d
JW
1838 if (rw64)
1839 mark_insn_zext(env, reg);
1840
1841 return mark_reg_read(env, reg, reg->parent,
1842 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1843 } else {
1844 /* check whether register used as dest operand can be written to */
1845 if (regno == BPF_REG_FP) {
61bd5218 1846 verbose(env, "frame pointer is read only\n");
17a52670
AS
1847 return -EACCES;
1848 }
c342dc10 1849 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1850 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1851 if (t == DST_OP)
61bd5218 1852 mark_reg_unknown(env, regs, regno);
17a52670
AS
1853 }
1854 return 0;
1855}
1856
b5dc0163
AS
1857/* for any branch, call, exit record the history of jmps in the given state */
1858static int push_jmp_history(struct bpf_verifier_env *env,
1859 struct bpf_verifier_state *cur)
1860{
1861 u32 cnt = cur->jmp_history_cnt;
1862 struct bpf_idx_pair *p;
1863
1864 cnt++;
1865 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1866 if (!p)
1867 return -ENOMEM;
1868 p[cnt - 1].idx = env->insn_idx;
1869 p[cnt - 1].prev_idx = env->prev_insn_idx;
1870 cur->jmp_history = p;
1871 cur->jmp_history_cnt = cnt;
1872 return 0;
1873}
1874
1875/* Backtrack one insn at a time. If idx is not at the top of recorded
1876 * history then previous instruction came from straight line execution.
1877 */
1878static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1879 u32 *history)
1880{
1881 u32 cnt = *history;
1882
1883 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1884 i = st->jmp_history[cnt - 1].prev_idx;
1885 (*history)--;
1886 } else {
1887 i--;
1888 }
1889 return i;
1890}
1891
1892/* For given verifier state backtrack_insn() is called from the last insn to
1893 * the first insn. Its purpose is to compute a bitmask of registers and
1894 * stack slots that needs precision in the parent verifier state.
1895 */
1896static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1897 u32 *reg_mask, u64 *stack_mask)
1898{
1899 const struct bpf_insn_cbs cbs = {
1900 .cb_print = verbose,
1901 .private_data = env,
1902 };
1903 struct bpf_insn *insn = env->prog->insnsi + idx;
1904 u8 class = BPF_CLASS(insn->code);
1905 u8 opcode = BPF_OP(insn->code);
1906 u8 mode = BPF_MODE(insn->code);
1907 u32 dreg = 1u << insn->dst_reg;
1908 u32 sreg = 1u << insn->src_reg;
1909 u32 spi;
1910
1911 if (insn->code == 0)
1912 return 0;
1913 if (env->log.level & BPF_LOG_LEVEL) {
1914 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1915 verbose(env, "%d: ", idx);
1916 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1917 }
1918
1919 if (class == BPF_ALU || class == BPF_ALU64) {
1920 if (!(*reg_mask & dreg))
1921 return 0;
1922 if (opcode == BPF_MOV) {
1923 if (BPF_SRC(insn->code) == BPF_X) {
1924 /* dreg = sreg
1925 * dreg needs precision after this insn
1926 * sreg needs precision before this insn
1927 */
1928 *reg_mask &= ~dreg;
1929 *reg_mask |= sreg;
1930 } else {
1931 /* dreg = K
1932 * dreg needs precision after this insn.
1933 * Corresponding register is already marked
1934 * as precise=true in this verifier state.
1935 * No further markings in parent are necessary
1936 */
1937 *reg_mask &= ~dreg;
1938 }
1939 } else {
1940 if (BPF_SRC(insn->code) == BPF_X) {
1941 /* dreg += sreg
1942 * both dreg and sreg need precision
1943 * before this insn
1944 */
1945 *reg_mask |= sreg;
1946 } /* else dreg += K
1947 * dreg still needs precision before this insn
1948 */
1949 }
1950 } else if (class == BPF_LDX) {
1951 if (!(*reg_mask & dreg))
1952 return 0;
1953 *reg_mask &= ~dreg;
1954
1955 /* scalars can only be spilled into stack w/o losing precision.
1956 * Load from any other memory can be zero extended.
1957 * The desire to keep that precision is already indicated
1958 * by 'precise' mark in corresponding register of this state.
1959 * No further tracking necessary.
1960 */
1961 if (insn->src_reg != BPF_REG_FP)
1962 return 0;
1963 if (BPF_SIZE(insn->code) != BPF_DW)
1964 return 0;
1965
1966 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1967 * that [fp - off] slot contains scalar that needs to be
1968 * tracked with precision
1969 */
1970 spi = (-insn->off - 1) / BPF_REG_SIZE;
1971 if (spi >= 64) {
1972 verbose(env, "BUG spi %d\n", spi);
1973 WARN_ONCE(1, "verifier backtracking bug");
1974 return -EFAULT;
1975 }
1976 *stack_mask |= 1ull << spi;
b3b50f05 1977 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 1978 if (*reg_mask & dreg)
b3b50f05 1979 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
1980 * to access memory. It means backtracking
1981 * encountered a case of pointer subtraction.
1982 */
1983 return -ENOTSUPP;
1984 /* scalars can only be spilled into stack */
1985 if (insn->dst_reg != BPF_REG_FP)
1986 return 0;
1987 if (BPF_SIZE(insn->code) != BPF_DW)
1988 return 0;
1989 spi = (-insn->off - 1) / BPF_REG_SIZE;
1990 if (spi >= 64) {
1991 verbose(env, "BUG spi %d\n", spi);
1992 WARN_ONCE(1, "verifier backtracking bug");
1993 return -EFAULT;
1994 }
1995 if (!(*stack_mask & (1ull << spi)))
1996 return 0;
1997 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
1998 if (class == BPF_STX)
1999 *reg_mask |= sreg;
b5dc0163
AS
2000 } else if (class == BPF_JMP || class == BPF_JMP32) {
2001 if (opcode == BPF_CALL) {
2002 if (insn->src_reg == BPF_PSEUDO_CALL)
2003 return -ENOTSUPP;
2004 /* regular helper call sets R0 */
2005 *reg_mask &= ~1;
2006 if (*reg_mask & 0x3f) {
2007 /* if backtracing was looking for registers R1-R5
2008 * they should have been found already.
2009 */
2010 verbose(env, "BUG regs %x\n", *reg_mask);
2011 WARN_ONCE(1, "verifier backtracking bug");
2012 return -EFAULT;
2013 }
2014 } else if (opcode == BPF_EXIT) {
2015 return -ENOTSUPP;
2016 }
2017 } else if (class == BPF_LD) {
2018 if (!(*reg_mask & dreg))
2019 return 0;
2020 *reg_mask &= ~dreg;
2021 /* It's ld_imm64 or ld_abs or ld_ind.
2022 * For ld_imm64 no further tracking of precision
2023 * into parent is necessary
2024 */
2025 if (mode == BPF_IND || mode == BPF_ABS)
2026 /* to be analyzed */
2027 return -ENOTSUPP;
b5dc0163
AS
2028 }
2029 return 0;
2030}
2031
2032/* the scalar precision tracking algorithm:
2033 * . at the start all registers have precise=false.
2034 * . scalar ranges are tracked as normal through alu and jmp insns.
2035 * . once precise value of the scalar register is used in:
2036 * . ptr + scalar alu
2037 * . if (scalar cond K|scalar)
2038 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2039 * backtrack through the verifier states and mark all registers and
2040 * stack slots with spilled constants that these scalar regisers
2041 * should be precise.
2042 * . during state pruning two registers (or spilled stack slots)
2043 * are equivalent if both are not precise.
2044 *
2045 * Note the verifier cannot simply walk register parentage chain,
2046 * since many different registers and stack slots could have been
2047 * used to compute single precise scalar.
2048 *
2049 * The approach of starting with precise=true for all registers and then
2050 * backtrack to mark a register as not precise when the verifier detects
2051 * that program doesn't care about specific value (e.g., when helper
2052 * takes register as ARG_ANYTHING parameter) is not safe.
2053 *
2054 * It's ok to walk single parentage chain of the verifier states.
2055 * It's possible that this backtracking will go all the way till 1st insn.
2056 * All other branches will be explored for needing precision later.
2057 *
2058 * The backtracking needs to deal with cases like:
2059 * 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)
2060 * r9 -= r8
2061 * r5 = r9
2062 * if r5 > 0x79f goto pc+7
2063 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2064 * r5 += 1
2065 * ...
2066 * call bpf_perf_event_output#25
2067 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2068 *
2069 * and this case:
2070 * r6 = 1
2071 * call foo // uses callee's r6 inside to compute r0
2072 * r0 += r6
2073 * if r0 == 0 goto
2074 *
2075 * to track above reg_mask/stack_mask needs to be independent for each frame.
2076 *
2077 * Also if parent's curframe > frame where backtracking started,
2078 * the verifier need to mark registers in both frames, otherwise callees
2079 * may incorrectly prune callers. This is similar to
2080 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2081 *
2082 * For now backtracking falls back into conservative marking.
2083 */
2084static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2085 struct bpf_verifier_state *st)
2086{
2087 struct bpf_func_state *func;
2088 struct bpf_reg_state *reg;
2089 int i, j;
2090
2091 /* big hammer: mark all scalars precise in this path.
2092 * pop_stack may still get !precise scalars.
2093 */
2094 for (; st; st = st->parent)
2095 for (i = 0; i <= st->curframe; i++) {
2096 func = st->frame[i];
2097 for (j = 0; j < BPF_REG_FP; j++) {
2098 reg = &func->regs[j];
2099 if (reg->type != SCALAR_VALUE)
2100 continue;
2101 reg->precise = true;
2102 }
2103 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2104 if (func->stack[j].slot_type[0] != STACK_SPILL)
2105 continue;
2106 reg = &func->stack[j].spilled_ptr;
2107 if (reg->type != SCALAR_VALUE)
2108 continue;
2109 reg->precise = true;
2110 }
2111 }
2112}
2113
a3ce685d
AS
2114static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2115 int spi)
b5dc0163
AS
2116{
2117 struct bpf_verifier_state *st = env->cur_state;
2118 int first_idx = st->first_insn_idx;
2119 int last_idx = env->insn_idx;
2120 struct bpf_func_state *func;
2121 struct bpf_reg_state *reg;
a3ce685d
AS
2122 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2123 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2124 bool skip_first = true;
a3ce685d 2125 bool new_marks = false;
b5dc0163
AS
2126 int i, err;
2127
2c78ee89 2128 if (!env->bpf_capable)
b5dc0163
AS
2129 return 0;
2130
2131 func = st->frame[st->curframe];
a3ce685d
AS
2132 if (regno >= 0) {
2133 reg = &func->regs[regno];
2134 if (reg->type != SCALAR_VALUE) {
2135 WARN_ONCE(1, "backtracing misuse");
2136 return -EFAULT;
2137 }
2138 if (!reg->precise)
2139 new_marks = true;
2140 else
2141 reg_mask = 0;
2142 reg->precise = true;
b5dc0163 2143 }
b5dc0163 2144
a3ce685d
AS
2145 while (spi >= 0) {
2146 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2147 stack_mask = 0;
2148 break;
2149 }
2150 reg = &func->stack[spi].spilled_ptr;
2151 if (reg->type != SCALAR_VALUE) {
2152 stack_mask = 0;
2153 break;
2154 }
2155 if (!reg->precise)
2156 new_marks = true;
2157 else
2158 stack_mask = 0;
2159 reg->precise = true;
2160 break;
2161 }
2162
2163 if (!new_marks)
2164 return 0;
2165 if (!reg_mask && !stack_mask)
2166 return 0;
b5dc0163
AS
2167 for (;;) {
2168 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2169 u32 history = st->jmp_history_cnt;
2170
2171 if (env->log.level & BPF_LOG_LEVEL)
2172 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2173 for (i = last_idx;;) {
2174 if (skip_first) {
2175 err = 0;
2176 skip_first = false;
2177 } else {
2178 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2179 }
2180 if (err == -ENOTSUPP) {
2181 mark_all_scalars_precise(env, st);
2182 return 0;
2183 } else if (err) {
2184 return err;
2185 }
2186 if (!reg_mask && !stack_mask)
2187 /* Found assignment(s) into tracked register in this state.
2188 * Since this state is already marked, just return.
2189 * Nothing to be tracked further in the parent state.
2190 */
2191 return 0;
2192 if (i == first_idx)
2193 break;
2194 i = get_prev_insn_idx(st, i, &history);
2195 if (i >= env->prog->len) {
2196 /* This can happen if backtracking reached insn 0
2197 * and there are still reg_mask or stack_mask
2198 * to backtrack.
2199 * It means the backtracking missed the spot where
2200 * particular register was initialized with a constant.
2201 */
2202 verbose(env, "BUG backtracking idx %d\n", i);
2203 WARN_ONCE(1, "verifier backtracking bug");
2204 return -EFAULT;
2205 }
2206 }
2207 st = st->parent;
2208 if (!st)
2209 break;
2210
a3ce685d 2211 new_marks = false;
b5dc0163
AS
2212 func = st->frame[st->curframe];
2213 bitmap_from_u64(mask, reg_mask);
2214 for_each_set_bit(i, mask, 32) {
2215 reg = &func->regs[i];
a3ce685d
AS
2216 if (reg->type != SCALAR_VALUE) {
2217 reg_mask &= ~(1u << i);
b5dc0163 2218 continue;
a3ce685d 2219 }
b5dc0163
AS
2220 if (!reg->precise)
2221 new_marks = true;
2222 reg->precise = true;
2223 }
2224
2225 bitmap_from_u64(mask, stack_mask);
2226 for_each_set_bit(i, mask, 64) {
2227 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2228 /* the sequence of instructions:
2229 * 2: (bf) r3 = r10
2230 * 3: (7b) *(u64 *)(r3 -8) = r0
2231 * 4: (79) r4 = *(u64 *)(r10 -8)
2232 * doesn't contain jmps. It's backtracked
2233 * as a single block.
2234 * During backtracking insn 3 is not recognized as
2235 * stack access, so at the end of backtracking
2236 * stack slot fp-8 is still marked in stack_mask.
2237 * However the parent state may not have accessed
2238 * fp-8 and it's "unallocated" stack space.
2239 * In such case fallback to conservative.
b5dc0163 2240 */
2339cd6c
AS
2241 mark_all_scalars_precise(env, st);
2242 return 0;
b5dc0163
AS
2243 }
2244
a3ce685d
AS
2245 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2246 stack_mask &= ~(1ull << i);
b5dc0163 2247 continue;
a3ce685d 2248 }
b5dc0163 2249 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2250 if (reg->type != SCALAR_VALUE) {
2251 stack_mask &= ~(1ull << i);
b5dc0163 2252 continue;
a3ce685d 2253 }
b5dc0163
AS
2254 if (!reg->precise)
2255 new_marks = true;
2256 reg->precise = true;
2257 }
2258 if (env->log.level & BPF_LOG_LEVEL) {
2259 print_verifier_state(env, func);
2260 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2261 new_marks ? "didn't have" : "already had",
2262 reg_mask, stack_mask);
2263 }
2264
a3ce685d
AS
2265 if (!reg_mask && !stack_mask)
2266 break;
b5dc0163
AS
2267 if (!new_marks)
2268 break;
2269
2270 last_idx = st->last_insn_idx;
2271 first_idx = st->first_insn_idx;
2272 }
2273 return 0;
2274}
2275
a3ce685d
AS
2276static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2277{
2278 return __mark_chain_precision(env, regno, -1);
2279}
2280
2281static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2282{
2283 return __mark_chain_precision(env, -1, spi);
2284}
b5dc0163 2285
1be7f75d
AS
2286static bool is_spillable_regtype(enum bpf_reg_type type)
2287{
2288 switch (type) {
2289 case PTR_TO_MAP_VALUE:
2290 case PTR_TO_MAP_VALUE_OR_NULL:
2291 case PTR_TO_STACK:
2292 case PTR_TO_CTX:
969bf05e 2293 case PTR_TO_PACKET:
de8f3a83 2294 case PTR_TO_PACKET_META:
969bf05e 2295 case PTR_TO_PACKET_END:
d58e468b 2296 case PTR_TO_FLOW_KEYS:
1be7f75d 2297 case CONST_PTR_TO_MAP:
c64b7983
JS
2298 case PTR_TO_SOCKET:
2299 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2300 case PTR_TO_SOCK_COMMON:
2301 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2302 case PTR_TO_TCP_SOCK:
2303 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2304 case PTR_TO_XDP_SOCK:
65726b5b 2305 case PTR_TO_BTF_ID:
b121b341 2306 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2307 case PTR_TO_RDONLY_BUF:
2308 case PTR_TO_RDONLY_BUF_OR_NULL:
2309 case PTR_TO_RDWR_BUF:
2310 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2311 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2312 case PTR_TO_MEM:
2313 case PTR_TO_MEM_OR_NULL:
69c087ba
YS
2314 case PTR_TO_FUNC:
2315 case PTR_TO_MAP_KEY:
1be7f75d
AS
2316 return true;
2317 default:
2318 return false;
2319 }
2320}
2321
cc2b14d5
AS
2322/* Does this register contain a constant zero? */
2323static bool register_is_null(struct bpf_reg_state *reg)
2324{
2325 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2326}
2327
f7cf25b2
AS
2328static bool register_is_const(struct bpf_reg_state *reg)
2329{
2330 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2331}
2332
5689d49b
YS
2333static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2334{
2335 return tnum_is_unknown(reg->var_off) &&
2336 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2337 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2338 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2339 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2340}
2341
2342static bool register_is_bounded(struct bpf_reg_state *reg)
2343{
2344 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2345}
2346
6e7e63cb
JH
2347static bool __is_pointer_value(bool allow_ptr_leaks,
2348 const struct bpf_reg_state *reg)
2349{
2350 if (allow_ptr_leaks)
2351 return false;
2352
2353 return reg->type != SCALAR_VALUE;
2354}
2355
f7cf25b2
AS
2356static void save_register_state(struct bpf_func_state *state,
2357 int spi, struct bpf_reg_state *reg)
2358{
2359 int i;
2360
2361 state->stack[spi].spilled_ptr = *reg;
2362 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2363
2364 for (i = 0; i < BPF_REG_SIZE; i++)
2365 state->stack[spi].slot_type[i] = STACK_SPILL;
2366}
2367
01f810ac 2368/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2369 * stack boundary and alignment are checked in check_mem_access()
2370 */
01f810ac
AM
2371static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2372 /* stack frame we're writing to */
2373 struct bpf_func_state *state,
2374 int off, int size, int value_regno,
2375 int insn_idx)
17a52670 2376{
f4d7e40a 2377 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2378 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2379 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2380 struct bpf_reg_state *reg = NULL;
638f5b90 2381
f4d7e40a 2382 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2383 state->acquired_refs, true);
638f5b90
AS
2384 if (err)
2385 return err;
9c399760
AS
2386 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2387 * so it's aligned access and [off, off + size) are within stack limits
2388 */
638f5b90
AS
2389 if (!env->allow_ptr_leaks &&
2390 state->stack[spi].slot_type[0] == STACK_SPILL &&
2391 size != BPF_REG_SIZE) {
2392 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2393 return -EACCES;
2394 }
17a52670 2395
f4d7e40a 2396 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2397 if (value_regno >= 0)
2398 reg = &cur->regs[value_regno];
17a52670 2399
5689d49b 2400 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2401 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2402 if (dst_reg != BPF_REG_FP) {
2403 /* The backtracking logic can only recognize explicit
2404 * stack slot address like [fp - 8]. Other spill of
2405 * scalar via different register has to be conervative.
2406 * Backtrack from here and mark all registers as precise
2407 * that contributed into 'reg' being a constant.
2408 */
2409 err = mark_chain_precision(env, value_regno);
2410 if (err)
2411 return err;
2412 }
f7cf25b2
AS
2413 save_register_state(state, spi, reg);
2414 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2415 /* register containing pointer is being spilled into stack */
9c399760 2416 if (size != BPF_REG_SIZE) {
f7cf25b2 2417 verbose_linfo(env, insn_idx, "; ");
61bd5218 2418 verbose(env, "invalid size of register spill\n");
17a52670
AS
2419 return -EACCES;
2420 }
2421
f7cf25b2 2422 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2423 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2424 return -EINVAL;
2425 }
2426
2c78ee89 2427 if (!env->bypass_spec_v4) {
f7cf25b2 2428 bool sanitize = false;
17a52670 2429
f7cf25b2
AS
2430 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2431 register_is_const(&state->stack[spi].spilled_ptr))
2432 sanitize = true;
2433 for (i = 0; i < BPF_REG_SIZE; i++)
2434 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2435 sanitize = true;
2436 break;
2437 }
2438 if (sanitize) {
af86ca4e
AS
2439 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2440 int soff = (-spi - 1) * BPF_REG_SIZE;
2441
2442 /* detected reuse of integer stack slot with a pointer
2443 * which means either llvm is reusing stack slot or
2444 * an attacker is trying to exploit CVE-2018-3639
2445 * (speculative store bypass)
2446 * Have to sanitize that slot with preemptive
2447 * store of zero.
2448 */
2449 if (*poff && *poff != soff) {
2450 /* disallow programs where single insn stores
2451 * into two different stack slots, since verifier
2452 * cannot sanitize them
2453 */
2454 verbose(env,
2455 "insn %d cannot access two stack slots fp%d and fp%d",
2456 insn_idx, *poff, soff);
2457 return -EINVAL;
2458 }
2459 *poff = soff;
2460 }
af86ca4e 2461 }
f7cf25b2 2462 save_register_state(state, spi, reg);
9c399760 2463 } else {
cc2b14d5
AS
2464 u8 type = STACK_MISC;
2465
679c782d
EC
2466 /* regular write of data into stack destroys any spilled ptr */
2467 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2468 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2469 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2470 for (i = 0; i < BPF_REG_SIZE; i++)
2471 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2472
cc2b14d5
AS
2473 /* only mark the slot as written if all 8 bytes were written
2474 * otherwise read propagation may incorrectly stop too soon
2475 * when stack slots are partially written.
2476 * This heuristic means that read propagation will be
2477 * conservative, since it will add reg_live_read marks
2478 * to stack slots all the way to first state when programs
2479 * writes+reads less than 8 bytes
2480 */
2481 if (size == BPF_REG_SIZE)
2482 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2483
2484 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2485 if (reg && register_is_null(reg)) {
2486 /* backtracking doesn't work for STACK_ZERO yet. */
2487 err = mark_chain_precision(env, value_regno);
2488 if (err)
2489 return err;
cc2b14d5 2490 type = STACK_ZERO;
b5dc0163 2491 }
cc2b14d5 2492
0bae2d4d 2493 /* Mark slots affected by this stack write. */
9c399760 2494 for (i = 0; i < size; i++)
638f5b90 2495 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2496 type;
17a52670
AS
2497 }
2498 return 0;
2499}
2500
01f810ac
AM
2501/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2502 * known to contain a variable offset.
2503 * This function checks whether the write is permitted and conservatively
2504 * tracks the effects of the write, considering that each stack slot in the
2505 * dynamic range is potentially written to.
2506 *
2507 * 'off' includes 'regno->off'.
2508 * 'value_regno' can be -1, meaning that an unknown value is being written to
2509 * the stack.
2510 *
2511 * Spilled pointers in range are not marked as written because we don't know
2512 * what's going to be actually written. This means that read propagation for
2513 * future reads cannot be terminated by this write.
2514 *
2515 * For privileged programs, uninitialized stack slots are considered
2516 * initialized by this write (even though we don't know exactly what offsets
2517 * are going to be written to). The idea is that we don't want the verifier to
2518 * reject future reads that access slots written to through variable offsets.
2519 */
2520static int check_stack_write_var_off(struct bpf_verifier_env *env,
2521 /* func where register points to */
2522 struct bpf_func_state *state,
2523 int ptr_regno, int off, int size,
2524 int value_regno, int insn_idx)
2525{
2526 struct bpf_func_state *cur; /* state of the current function */
2527 int min_off, max_off;
2528 int i, err;
2529 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2530 bool writing_zero = false;
2531 /* set if the fact that we're writing a zero is used to let any
2532 * stack slots remain STACK_ZERO
2533 */
2534 bool zero_used = false;
2535
2536 cur = env->cur_state->frame[env->cur_state->curframe];
2537 ptr_reg = &cur->regs[ptr_regno];
2538 min_off = ptr_reg->smin_value + off;
2539 max_off = ptr_reg->smax_value + off + size;
2540 if (value_regno >= 0)
2541 value_reg = &cur->regs[value_regno];
2542 if (value_reg && register_is_null(value_reg))
2543 writing_zero = true;
2544
2545 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2546 state->acquired_refs, true);
2547 if (err)
2548 return err;
2549
2550
2551 /* Variable offset writes destroy any spilled pointers in range. */
2552 for (i = min_off; i < max_off; i++) {
2553 u8 new_type, *stype;
2554 int slot, spi;
2555
2556 slot = -i - 1;
2557 spi = slot / BPF_REG_SIZE;
2558 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2559
2560 if (!env->allow_ptr_leaks
2561 && *stype != NOT_INIT
2562 && *stype != SCALAR_VALUE) {
2563 /* Reject the write if there's are spilled pointers in
2564 * range. If we didn't reject here, the ptr status
2565 * would be erased below (even though not all slots are
2566 * actually overwritten), possibly opening the door to
2567 * leaks.
2568 */
2569 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2570 insn_idx, i);
2571 return -EINVAL;
2572 }
2573
2574 /* Erase all spilled pointers. */
2575 state->stack[spi].spilled_ptr.type = NOT_INIT;
2576
2577 /* Update the slot type. */
2578 new_type = STACK_MISC;
2579 if (writing_zero && *stype == STACK_ZERO) {
2580 new_type = STACK_ZERO;
2581 zero_used = true;
2582 }
2583 /* If the slot is STACK_INVALID, we check whether it's OK to
2584 * pretend that it will be initialized by this write. The slot
2585 * might not actually be written to, and so if we mark it as
2586 * initialized future reads might leak uninitialized memory.
2587 * For privileged programs, we will accept such reads to slots
2588 * that may or may not be written because, if we're reject
2589 * them, the error would be too confusing.
2590 */
2591 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2592 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2593 insn_idx, i);
2594 return -EINVAL;
2595 }
2596 *stype = new_type;
2597 }
2598 if (zero_used) {
2599 /* backtracking doesn't work for STACK_ZERO yet. */
2600 err = mark_chain_precision(env, value_regno);
2601 if (err)
2602 return err;
2603 }
2604 return 0;
2605}
2606
2607/* When register 'dst_regno' is assigned some values from stack[min_off,
2608 * max_off), we set the register's type according to the types of the
2609 * respective stack slots. If all the stack values are known to be zeros, then
2610 * so is the destination reg. Otherwise, the register is considered to be
2611 * SCALAR. This function does not deal with register filling; the caller must
2612 * ensure that all spilled registers in the stack range have been marked as
2613 * read.
2614 */
2615static void mark_reg_stack_read(struct bpf_verifier_env *env,
2616 /* func where src register points to */
2617 struct bpf_func_state *ptr_state,
2618 int min_off, int max_off, int dst_regno)
2619{
2620 struct bpf_verifier_state *vstate = env->cur_state;
2621 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2622 int i, slot, spi;
2623 u8 *stype;
2624 int zeros = 0;
2625
2626 for (i = min_off; i < max_off; i++) {
2627 slot = -i - 1;
2628 spi = slot / BPF_REG_SIZE;
2629 stype = ptr_state->stack[spi].slot_type;
2630 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2631 break;
2632 zeros++;
2633 }
2634 if (zeros == max_off - min_off) {
2635 /* any access_size read into register is zero extended,
2636 * so the whole register == const_zero
2637 */
2638 __mark_reg_const_zero(&state->regs[dst_regno]);
2639 /* backtracking doesn't support STACK_ZERO yet,
2640 * so mark it precise here, so that later
2641 * backtracking can stop here.
2642 * Backtracking may not need this if this register
2643 * doesn't participate in pointer adjustment.
2644 * Forward propagation of precise flag is not
2645 * necessary either. This mark is only to stop
2646 * backtracking. Any register that contributed
2647 * to const 0 was marked precise before spill.
2648 */
2649 state->regs[dst_regno].precise = true;
2650 } else {
2651 /* have read misc data from the stack */
2652 mark_reg_unknown(env, state->regs, dst_regno);
2653 }
2654 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2655}
2656
2657/* Read the stack at 'off' and put the results into the register indicated by
2658 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2659 * spilled reg.
2660 *
2661 * 'dst_regno' can be -1, meaning that the read value is not going to a
2662 * register.
2663 *
2664 * The access is assumed to be within the current stack bounds.
2665 */
2666static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2667 /* func where src register points to */
2668 struct bpf_func_state *reg_state,
2669 int off, int size, int dst_regno)
17a52670 2670{
f4d7e40a
AS
2671 struct bpf_verifier_state *vstate = env->cur_state;
2672 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2673 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2674 struct bpf_reg_state *reg;
638f5b90 2675 u8 *stype;
17a52670 2676
f4d7e40a 2677 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2678 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2679
638f5b90 2680 if (stype[0] == STACK_SPILL) {
9c399760 2681 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2682 if (reg->type != SCALAR_VALUE) {
2683 verbose_linfo(env, env->insn_idx, "; ");
2684 verbose(env, "invalid size of register fill\n");
2685 return -EACCES;
2686 }
01f810ac
AM
2687 if (dst_regno >= 0) {
2688 mark_reg_unknown(env, state->regs, dst_regno);
2689 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2690 }
2691 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2692 return 0;
17a52670 2693 }
9c399760 2694 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2695 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2696 verbose(env, "corrupted spill memory\n");
17a52670
AS
2697 return -EACCES;
2698 }
2699 }
2700
01f810ac 2701 if (dst_regno >= 0) {
17a52670 2702 /* restore register state from stack */
01f810ac 2703 state->regs[dst_regno] = *reg;
2f18f62e
AS
2704 /* mark reg as written since spilled pointer state likely
2705 * has its liveness marks cleared by is_state_visited()
2706 * which resets stack/reg liveness for state transitions
2707 */
01f810ac 2708 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2709 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 2710 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2711 * it is acceptable to use this value as a SCALAR_VALUE
2712 * (e.g. for XADD).
2713 * We must not allow unprivileged callers to do that
2714 * with spilled pointers.
2715 */
2716 verbose(env, "leaking pointer from stack off %d\n",
2717 off);
2718 return -EACCES;
dc503a8a 2719 }
f7cf25b2 2720 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2721 } else {
01f810ac 2722 u8 type;
cc2b14d5 2723
17a52670 2724 for (i = 0; i < size; i++) {
01f810ac
AM
2725 type = stype[(slot - i) % BPF_REG_SIZE];
2726 if (type == STACK_MISC)
cc2b14d5 2727 continue;
01f810ac 2728 if (type == STACK_ZERO)
cc2b14d5 2729 continue;
cc2b14d5
AS
2730 verbose(env, "invalid read from stack off %d+%d size %d\n",
2731 off, i, size);
2732 return -EACCES;
2733 }
f7cf25b2 2734 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
2735 if (dst_regno >= 0)
2736 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2737 }
f7cf25b2 2738 return 0;
17a52670
AS
2739}
2740
01f810ac
AM
2741enum stack_access_src {
2742 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2743 ACCESS_HELPER = 2, /* the access is performed by a helper */
2744};
2745
2746static int check_stack_range_initialized(struct bpf_verifier_env *env,
2747 int regno, int off, int access_size,
2748 bool zero_size_allowed,
2749 enum stack_access_src type,
2750 struct bpf_call_arg_meta *meta);
2751
2752static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2753{
2754 return cur_regs(env) + regno;
2755}
2756
2757/* Read the stack at 'ptr_regno + off' and put the result into the register
2758 * 'dst_regno'.
2759 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2760 * but not its variable offset.
2761 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2762 *
2763 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2764 * filling registers (i.e. reads of spilled register cannot be detected when
2765 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2766 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2767 * offset; for a fixed offset check_stack_read_fixed_off should be used
2768 * instead.
2769 */
2770static int check_stack_read_var_off(struct bpf_verifier_env *env,
2771 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2772{
01f810ac
AM
2773 /* The state of the source register. */
2774 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2775 struct bpf_func_state *ptr_state = func(env, reg);
2776 int err;
2777 int min_off, max_off;
2778
2779 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2780 */
01f810ac
AM
2781 err = check_stack_range_initialized(env, ptr_regno, off, size,
2782 false, ACCESS_DIRECT, NULL);
2783 if (err)
2784 return err;
2785
2786 min_off = reg->smin_value + off;
2787 max_off = reg->smax_value + off;
2788 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2789 return 0;
2790}
2791
2792/* check_stack_read dispatches to check_stack_read_fixed_off or
2793 * check_stack_read_var_off.
2794 *
2795 * The caller must ensure that the offset falls within the allocated stack
2796 * bounds.
2797 *
2798 * 'dst_regno' is a register which will receive the value from the stack. It
2799 * can be -1, meaning that the read value is not going to a register.
2800 */
2801static int check_stack_read(struct bpf_verifier_env *env,
2802 int ptr_regno, int off, int size,
2803 int dst_regno)
2804{
2805 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2806 struct bpf_func_state *state = func(env, reg);
2807 int err;
2808 /* Some accesses are only permitted with a static offset. */
2809 bool var_off = !tnum_is_const(reg->var_off);
2810
2811 /* The offset is required to be static when reads don't go to a
2812 * register, in order to not leak pointers (see
2813 * check_stack_read_fixed_off).
2814 */
2815 if (dst_regno < 0 && var_off) {
e4298d25
DB
2816 char tn_buf[48];
2817
2818 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 2819 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
2820 tn_buf, off, size);
2821 return -EACCES;
2822 }
01f810ac
AM
2823 /* Variable offset is prohibited for unprivileged mode for simplicity
2824 * since it requires corresponding support in Spectre masking for stack
2825 * ALU. See also retrieve_ptr_limit().
2826 */
2827 if (!env->bypass_spec_v1 && var_off) {
2828 char tn_buf[48];
e4298d25 2829
01f810ac
AM
2830 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2831 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2832 ptr_regno, tn_buf);
e4298d25
DB
2833 return -EACCES;
2834 }
2835
01f810ac
AM
2836 if (!var_off) {
2837 off += reg->var_off.value;
2838 err = check_stack_read_fixed_off(env, state, off, size,
2839 dst_regno);
2840 } else {
2841 /* Variable offset stack reads need more conservative handling
2842 * than fixed offset ones. Note that dst_regno >= 0 on this
2843 * branch.
2844 */
2845 err = check_stack_read_var_off(env, ptr_regno, off, size,
2846 dst_regno);
2847 }
2848 return err;
2849}
2850
2851
2852/* check_stack_write dispatches to check_stack_write_fixed_off or
2853 * check_stack_write_var_off.
2854 *
2855 * 'ptr_regno' is the register used as a pointer into the stack.
2856 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2857 * 'value_regno' is the register whose value we're writing to the stack. It can
2858 * be -1, meaning that we're not writing from a register.
2859 *
2860 * The caller must ensure that the offset falls within the maximum stack size.
2861 */
2862static int check_stack_write(struct bpf_verifier_env *env,
2863 int ptr_regno, int off, int size,
2864 int value_regno, int insn_idx)
2865{
2866 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2867 struct bpf_func_state *state = func(env, reg);
2868 int err;
2869
2870 if (tnum_is_const(reg->var_off)) {
2871 off += reg->var_off.value;
2872 err = check_stack_write_fixed_off(env, state, off, size,
2873 value_regno, insn_idx);
2874 } else {
2875 /* Variable offset stack reads need more conservative handling
2876 * than fixed offset ones.
2877 */
2878 err = check_stack_write_var_off(env, state,
2879 ptr_regno, off, size,
2880 value_regno, insn_idx);
2881 }
2882 return err;
e4298d25
DB
2883}
2884
591fe988
DB
2885static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2886 int off, int size, enum bpf_access_type type)
2887{
2888 struct bpf_reg_state *regs = cur_regs(env);
2889 struct bpf_map *map = regs[regno].map_ptr;
2890 u32 cap = bpf_map_flags_to_cap(map);
2891
2892 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2893 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2894 map->value_size, off, size);
2895 return -EACCES;
2896 }
2897
2898 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2899 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2900 map->value_size, off, size);
2901 return -EACCES;
2902 }
2903
2904 return 0;
2905}
2906
457f4436
AN
2907/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2908static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2909 int off, int size, u32 mem_size,
2910 bool zero_size_allowed)
17a52670 2911{
457f4436
AN
2912 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2913 struct bpf_reg_state *reg;
2914
2915 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2916 return 0;
17a52670 2917
457f4436
AN
2918 reg = &cur_regs(env)[regno];
2919 switch (reg->type) {
69c087ba
YS
2920 case PTR_TO_MAP_KEY:
2921 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
2922 mem_size, off, size);
2923 break;
457f4436 2924 case PTR_TO_MAP_VALUE:
61bd5218 2925 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2926 mem_size, off, size);
2927 break;
2928 case PTR_TO_PACKET:
2929 case PTR_TO_PACKET_META:
2930 case PTR_TO_PACKET_END:
2931 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2932 off, size, regno, reg->id, off, mem_size);
2933 break;
2934 case PTR_TO_MEM:
2935 default:
2936 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2937 mem_size, off, size);
17a52670 2938 }
457f4436
AN
2939
2940 return -EACCES;
17a52670
AS
2941}
2942
457f4436
AN
2943/* check read/write into a memory region with possible variable offset */
2944static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2945 int off, int size, u32 mem_size,
2946 bool zero_size_allowed)
dbcfe5f7 2947{
f4d7e40a
AS
2948 struct bpf_verifier_state *vstate = env->cur_state;
2949 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2950 struct bpf_reg_state *reg = &state->regs[regno];
2951 int err;
2952
457f4436 2953 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2954 * need to try adding each of min_value and max_value to off
2955 * to make sure our theoretical access will be safe.
dbcfe5f7 2956 */
06ee7115 2957 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2958 print_verifier_state(env, state);
b7137c4e 2959
dbcfe5f7
GB
2960 /* The minimum value is only important with signed
2961 * comparisons where we can't assume the floor of a
2962 * value is 0. If we are using signed variables for our
2963 * index'es we need to make sure that whatever we use
2964 * will have a set floor within our range.
2965 */
b7137c4e
DB
2966 if (reg->smin_value < 0 &&
2967 (reg->smin_value == S64_MIN ||
2968 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2969 reg->smin_value + off < 0)) {
61bd5218 2970 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2971 regno);
2972 return -EACCES;
2973 }
457f4436
AN
2974 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2975 mem_size, zero_size_allowed);
dbcfe5f7 2976 if (err) {
457f4436 2977 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 2978 regno);
dbcfe5f7
GB
2979 return err;
2980 }
2981
b03c9f9f
EC
2982 /* If we haven't set a max value then we need to bail since we can't be
2983 * sure we won't do bad things.
2984 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 2985 */
b03c9f9f 2986 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 2987 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
2988 regno);
2989 return -EACCES;
2990 }
457f4436
AN
2991 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2992 mem_size, zero_size_allowed);
2993 if (err) {
2994 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 2995 regno);
457f4436
AN
2996 return err;
2997 }
2998
2999 return 0;
3000}
d83525ca 3001
457f4436
AN
3002/* check read/write into a map element with possible variable offset */
3003static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3004 int off, int size, bool zero_size_allowed)
3005{
3006 struct bpf_verifier_state *vstate = env->cur_state;
3007 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3008 struct bpf_reg_state *reg = &state->regs[regno];
3009 struct bpf_map *map = reg->map_ptr;
3010 int err;
3011
3012 err = check_mem_region_access(env, regno, off, size, map->value_size,
3013 zero_size_allowed);
3014 if (err)
3015 return err;
3016
3017 if (map_value_has_spin_lock(map)) {
3018 u32 lock = map->spin_lock_off;
d83525ca
AS
3019
3020 /* if any part of struct bpf_spin_lock can be touched by
3021 * load/store reject this program.
3022 * To check that [x1, x2) overlaps with [y1, y2)
3023 * it is sufficient to check x1 < y2 && y1 < x2.
3024 */
3025 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3026 lock < reg->umax_value + off + size) {
3027 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3028 return -EACCES;
3029 }
3030 }
f1174f77 3031 return err;
dbcfe5f7
GB
3032}
3033
969bf05e
AS
3034#define MAX_PACKET_OFF 0xffff
3035
7e40781c
UP
3036static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3037{
3aac1ead 3038 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
3039}
3040
58e2af8b 3041static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3042 const struct bpf_call_arg_meta *meta,
3043 enum bpf_access_type t)
4acf6c0b 3044{
7e40781c
UP
3045 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3046
3047 switch (prog_type) {
5d66fa7d 3048 /* Program types only with direct read access go here! */
3a0af8fd
TG
3049 case BPF_PROG_TYPE_LWT_IN:
3050 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3051 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3052 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3053 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3054 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3055 if (t == BPF_WRITE)
3056 return false;
8731745e 3057 fallthrough;
5d66fa7d
DB
3058
3059 /* Program types with direct read + write access go here! */
36bbef52
DB
3060 case BPF_PROG_TYPE_SCHED_CLS:
3061 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3062 case BPF_PROG_TYPE_XDP:
3a0af8fd 3063 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3064 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3065 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3066 if (meta)
3067 return meta->pkt_access;
3068
3069 env->seen_direct_write = true;
4acf6c0b 3070 return true;
0d01da6a
SF
3071
3072 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3073 if (t == BPF_WRITE)
3074 env->seen_direct_write = true;
3075
3076 return true;
3077
4acf6c0b
BB
3078 default:
3079 return false;
3080 }
3081}
3082
f1174f77 3083static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3084 int size, bool zero_size_allowed)
f1174f77 3085{
638f5b90 3086 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3087 struct bpf_reg_state *reg = &regs[regno];
3088 int err;
3089
3090 /* We may have added a variable offset to the packet pointer; but any
3091 * reg->range we have comes after that. We are only checking the fixed
3092 * offset.
3093 */
3094
3095 /* We don't allow negative numbers, because we aren't tracking enough
3096 * detail to prove they're safe.
3097 */
b03c9f9f 3098 if (reg->smin_value < 0) {
61bd5218 3099 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3100 regno);
3101 return -EACCES;
3102 }
6d94e741
AS
3103
3104 err = reg->range < 0 ? -EINVAL :
3105 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3106 zero_size_allowed);
f1174f77 3107 if (err) {
61bd5218 3108 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3109 return err;
3110 }
e647815a 3111
457f4436 3112 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3113 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3114 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3115 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3116 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3117 */
3118 env->prog->aux->max_pkt_offset =
3119 max_t(u32, env->prog->aux->max_pkt_offset,
3120 off + reg->umax_value + size - 1);
3121
f1174f77
EC
3122 return err;
3123}
3124
3125/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3126static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3127 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3128 struct btf **btf, u32 *btf_id)
17a52670 3129{
f96da094
DB
3130 struct bpf_insn_access_aux info = {
3131 .reg_type = *reg_type,
9e15db66 3132 .log = &env->log,
f96da094 3133 };
31fd8581 3134
4f9218aa 3135 if (env->ops->is_valid_access &&
5e43f899 3136 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3137 /* A non zero info.ctx_field_size indicates that this field is a
3138 * candidate for later verifier transformation to load the whole
3139 * field and then apply a mask when accessed with a narrower
3140 * access than actual ctx access size. A zero info.ctx_field_size
3141 * will only allow for whole field access and rejects any other
3142 * type of narrower access.
31fd8581 3143 */
23994631 3144 *reg_type = info.reg_type;
31fd8581 3145
22dc4a0f
AN
3146 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3147 *btf = info.btf;
9e15db66 3148 *btf_id = info.btf_id;
22dc4a0f 3149 } else {
9e15db66 3150 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3151 }
32bbe007
AS
3152 /* remember the offset of last byte accessed in ctx */
3153 if (env->prog->aux->max_ctx_offset < off + size)
3154 env->prog->aux->max_ctx_offset = off + size;
17a52670 3155 return 0;
32bbe007 3156 }
17a52670 3157
61bd5218 3158 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3159 return -EACCES;
3160}
3161
d58e468b
PP
3162static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3163 int size)
3164{
3165 if (size < 0 || off < 0 ||
3166 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3167 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3168 off, size);
3169 return -EACCES;
3170 }
3171 return 0;
3172}
3173
5f456649
MKL
3174static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3175 u32 regno, int off, int size,
3176 enum bpf_access_type t)
c64b7983
JS
3177{
3178 struct bpf_reg_state *regs = cur_regs(env);
3179 struct bpf_reg_state *reg = &regs[regno];
5f456649 3180 struct bpf_insn_access_aux info = {};
46f8bc92 3181 bool valid;
c64b7983
JS
3182
3183 if (reg->smin_value < 0) {
3184 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3185 regno);
3186 return -EACCES;
3187 }
3188
46f8bc92
MKL
3189 switch (reg->type) {
3190 case PTR_TO_SOCK_COMMON:
3191 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3192 break;
3193 case PTR_TO_SOCKET:
3194 valid = bpf_sock_is_valid_access(off, size, t, &info);
3195 break;
655a51e5
MKL
3196 case PTR_TO_TCP_SOCK:
3197 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3198 break;
fada7fdc
JL
3199 case PTR_TO_XDP_SOCK:
3200 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3201 break;
46f8bc92
MKL
3202 default:
3203 valid = false;
c64b7983
JS
3204 }
3205
5f456649 3206
46f8bc92
MKL
3207 if (valid) {
3208 env->insn_aux_data[insn_idx].ctx_field_size =
3209 info.ctx_field_size;
3210 return 0;
3211 }
3212
3213 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3214 regno, reg_type_str[reg->type], off, size);
3215
3216 return -EACCES;
c64b7983
JS
3217}
3218
4cabc5b1
DB
3219static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3220{
2a159c6f 3221 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3222}
3223
f37a8cb8
DB
3224static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3225{
2a159c6f 3226 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3227
46f8bc92
MKL
3228 return reg->type == PTR_TO_CTX;
3229}
3230
3231static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3232{
3233 const struct bpf_reg_state *reg = reg_state(env, regno);
3234
3235 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3236}
3237
ca369602
DB
3238static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3239{
2a159c6f 3240 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3241
3242 return type_is_pkt_pointer(reg->type);
3243}
3244
4b5defde
DB
3245static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3246{
3247 const struct bpf_reg_state *reg = reg_state(env, regno);
3248
3249 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3250 return reg->type == PTR_TO_FLOW_KEYS;
3251}
3252
61bd5218
JK
3253static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3254 const struct bpf_reg_state *reg,
d1174416 3255 int off, int size, bool strict)
969bf05e 3256{
f1174f77 3257 struct tnum reg_off;
e07b98d9 3258 int ip_align;
d1174416
DM
3259
3260 /* Byte size accesses are always allowed. */
3261 if (!strict || size == 1)
3262 return 0;
3263
e4eda884
DM
3264 /* For platforms that do not have a Kconfig enabling
3265 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3266 * NET_IP_ALIGN is universally set to '2'. And on platforms
3267 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3268 * to this code only in strict mode where we want to emulate
3269 * the NET_IP_ALIGN==2 checking. Therefore use an
3270 * unconditional IP align value of '2'.
e07b98d9 3271 */
e4eda884 3272 ip_align = 2;
f1174f77
EC
3273
3274 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3275 if (!tnum_is_aligned(reg_off, size)) {
3276 char tn_buf[48];
3277
3278 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3279 verbose(env,
3280 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3281 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3282 return -EACCES;
3283 }
79adffcd 3284
969bf05e
AS
3285 return 0;
3286}
3287
61bd5218
JK
3288static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3289 const struct bpf_reg_state *reg,
f1174f77
EC
3290 const char *pointer_desc,
3291 int off, int size, bool strict)
79adffcd 3292{
f1174f77
EC
3293 struct tnum reg_off;
3294
3295 /* Byte size accesses are always allowed. */
3296 if (!strict || size == 1)
3297 return 0;
3298
3299 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3300 if (!tnum_is_aligned(reg_off, size)) {
3301 char tn_buf[48];
3302
3303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3304 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3305 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3306 return -EACCES;
3307 }
3308
969bf05e
AS
3309 return 0;
3310}
3311
e07b98d9 3312static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3313 const struct bpf_reg_state *reg, int off,
3314 int size, bool strict_alignment_once)
79adffcd 3315{
ca369602 3316 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3317 const char *pointer_desc = "";
d1174416 3318
79adffcd
DB
3319 switch (reg->type) {
3320 case PTR_TO_PACKET:
de8f3a83
DB
3321 case PTR_TO_PACKET_META:
3322 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3323 * right in front, treat it the very same way.
3324 */
61bd5218 3325 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3326 case PTR_TO_FLOW_KEYS:
3327 pointer_desc = "flow keys ";
3328 break;
69c087ba
YS
3329 case PTR_TO_MAP_KEY:
3330 pointer_desc = "key ";
3331 break;
f1174f77
EC
3332 case PTR_TO_MAP_VALUE:
3333 pointer_desc = "value ";
3334 break;
3335 case PTR_TO_CTX:
3336 pointer_desc = "context ";
3337 break;
3338 case PTR_TO_STACK:
3339 pointer_desc = "stack ";
01f810ac
AM
3340 /* The stack spill tracking logic in check_stack_write_fixed_off()
3341 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3342 * aligned.
3343 */
3344 strict = true;
f1174f77 3345 break;
c64b7983
JS
3346 case PTR_TO_SOCKET:
3347 pointer_desc = "sock ";
3348 break;
46f8bc92
MKL
3349 case PTR_TO_SOCK_COMMON:
3350 pointer_desc = "sock_common ";
3351 break;
655a51e5
MKL
3352 case PTR_TO_TCP_SOCK:
3353 pointer_desc = "tcp_sock ";
3354 break;
fada7fdc
JL
3355 case PTR_TO_XDP_SOCK:
3356 pointer_desc = "xdp_sock ";
3357 break;
79adffcd 3358 default:
f1174f77 3359 break;
79adffcd 3360 }
61bd5218
JK
3361 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3362 strict);
79adffcd
DB
3363}
3364
f4d7e40a
AS
3365static int update_stack_depth(struct bpf_verifier_env *env,
3366 const struct bpf_func_state *func,
3367 int off)
3368{
9c8105bd 3369 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3370
3371 if (stack >= -off)
3372 return 0;
3373
3374 /* update known max for given subprogram */
9c8105bd 3375 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3376 return 0;
3377}
f4d7e40a 3378
70a87ffe
AS
3379/* starting from main bpf function walk all instructions of the function
3380 * and recursively walk all callees that given function can call.
3381 * Ignore jump and exit insns.
3382 * Since recursion is prevented by check_cfg() this algorithm
3383 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3384 */
3385static int check_max_stack_depth(struct bpf_verifier_env *env)
3386{
9c8105bd
JW
3387 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3388 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3389 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3390 bool tail_call_reachable = false;
70a87ffe
AS
3391 int ret_insn[MAX_CALL_FRAMES];
3392 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3393 int j;
f4d7e40a 3394
70a87ffe 3395process_func:
7f6e4312
MF
3396 /* protect against potential stack overflow that might happen when
3397 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3398 * depth for such case down to 256 so that the worst case scenario
3399 * would result in 8k stack size (32 which is tailcall limit * 256 =
3400 * 8k).
3401 *
3402 * To get the idea what might happen, see an example:
3403 * func1 -> sub rsp, 128
3404 * subfunc1 -> sub rsp, 256
3405 * tailcall1 -> add rsp, 256
3406 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3407 * subfunc2 -> sub rsp, 64
3408 * subfunc22 -> sub rsp, 128
3409 * tailcall2 -> add rsp, 128
3410 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3411 *
3412 * tailcall will unwind the current stack frame but it will not get rid
3413 * of caller's stack as shown on the example above.
3414 */
3415 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3416 verbose(env,
3417 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3418 depth);
3419 return -EACCES;
3420 }
70a87ffe
AS
3421 /* round up to 32-bytes, since this is granularity
3422 * of interpreter stack size
3423 */
9c8105bd 3424 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3425 if (depth > MAX_BPF_STACK) {
f4d7e40a 3426 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3427 frame + 1, depth);
f4d7e40a
AS
3428 return -EACCES;
3429 }
70a87ffe 3430continue_func:
4cb3d99c 3431 subprog_end = subprog[idx + 1].start;
70a87ffe 3432 for (; i < subprog_end; i++) {
69c087ba 3433 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3434 continue;
3435 /* remember insn and function to return to */
3436 ret_insn[frame] = i + 1;
9c8105bd 3437 ret_prog[frame] = idx;
70a87ffe
AS
3438
3439 /* find the callee */
3440 i = i + insn[i].imm + 1;
9c8105bd
JW
3441 idx = find_subprog(env, i);
3442 if (idx < 0) {
70a87ffe
AS
3443 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3444 i);
3445 return -EFAULT;
3446 }
ebf7d1f5
MF
3447
3448 if (subprog[idx].has_tail_call)
3449 tail_call_reachable = true;
3450
70a87ffe
AS
3451 frame++;
3452 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3453 verbose(env, "the call stack of %d frames is too deep !\n",
3454 frame);
3455 return -E2BIG;
70a87ffe
AS
3456 }
3457 goto process_func;
3458 }
ebf7d1f5
MF
3459 /* if tail call got detected across bpf2bpf calls then mark each of the
3460 * currently present subprog frames as tail call reachable subprogs;
3461 * this info will be utilized by JIT so that we will be preserving the
3462 * tail call counter throughout bpf2bpf calls combined with tailcalls
3463 */
3464 if (tail_call_reachable)
3465 for (j = 0; j < frame; j++)
3466 subprog[ret_prog[j]].tail_call_reachable = true;
3467
70a87ffe
AS
3468 /* end of for() loop means the last insn of the 'subprog'
3469 * was reached. Doesn't matter whether it was JA or EXIT
3470 */
3471 if (frame == 0)
3472 return 0;
9c8105bd 3473 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3474 frame--;
3475 i = ret_insn[frame];
9c8105bd 3476 idx = ret_prog[frame];
70a87ffe 3477 goto continue_func;
f4d7e40a
AS
3478}
3479
19d28fbd 3480#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3481static int get_callee_stack_depth(struct bpf_verifier_env *env,
3482 const struct bpf_insn *insn, int idx)
3483{
3484 int start = idx + insn->imm + 1, subprog;
3485
3486 subprog = find_subprog(env, start);
3487 if (subprog < 0) {
3488 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3489 start);
3490 return -EFAULT;
3491 }
9c8105bd 3492 return env->subprog_info[subprog].stack_depth;
1ea47e01 3493}
19d28fbd 3494#endif
1ea47e01 3495
51c39bb1
AS
3496int check_ctx_reg(struct bpf_verifier_env *env,
3497 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3498{
3499 /* Access to ctx or passing it to a helper is only allowed in
3500 * its original, unmodified form.
3501 */
3502
3503 if (reg->off) {
3504 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3505 regno, reg->off);
3506 return -EACCES;
3507 }
3508
3509 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3510 char tn_buf[48];
3511
3512 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3513 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3514 return -EACCES;
3515 }
3516
3517 return 0;
3518}
3519
afbf21dc
YS
3520static int __check_buffer_access(struct bpf_verifier_env *env,
3521 const char *buf_info,
3522 const struct bpf_reg_state *reg,
3523 int regno, int off, int size)
9df1c28b
MM
3524{
3525 if (off < 0) {
3526 verbose(env,
4fc00b79 3527 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3528 regno, buf_info, off, size);
9df1c28b
MM
3529 return -EACCES;
3530 }
3531 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3532 char tn_buf[48];
3533
3534 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3535 verbose(env,
4fc00b79 3536 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3537 regno, off, tn_buf);
3538 return -EACCES;
3539 }
afbf21dc
YS
3540
3541 return 0;
3542}
3543
3544static int check_tp_buffer_access(struct bpf_verifier_env *env,
3545 const struct bpf_reg_state *reg,
3546 int regno, int off, int size)
3547{
3548 int err;
3549
3550 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3551 if (err)
3552 return err;
3553
9df1c28b
MM
3554 if (off + size > env->prog->aux->max_tp_access)
3555 env->prog->aux->max_tp_access = off + size;
3556
3557 return 0;
3558}
3559
afbf21dc
YS
3560static int check_buffer_access(struct bpf_verifier_env *env,
3561 const struct bpf_reg_state *reg,
3562 int regno, int off, int size,
3563 bool zero_size_allowed,
3564 const char *buf_info,
3565 u32 *max_access)
3566{
3567 int err;
3568
3569 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3570 if (err)
3571 return err;
3572
3573 if (off + size > *max_access)
3574 *max_access = off + size;
3575
3576 return 0;
3577}
3578
3f50f132
JF
3579/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3580static void zext_32_to_64(struct bpf_reg_state *reg)
3581{
3582 reg->var_off = tnum_subreg(reg->var_off);
3583 __reg_assign_32_into_64(reg);
3584}
9df1c28b 3585
0c17d1d2
JH
3586/* truncate register to smaller size (in bytes)
3587 * must be called with size < BPF_REG_SIZE
3588 */
3589static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3590{
3591 u64 mask;
3592
3593 /* clear high bits in bit representation */
3594 reg->var_off = tnum_cast(reg->var_off, size);
3595
3596 /* fix arithmetic bounds */
3597 mask = ((u64)1 << (size * 8)) - 1;
3598 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3599 reg->umin_value &= mask;
3600 reg->umax_value &= mask;
3601 } else {
3602 reg->umin_value = 0;
3603 reg->umax_value = mask;
3604 }
3605 reg->smin_value = reg->umin_value;
3606 reg->smax_value = reg->umax_value;
3f50f132
JF
3607
3608 /* If size is smaller than 32bit register the 32bit register
3609 * values are also truncated so we push 64-bit bounds into
3610 * 32-bit bounds. Above were truncated < 32-bits already.
3611 */
3612 if (size >= 4)
3613 return;
3614 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3615}
3616
a23740ec
AN
3617static bool bpf_map_is_rdonly(const struct bpf_map *map)
3618{
3619 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3620}
3621
3622static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3623{
3624 void *ptr;
3625 u64 addr;
3626 int err;
3627
3628 err = map->ops->map_direct_value_addr(map, &addr, off);
3629 if (err)
3630 return err;
2dedd7d2 3631 ptr = (void *)(long)addr + off;
a23740ec
AN
3632
3633 switch (size) {
3634 case sizeof(u8):
3635 *val = (u64)*(u8 *)ptr;
3636 break;
3637 case sizeof(u16):
3638 *val = (u64)*(u16 *)ptr;
3639 break;
3640 case sizeof(u32):
3641 *val = (u64)*(u32 *)ptr;
3642 break;
3643 case sizeof(u64):
3644 *val = *(u64 *)ptr;
3645 break;
3646 default:
3647 return -EINVAL;
3648 }
3649 return 0;
3650}
3651
9e15db66
AS
3652static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3653 struct bpf_reg_state *regs,
3654 int regno, int off, int size,
3655 enum bpf_access_type atype,
3656 int value_regno)
3657{
3658 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3659 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3660 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3661 u32 btf_id;
3662 int ret;
3663
9e15db66
AS
3664 if (off < 0) {
3665 verbose(env,
3666 "R%d is ptr_%s invalid negative access: off=%d\n",
3667 regno, tname, off);
3668 return -EACCES;
3669 }
3670 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3671 char tn_buf[48];
3672
3673 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3674 verbose(env,
3675 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3676 regno, tname, off, tn_buf);
3677 return -EACCES;
3678 }
3679
27ae7997 3680 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3681 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3682 off, size, atype, &btf_id);
27ae7997
MKL
3683 } else {
3684 if (atype != BPF_READ) {
3685 verbose(env, "only read is supported\n");
3686 return -EACCES;
3687 }
3688
22dc4a0f
AN
3689 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3690 atype, &btf_id);
27ae7997
MKL
3691 }
3692
9e15db66
AS
3693 if (ret < 0)
3694 return ret;
3695
41c48f3a 3696 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3697 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3698
3699 return 0;
3700}
3701
3702static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3703 struct bpf_reg_state *regs,
3704 int regno, int off, int size,
3705 enum bpf_access_type atype,
3706 int value_regno)
3707{
3708 struct bpf_reg_state *reg = regs + regno;
3709 struct bpf_map *map = reg->map_ptr;
3710 const struct btf_type *t;
3711 const char *tname;
3712 u32 btf_id;
3713 int ret;
3714
3715 if (!btf_vmlinux) {
3716 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3717 return -ENOTSUPP;
3718 }
3719
3720 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3721 verbose(env, "map_ptr access not supported for map type %d\n",
3722 map->map_type);
3723 return -ENOTSUPP;
3724 }
3725
3726 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3727 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3728
3729 if (!env->allow_ptr_to_map_access) {
3730 verbose(env,
3731 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3732 tname);
3733 return -EPERM;
9e15db66 3734 }
27ae7997 3735
41c48f3a
AI
3736 if (off < 0) {
3737 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3738 regno, tname, off);
3739 return -EACCES;
3740 }
3741
3742 if (atype != BPF_READ) {
3743 verbose(env, "only read from %s is supported\n", tname);
3744 return -EACCES;
3745 }
3746
22dc4a0f 3747 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3748 if (ret < 0)
3749 return ret;
3750
3751 if (value_regno >= 0)
22dc4a0f 3752 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3753
9e15db66
AS
3754 return 0;
3755}
3756
01f810ac
AM
3757/* Check that the stack access at the given offset is within bounds. The
3758 * maximum valid offset is -1.
3759 *
3760 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3761 * -state->allocated_stack for reads.
3762 */
3763static int check_stack_slot_within_bounds(int off,
3764 struct bpf_func_state *state,
3765 enum bpf_access_type t)
3766{
3767 int min_valid_off;
3768
3769 if (t == BPF_WRITE)
3770 min_valid_off = -MAX_BPF_STACK;
3771 else
3772 min_valid_off = -state->allocated_stack;
3773
3774 if (off < min_valid_off || off > -1)
3775 return -EACCES;
3776 return 0;
3777}
3778
3779/* Check that the stack access at 'regno + off' falls within the maximum stack
3780 * bounds.
3781 *
3782 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3783 */
3784static int check_stack_access_within_bounds(
3785 struct bpf_verifier_env *env,
3786 int regno, int off, int access_size,
3787 enum stack_access_src src, enum bpf_access_type type)
3788{
3789 struct bpf_reg_state *regs = cur_regs(env);
3790 struct bpf_reg_state *reg = regs + regno;
3791 struct bpf_func_state *state = func(env, reg);
3792 int min_off, max_off;
3793 int err;
3794 char *err_extra;
3795
3796 if (src == ACCESS_HELPER)
3797 /* We don't know if helpers are reading or writing (or both). */
3798 err_extra = " indirect access to";
3799 else if (type == BPF_READ)
3800 err_extra = " read from";
3801 else
3802 err_extra = " write to";
3803
3804 if (tnum_is_const(reg->var_off)) {
3805 min_off = reg->var_off.value + off;
3806 if (access_size > 0)
3807 max_off = min_off + access_size - 1;
3808 else
3809 max_off = min_off;
3810 } else {
3811 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3812 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3813 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3814 err_extra, regno);
3815 return -EACCES;
3816 }
3817 min_off = reg->smin_value + off;
3818 if (access_size > 0)
3819 max_off = reg->smax_value + off + access_size - 1;
3820 else
3821 max_off = min_off;
3822 }
3823
3824 err = check_stack_slot_within_bounds(min_off, state, type);
3825 if (!err)
3826 err = check_stack_slot_within_bounds(max_off, state, type);
3827
3828 if (err) {
3829 if (tnum_is_const(reg->var_off)) {
3830 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3831 err_extra, regno, off, access_size);
3832 } else {
3833 char tn_buf[48];
3834
3835 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3836 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3837 err_extra, regno, tn_buf, access_size);
3838 }
3839 }
3840 return err;
3841}
41c48f3a 3842
17a52670
AS
3843/* check whether memory at (regno + off) is accessible for t = (read | write)
3844 * if t==write, value_regno is a register which value is stored into memory
3845 * if t==read, value_regno is a register which will receive the value from memory
3846 * if t==write && value_regno==-1, some unknown value is stored into memory
3847 * if t==read && value_regno==-1, don't care what we read from memory
3848 */
ca369602
DB
3849static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3850 int off, int bpf_size, enum bpf_access_type t,
3851 int value_regno, bool strict_alignment_once)
17a52670 3852{
638f5b90
AS
3853 struct bpf_reg_state *regs = cur_regs(env);
3854 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3855 struct bpf_func_state *state;
17a52670
AS
3856 int size, err = 0;
3857
3858 size = bpf_size_to_bytes(bpf_size);
3859 if (size < 0)
3860 return size;
3861
f1174f77 3862 /* alignment checks will add in reg->off themselves */
ca369602 3863 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3864 if (err)
3865 return err;
17a52670 3866
f1174f77
EC
3867 /* for access checks, reg->off is just part of off */
3868 off += reg->off;
3869
69c087ba
YS
3870 if (reg->type == PTR_TO_MAP_KEY) {
3871 if (t == BPF_WRITE) {
3872 verbose(env, "write to change key R%d not allowed\n", regno);
3873 return -EACCES;
3874 }
3875
3876 err = check_mem_region_access(env, regno, off, size,
3877 reg->map_ptr->key_size, false);
3878 if (err)
3879 return err;
3880 if (value_regno >= 0)
3881 mark_reg_unknown(env, regs, value_regno);
3882 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3883 if (t == BPF_WRITE && value_regno >= 0 &&
3884 is_pointer_value(env, value_regno)) {
61bd5218 3885 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3886 return -EACCES;
3887 }
591fe988
DB
3888 err = check_map_access_type(env, regno, off, size, t);
3889 if (err)
3890 return err;
9fd29c08 3891 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3892 if (!err && t == BPF_READ && value_regno >= 0) {
3893 struct bpf_map *map = reg->map_ptr;
3894
3895 /* if map is read-only, track its contents as scalars */
3896 if (tnum_is_const(reg->var_off) &&
3897 bpf_map_is_rdonly(map) &&
3898 map->ops->map_direct_value_addr) {
3899 int map_off = off + reg->var_off.value;
3900 u64 val = 0;
3901
3902 err = bpf_map_direct_read(map, map_off, size,
3903 &val);
3904 if (err)
3905 return err;
3906
3907 regs[value_regno].type = SCALAR_VALUE;
3908 __mark_reg_known(&regs[value_regno], val);
3909 } else {
3910 mark_reg_unknown(env, regs, value_regno);
3911 }
3912 }
457f4436
AN
3913 } else if (reg->type == PTR_TO_MEM) {
3914 if (t == BPF_WRITE && value_regno >= 0 &&
3915 is_pointer_value(env, value_regno)) {
3916 verbose(env, "R%d leaks addr into mem\n", value_regno);
3917 return -EACCES;
3918 }
3919 err = check_mem_region_access(env, regno, off, size,
3920 reg->mem_size, false);
3921 if (!err && t == BPF_READ && value_regno >= 0)
3922 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3923 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3924 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 3925 struct btf *btf = NULL;
9e15db66 3926 u32 btf_id = 0;
19de99f7 3927
1be7f75d
AS
3928 if (t == BPF_WRITE && value_regno >= 0 &&
3929 is_pointer_value(env, value_regno)) {
61bd5218 3930 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3931 return -EACCES;
3932 }
f1174f77 3933
58990d1f
DB
3934 err = check_ctx_reg(env, reg, regno);
3935 if (err < 0)
3936 return err;
3937
22dc4a0f 3938 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
3939 if (err)
3940 verbose_linfo(env, insn_idx, "; ");
969bf05e 3941 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3942 /* ctx access returns either a scalar, or a
de8f3a83
DB
3943 * PTR_TO_PACKET[_META,_END]. In the latter
3944 * case, we know the offset is zero.
f1174f77 3945 */
46f8bc92 3946 if (reg_type == SCALAR_VALUE) {
638f5b90 3947 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3948 } else {
638f5b90 3949 mark_reg_known_zero(env, regs,
61bd5218 3950 value_regno);
46f8bc92
MKL
3951 if (reg_type_may_be_null(reg_type))
3952 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3953 /* A load of ctx field could have different
3954 * actual load size with the one encoded in the
3955 * insn. When the dst is PTR, it is for sure not
3956 * a sub-register.
3957 */
3958 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 3959 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
3960 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3961 regs[value_regno].btf = btf;
9e15db66 3962 regs[value_regno].btf_id = btf_id;
22dc4a0f 3963 }
46f8bc92 3964 }
638f5b90 3965 regs[value_regno].type = reg_type;
969bf05e 3966 }
17a52670 3967
f1174f77 3968 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
3969 /* Basic bounds checks. */
3970 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
3971 if (err)
3972 return err;
8726679a 3973
f4d7e40a
AS
3974 state = func(env, reg);
3975 err = update_stack_depth(env, state, off);
3976 if (err)
3977 return err;
8726679a 3978
01f810ac
AM
3979 if (t == BPF_READ)
3980 err = check_stack_read(env, regno, off, size,
61bd5218 3981 value_regno);
01f810ac
AM
3982 else
3983 err = check_stack_write(env, regno, off, size,
3984 value_regno, insn_idx);
de8f3a83 3985 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 3986 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 3987 verbose(env, "cannot write into packet\n");
969bf05e
AS
3988 return -EACCES;
3989 }
4acf6c0b
BB
3990 if (t == BPF_WRITE && value_regno >= 0 &&
3991 is_pointer_value(env, value_regno)) {
61bd5218
JK
3992 verbose(env, "R%d leaks addr into packet\n",
3993 value_regno);
4acf6c0b
BB
3994 return -EACCES;
3995 }
9fd29c08 3996 err = check_packet_access(env, regno, off, size, false);
969bf05e 3997 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 3998 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
3999 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4000 if (t == BPF_WRITE && value_regno >= 0 &&
4001 is_pointer_value(env, value_regno)) {
4002 verbose(env, "R%d leaks addr into flow keys\n",
4003 value_regno);
4004 return -EACCES;
4005 }
4006
4007 err = check_flow_keys_access(env, off, size);
4008 if (!err && t == BPF_READ && value_regno >= 0)
4009 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4010 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4011 if (t == BPF_WRITE) {
46f8bc92
MKL
4012 verbose(env, "R%d cannot write into %s\n",
4013 regno, reg_type_str[reg->type]);
c64b7983
JS
4014 return -EACCES;
4015 }
5f456649 4016 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4017 if (!err && value_regno >= 0)
4018 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4019 } else if (reg->type == PTR_TO_TP_BUFFER) {
4020 err = check_tp_buffer_access(env, reg, regno, off, size);
4021 if (!err && t == BPF_READ && value_regno >= 0)
4022 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
4023 } else if (reg->type == PTR_TO_BTF_ID) {
4024 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4025 value_regno);
41c48f3a
AI
4026 } else if (reg->type == CONST_PTR_TO_MAP) {
4027 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4028 value_regno);
afbf21dc
YS
4029 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4030 if (t == BPF_WRITE) {
4031 verbose(env, "R%d cannot write into %s\n",
4032 regno, reg_type_str[reg->type]);
4033 return -EACCES;
4034 }
f6dfbe31
CIK
4035 err = check_buffer_access(env, reg, regno, off, size, false,
4036 "rdonly",
afbf21dc
YS
4037 &env->prog->aux->max_rdonly_access);
4038 if (!err && value_regno >= 0)
4039 mark_reg_unknown(env, regs, value_regno);
4040 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
4041 err = check_buffer_access(env, reg, regno, off, size, false,
4042 "rdwr",
afbf21dc
YS
4043 &env->prog->aux->max_rdwr_access);
4044 if (!err && t == BPF_READ && value_regno >= 0)
4045 mark_reg_unknown(env, regs, value_regno);
17a52670 4046 } else {
61bd5218
JK
4047 verbose(env, "R%d invalid mem access '%s'\n", regno,
4048 reg_type_str[reg->type]);
17a52670
AS
4049 return -EACCES;
4050 }
969bf05e 4051
f1174f77 4052 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4053 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4054 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4055 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4056 }
17a52670
AS
4057 return err;
4058}
4059
91c960b0 4060static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4061{
5ffa2550 4062 int load_reg;
17a52670
AS
4063 int err;
4064
5ca419f2
BJ
4065 switch (insn->imm) {
4066 case BPF_ADD:
4067 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4068 case BPF_AND:
4069 case BPF_AND | BPF_FETCH:
4070 case BPF_OR:
4071 case BPF_OR | BPF_FETCH:
4072 case BPF_XOR:
4073 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4074 case BPF_XCHG:
4075 case BPF_CMPXCHG:
5ca419f2
BJ
4076 break;
4077 default:
91c960b0
BJ
4078 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4079 return -EINVAL;
4080 }
4081
4082 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4083 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4084 return -EINVAL;
4085 }
4086
4087 /* check src1 operand */
dc503a8a 4088 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4089 if (err)
4090 return err;
4091
4092 /* check src2 operand */
dc503a8a 4093 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4094 if (err)
4095 return err;
4096
5ffa2550
BJ
4097 if (insn->imm == BPF_CMPXCHG) {
4098 /* Check comparison of R0 with memory location */
4099 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4100 if (err)
4101 return err;
4102 }
4103
6bdf6abc 4104 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4105 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4106 return -EACCES;
4107 }
4108
ca369602 4109 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4110 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4111 is_flow_key_reg(env, insn->dst_reg) ||
4112 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4113 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f
DB
4114 insn->dst_reg,
4115 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
4116 return -EACCES;
4117 }
4118
37086bfd
BJ
4119 if (insn->imm & BPF_FETCH) {
4120 if (insn->imm == BPF_CMPXCHG)
4121 load_reg = BPF_REG_0;
4122 else
4123 load_reg = insn->src_reg;
4124
4125 /* check and record load of old value */
4126 err = check_reg_arg(env, load_reg, DST_OP);
4127 if (err)
4128 return err;
4129 } else {
4130 /* This instruction accesses a memory location but doesn't
4131 * actually load it into a register.
4132 */
4133 load_reg = -1;
4134 }
4135
91c960b0 4136 /* check whether we can read the memory */
31fd8581 4137 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
37086bfd 4138 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
17a52670
AS
4139 if (err)
4140 return err;
4141
91c960b0 4142 /* check whether we can write into the same memory */
5ca419f2
BJ
4143 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4144 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4145 if (err)
4146 return err;
4147
5ca419f2 4148 return 0;
17a52670
AS
4149}
4150
01f810ac
AM
4151/* When register 'regno' is used to read the stack (either directly or through
4152 * a helper function) make sure that it's within stack boundary and, depending
4153 * on the access type, that all elements of the stack are initialized.
4154 *
4155 * 'off' includes 'regno->off', but not its dynamic part (if any).
4156 *
4157 * All registers that have been spilled on the stack in the slots within the
4158 * read offsets are marked as read.
4159 */
4160static int check_stack_range_initialized(
4161 struct bpf_verifier_env *env, int regno, int off,
4162 int access_size, bool zero_size_allowed,
4163 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4164{
4165 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4166 struct bpf_func_state *state = func(env, reg);
4167 int err, min_off, max_off, i, j, slot, spi;
4168 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4169 enum bpf_access_type bounds_check_type;
4170 /* Some accesses can write anything into the stack, others are
4171 * read-only.
4172 */
4173 bool clobber = false;
2011fccf 4174
01f810ac
AM
4175 if (access_size == 0 && !zero_size_allowed) {
4176 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4177 return -EACCES;
4178 }
2011fccf 4179
01f810ac
AM
4180 if (type == ACCESS_HELPER) {
4181 /* The bounds checks for writes are more permissive than for
4182 * reads. However, if raw_mode is not set, we'll do extra
4183 * checks below.
4184 */
4185 bounds_check_type = BPF_WRITE;
4186 clobber = true;
4187 } else {
4188 bounds_check_type = BPF_READ;
4189 }
4190 err = check_stack_access_within_bounds(env, regno, off, access_size,
4191 type, bounds_check_type);
4192 if (err)
4193 return err;
4194
17a52670 4195
2011fccf 4196 if (tnum_is_const(reg->var_off)) {
01f810ac 4197 min_off = max_off = reg->var_off.value + off;
2011fccf 4198 } else {
088ec26d
AI
4199 /* Variable offset is prohibited for unprivileged mode for
4200 * simplicity since it requires corresponding support in
4201 * Spectre masking for stack ALU.
4202 * See also retrieve_ptr_limit().
4203 */
2c78ee89 4204 if (!env->bypass_spec_v1) {
088ec26d 4205 char tn_buf[48];
f1174f77 4206
088ec26d 4207 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4208 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4209 regno, err_extra, tn_buf);
088ec26d
AI
4210 return -EACCES;
4211 }
f2bcd05e
AI
4212 /* Only initialized buffer on stack is allowed to be accessed
4213 * with variable offset. With uninitialized buffer it's hard to
4214 * guarantee that whole memory is marked as initialized on
4215 * helper return since specific bounds are unknown what may
4216 * cause uninitialized stack leaking.
4217 */
4218 if (meta && meta->raw_mode)
4219 meta = NULL;
4220
01f810ac
AM
4221 min_off = reg->smin_value + off;
4222 max_off = reg->smax_value + off;
17a52670
AS
4223 }
4224
435faee1
DB
4225 if (meta && meta->raw_mode) {
4226 meta->access_size = access_size;
4227 meta->regno = regno;
4228 return 0;
4229 }
4230
2011fccf 4231 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4232 u8 *stype;
4233
2011fccf 4234 slot = -i - 1;
638f5b90 4235 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4236 if (state->allocated_stack <= slot)
4237 goto err;
4238 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4239 if (*stype == STACK_MISC)
4240 goto mark;
4241 if (*stype == STACK_ZERO) {
01f810ac
AM
4242 if (clobber) {
4243 /* helper can write anything into the stack */
4244 *stype = STACK_MISC;
4245 }
cc2b14d5 4246 goto mark;
17a52670 4247 }
1d68f22b
YS
4248
4249 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4250 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4251 goto mark;
4252
f7cf25b2 4253 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4254 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4255 env->allow_ptr_leaks)) {
01f810ac
AM
4256 if (clobber) {
4257 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4258 for (j = 0; j < BPF_REG_SIZE; j++)
4259 state->stack[spi].slot_type[j] = STACK_MISC;
4260 }
f7cf25b2
AS
4261 goto mark;
4262 }
4263
cc2b14d5 4264err:
2011fccf 4265 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4266 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4267 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4268 } else {
4269 char tn_buf[48];
4270
4271 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4272 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4273 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4274 }
cc2b14d5
AS
4275 return -EACCES;
4276mark:
4277 /* reading any byte out of 8-byte 'spill_slot' will cause
4278 * the whole slot to be marked as 'read'
4279 */
679c782d 4280 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4281 state->stack[spi].spilled_ptr.parent,
4282 REG_LIVE_READ64);
17a52670 4283 }
2011fccf 4284 return update_stack_depth(env, state, min_off);
17a52670
AS
4285}
4286
06c1c049
GB
4287static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4288 int access_size, bool zero_size_allowed,
4289 struct bpf_call_arg_meta *meta)
4290{
638f5b90 4291 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4292
f1174f77 4293 switch (reg->type) {
06c1c049 4294 case PTR_TO_PACKET:
de8f3a83 4295 case PTR_TO_PACKET_META:
9fd29c08
YS
4296 return check_packet_access(env, regno, reg->off, access_size,
4297 zero_size_allowed);
69c087ba
YS
4298 case PTR_TO_MAP_KEY:
4299 return check_mem_region_access(env, regno, reg->off, access_size,
4300 reg->map_ptr->key_size, false);
06c1c049 4301 case PTR_TO_MAP_VALUE:
591fe988
DB
4302 if (check_map_access_type(env, regno, reg->off, access_size,
4303 meta && meta->raw_mode ? BPF_WRITE :
4304 BPF_READ))
4305 return -EACCES;
9fd29c08
YS
4306 return check_map_access(env, regno, reg->off, access_size,
4307 zero_size_allowed);
457f4436
AN
4308 case PTR_TO_MEM:
4309 return check_mem_region_access(env, regno, reg->off,
4310 access_size, reg->mem_size,
4311 zero_size_allowed);
afbf21dc
YS
4312 case PTR_TO_RDONLY_BUF:
4313 if (meta && meta->raw_mode)
4314 return -EACCES;
4315 return check_buffer_access(env, reg, regno, reg->off,
4316 access_size, zero_size_allowed,
4317 "rdonly",
4318 &env->prog->aux->max_rdonly_access);
4319 case PTR_TO_RDWR_BUF:
4320 return check_buffer_access(env, reg, regno, reg->off,
4321 access_size, zero_size_allowed,
4322 "rdwr",
4323 &env->prog->aux->max_rdwr_access);
0d004c02 4324 case PTR_TO_STACK:
01f810ac
AM
4325 return check_stack_range_initialized(
4326 env,
4327 regno, reg->off, access_size,
4328 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4329 default: /* scalar_value or invalid ptr */
4330 /* Allow zero-byte read from NULL, regardless of pointer type */
4331 if (zero_size_allowed && access_size == 0 &&
4332 register_is_null(reg))
4333 return 0;
4334
4335 verbose(env, "R%d type=%s expected=%s\n", regno,
4336 reg_type_str[reg->type],
4337 reg_type_str[PTR_TO_STACK]);
4338 return -EACCES;
06c1c049
GB
4339 }
4340}
4341
e5069b9c
DB
4342int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4343 u32 regno, u32 mem_size)
4344{
4345 if (register_is_null(reg))
4346 return 0;
4347
4348 if (reg_type_may_be_null(reg->type)) {
4349 /* Assuming that the register contains a value check if the memory
4350 * access is safe. Temporarily save and restore the register's state as
4351 * the conversion shouldn't be visible to a caller.
4352 */
4353 const struct bpf_reg_state saved_reg = *reg;
4354 int rv;
4355
4356 mark_ptr_not_null_reg(reg);
4357 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4358 *reg = saved_reg;
4359 return rv;
4360 }
4361
4362 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4363}
4364
d83525ca
AS
4365/* Implementation details:
4366 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4367 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4368 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4369 * value_or_null->value transition, since the verifier only cares about
4370 * the range of access to valid map value pointer and doesn't care about actual
4371 * address of the map element.
4372 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4373 * reg->id > 0 after value_or_null->value transition. By doing so
4374 * two bpf_map_lookups will be considered two different pointers that
4375 * point to different bpf_spin_locks.
4376 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4377 * dead-locks.
4378 * Since only one bpf_spin_lock is allowed the checks are simpler than
4379 * reg_is_refcounted() logic. The verifier needs to remember only
4380 * one spin_lock instead of array of acquired_refs.
4381 * cur_state->active_spin_lock remembers which map value element got locked
4382 * and clears it after bpf_spin_unlock.
4383 */
4384static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4385 bool is_lock)
4386{
4387 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4388 struct bpf_verifier_state *cur = env->cur_state;
4389 bool is_const = tnum_is_const(reg->var_off);
4390 struct bpf_map *map = reg->map_ptr;
4391 u64 val = reg->var_off.value;
4392
d83525ca
AS
4393 if (!is_const) {
4394 verbose(env,
4395 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4396 regno);
4397 return -EINVAL;
4398 }
4399 if (!map->btf) {
4400 verbose(env,
4401 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4402 map->name);
4403 return -EINVAL;
4404 }
4405 if (!map_value_has_spin_lock(map)) {
4406 if (map->spin_lock_off == -E2BIG)
4407 verbose(env,
4408 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4409 map->name);
4410 else if (map->spin_lock_off == -ENOENT)
4411 verbose(env,
4412 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4413 map->name);
4414 else
4415 verbose(env,
4416 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4417 map->name);
4418 return -EINVAL;
4419 }
4420 if (map->spin_lock_off != val + reg->off) {
4421 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4422 val + reg->off);
4423 return -EINVAL;
4424 }
4425 if (is_lock) {
4426 if (cur->active_spin_lock) {
4427 verbose(env,
4428 "Locking two bpf_spin_locks are not allowed\n");
4429 return -EINVAL;
4430 }
4431 cur->active_spin_lock = reg->id;
4432 } else {
4433 if (!cur->active_spin_lock) {
4434 verbose(env, "bpf_spin_unlock without taking a lock\n");
4435 return -EINVAL;
4436 }
4437 if (cur->active_spin_lock != reg->id) {
4438 verbose(env, "bpf_spin_unlock of different lock\n");
4439 return -EINVAL;
4440 }
4441 cur->active_spin_lock = 0;
4442 }
4443 return 0;
4444}
4445
90133415
DB
4446static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4447{
4448 return type == ARG_PTR_TO_MEM ||
4449 type == ARG_PTR_TO_MEM_OR_NULL ||
4450 type == ARG_PTR_TO_UNINIT_MEM;
4451}
4452
4453static bool arg_type_is_mem_size(enum bpf_arg_type type)
4454{
4455 return type == ARG_CONST_SIZE ||
4456 type == ARG_CONST_SIZE_OR_ZERO;
4457}
4458
457f4436
AN
4459static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4460{
4461 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4462}
4463
57c3bb72
AI
4464static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4465{
4466 return type == ARG_PTR_TO_INT ||
4467 type == ARG_PTR_TO_LONG;
4468}
4469
4470static int int_ptr_type_to_size(enum bpf_arg_type type)
4471{
4472 if (type == ARG_PTR_TO_INT)
4473 return sizeof(u32);
4474 else if (type == ARG_PTR_TO_LONG)
4475 return sizeof(u64);
4476
4477 return -EINVAL;
4478}
4479
912f442c
LB
4480static int resolve_map_arg_type(struct bpf_verifier_env *env,
4481 const struct bpf_call_arg_meta *meta,
4482 enum bpf_arg_type *arg_type)
4483{
4484 if (!meta->map_ptr) {
4485 /* kernel subsystem misconfigured verifier */
4486 verbose(env, "invalid map_ptr to access map->type\n");
4487 return -EACCES;
4488 }
4489
4490 switch (meta->map_ptr->map_type) {
4491 case BPF_MAP_TYPE_SOCKMAP:
4492 case BPF_MAP_TYPE_SOCKHASH:
4493 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4494 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4495 } else {
4496 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4497 return -EINVAL;
4498 }
4499 break;
4500
4501 default:
4502 break;
4503 }
4504 return 0;
4505}
4506
f79e7ea5
LB
4507struct bpf_reg_types {
4508 const enum bpf_reg_type types[10];
1df8f55a 4509 u32 *btf_id;
f79e7ea5
LB
4510};
4511
4512static const struct bpf_reg_types map_key_value_types = {
4513 .types = {
4514 PTR_TO_STACK,
4515 PTR_TO_PACKET,
4516 PTR_TO_PACKET_META,
69c087ba 4517 PTR_TO_MAP_KEY,
f79e7ea5
LB
4518 PTR_TO_MAP_VALUE,
4519 },
4520};
4521
4522static const struct bpf_reg_types sock_types = {
4523 .types = {
4524 PTR_TO_SOCK_COMMON,
4525 PTR_TO_SOCKET,
4526 PTR_TO_TCP_SOCK,
4527 PTR_TO_XDP_SOCK,
4528 },
4529};
4530
49a2a4d4 4531#ifdef CONFIG_NET
1df8f55a
MKL
4532static const struct bpf_reg_types btf_id_sock_common_types = {
4533 .types = {
4534 PTR_TO_SOCK_COMMON,
4535 PTR_TO_SOCKET,
4536 PTR_TO_TCP_SOCK,
4537 PTR_TO_XDP_SOCK,
4538 PTR_TO_BTF_ID,
4539 },
4540 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4541};
49a2a4d4 4542#endif
1df8f55a 4543
f79e7ea5
LB
4544static const struct bpf_reg_types mem_types = {
4545 .types = {
4546 PTR_TO_STACK,
4547 PTR_TO_PACKET,
4548 PTR_TO_PACKET_META,
69c087ba 4549 PTR_TO_MAP_KEY,
f79e7ea5
LB
4550 PTR_TO_MAP_VALUE,
4551 PTR_TO_MEM,
4552 PTR_TO_RDONLY_BUF,
4553 PTR_TO_RDWR_BUF,
4554 },
4555};
4556
4557static const struct bpf_reg_types int_ptr_types = {
4558 .types = {
4559 PTR_TO_STACK,
4560 PTR_TO_PACKET,
4561 PTR_TO_PACKET_META,
69c087ba 4562 PTR_TO_MAP_KEY,
f79e7ea5
LB
4563 PTR_TO_MAP_VALUE,
4564 },
4565};
4566
4567static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4568static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4569static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4570static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4571static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4572static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4573static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4574static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
69c087ba
YS
4575static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4576static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
f79e7ea5 4577
0789e13b 4578static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4579 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4580 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4581 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4582 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4583 [ARG_CONST_SIZE] = &scalar_types,
4584 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4585 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4586 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4587 [ARG_PTR_TO_CTX] = &context_types,
4588 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4589 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4590#ifdef CONFIG_NET
1df8f55a 4591 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4592#endif
f79e7ea5
LB
4593 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4594 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4595 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4596 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4597 [ARG_PTR_TO_MEM] = &mem_types,
4598 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4599 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4600 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4601 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4602 [ARG_PTR_TO_INT] = &int_ptr_types,
4603 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4604 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba
YS
4605 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4606 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
f79e7ea5
LB
4607};
4608
4609static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4610 enum bpf_arg_type arg_type,
4611 const u32 *arg_btf_id)
f79e7ea5
LB
4612{
4613 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4614 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4615 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4616 int i, j;
4617
a968d5e2
MKL
4618 compatible = compatible_reg_types[arg_type];
4619 if (!compatible) {
4620 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4621 return -EFAULT;
4622 }
4623
f79e7ea5
LB
4624 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4625 expected = compatible->types[i];
4626 if (expected == NOT_INIT)
4627 break;
4628
4629 if (type == expected)
a968d5e2 4630 goto found;
f79e7ea5
LB
4631 }
4632
4633 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4634 for (j = 0; j + 1 < i; j++)
4635 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4636 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4637 return -EACCES;
a968d5e2
MKL
4638
4639found:
4640 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4641 if (!arg_btf_id) {
4642 if (!compatible->btf_id) {
4643 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4644 return -EFAULT;
4645 }
4646 arg_btf_id = compatible->btf_id;
4647 }
4648
22dc4a0f
AN
4649 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4650 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4651 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4652 regno, kernel_type_name(reg->btf, reg->btf_id),
4653 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4654 return -EACCES;
4655 }
4656
4657 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4658 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4659 regno);
4660 return -EACCES;
4661 }
4662 }
4663
4664 return 0;
f79e7ea5
LB
4665}
4666
af7ec138
YS
4667static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4668 struct bpf_call_arg_meta *meta,
4669 const struct bpf_func_proto *fn)
17a52670 4670{
af7ec138 4671 u32 regno = BPF_REG_1 + arg;
638f5b90 4672 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4673 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4674 enum bpf_reg_type type = reg->type;
17a52670
AS
4675 int err = 0;
4676
80f1d68c 4677 if (arg_type == ARG_DONTCARE)
17a52670
AS
4678 return 0;
4679
dc503a8a
EC
4680 err = check_reg_arg(env, regno, SRC_OP);
4681 if (err)
4682 return err;
17a52670 4683
1be7f75d
AS
4684 if (arg_type == ARG_ANYTHING) {
4685 if (is_pointer_value(env, regno)) {
61bd5218
JK
4686 verbose(env, "R%d leaks addr into helper function\n",
4687 regno);
1be7f75d
AS
4688 return -EACCES;
4689 }
80f1d68c 4690 return 0;
1be7f75d 4691 }
80f1d68c 4692
de8f3a83 4693 if (type_is_pkt_pointer(type) &&
3a0af8fd 4694 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4695 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4696 return -EACCES;
4697 }
4698
912f442c
LB
4699 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4700 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4701 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4702 err = resolve_map_arg_type(env, meta, &arg_type);
4703 if (err)
4704 return err;
4705 }
4706
fd1b0d60
LB
4707 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4708 /* A NULL register has a SCALAR_VALUE type, so skip
4709 * type checking.
4710 */
4711 goto skip_type_check;
4712
a968d5e2 4713 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4714 if (err)
4715 return err;
4716
a968d5e2 4717 if (type == PTR_TO_CTX) {
feec7040
LB
4718 err = check_ctx_reg(env, reg, regno);
4719 if (err < 0)
4720 return err;
d7b9454a
LB
4721 }
4722
fd1b0d60 4723skip_type_check:
02f7c958 4724 if (reg->ref_obj_id) {
457f4436
AN
4725 if (meta->ref_obj_id) {
4726 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4727 regno, reg->ref_obj_id,
4728 meta->ref_obj_id);
4729 return -EFAULT;
4730 }
4731 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4732 }
4733
17a52670
AS
4734 if (arg_type == ARG_CONST_MAP_PTR) {
4735 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4736 meta->map_ptr = reg->map_ptr;
17a52670
AS
4737 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4738 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4739 * check that [key, key + map->key_size) are within
4740 * stack limits and initialized
4741 */
33ff9823 4742 if (!meta->map_ptr) {
17a52670
AS
4743 /* in function declaration map_ptr must come before
4744 * map_key, so that it's verified and known before
4745 * we have to check map_key here. Otherwise it means
4746 * that kernel subsystem misconfigured verifier
4747 */
61bd5218 4748 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4749 return -EACCES;
4750 }
d71962f3
PC
4751 err = check_helper_mem_access(env, regno,
4752 meta->map_ptr->key_size, false,
4753 NULL);
2ea864c5 4754 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4755 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4756 !register_is_null(reg)) ||
2ea864c5 4757 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4758 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4759 * check [value, value + map->value_size) validity
4760 */
33ff9823 4761 if (!meta->map_ptr) {
17a52670 4762 /* kernel subsystem misconfigured verifier */
61bd5218 4763 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4764 return -EACCES;
4765 }
2ea864c5 4766 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4767 err = check_helper_mem_access(env, regno,
4768 meta->map_ptr->value_size, false,
2ea864c5 4769 meta);
eaa6bcb7
HL
4770 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4771 if (!reg->btf_id) {
4772 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4773 return -EACCES;
4774 }
22dc4a0f 4775 meta->ret_btf = reg->btf;
eaa6bcb7 4776 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4777 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4778 if (meta->func_id == BPF_FUNC_spin_lock) {
4779 if (process_spin_lock(env, regno, true))
4780 return -EACCES;
4781 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4782 if (process_spin_lock(env, regno, false))
4783 return -EACCES;
4784 } else {
4785 verbose(env, "verifier internal error\n");
4786 return -EFAULT;
4787 }
69c087ba
YS
4788 } else if (arg_type == ARG_PTR_TO_FUNC) {
4789 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
4790 } else if (arg_type_is_mem_ptr(arg_type)) {
4791 /* The access to this pointer is only checked when we hit the
4792 * next is_mem_size argument below.
4793 */
4794 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 4795 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4796 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4797
10060503
JF
4798 /* This is used to refine r0 return value bounds for helpers
4799 * that enforce this value as an upper bound on return values.
4800 * See do_refine_retval_range() for helpers that can refine
4801 * the return value. C type of helper is u32 so we pull register
4802 * bound from umax_value however, if negative verifier errors
4803 * out. Only upper bounds can be learned because retval is an
4804 * int type and negative retvals are allowed.
849fa506 4805 */
10060503 4806 meta->msize_max_value = reg->umax_value;
849fa506 4807
f1174f77
EC
4808 /* The register is SCALAR_VALUE; the access check
4809 * happens using its boundaries.
06c1c049 4810 */
f1174f77 4811 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4812 /* For unprivileged variable accesses, disable raw
4813 * mode so that the program is required to
4814 * initialize all the memory that the helper could
4815 * just partially fill up.
4816 */
4817 meta = NULL;
4818
b03c9f9f 4819 if (reg->smin_value < 0) {
61bd5218 4820 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4821 regno);
4822 return -EACCES;
4823 }
06c1c049 4824
b03c9f9f 4825 if (reg->umin_value == 0) {
f1174f77
EC
4826 err = check_helper_mem_access(env, regno - 1, 0,
4827 zero_size_allowed,
4828 meta);
06c1c049
GB
4829 if (err)
4830 return err;
06c1c049 4831 }
f1174f77 4832
b03c9f9f 4833 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4834 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4835 regno);
4836 return -EACCES;
4837 }
4838 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4839 reg->umax_value,
f1174f77 4840 zero_size_allowed, meta);
b5dc0163
AS
4841 if (!err)
4842 err = mark_chain_precision(env, regno);
457f4436
AN
4843 } else if (arg_type_is_alloc_size(arg_type)) {
4844 if (!tnum_is_const(reg->var_off)) {
28a8add6 4845 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
4846 regno);
4847 return -EACCES;
4848 }
4849 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4850 } else if (arg_type_is_int_ptr(arg_type)) {
4851 int size = int_ptr_type_to_size(arg_type);
4852
4853 err = check_helper_mem_access(env, regno, size, false, meta);
4854 if (err)
4855 return err;
4856 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4857 }
4858
4859 return err;
4860}
4861
0126240f
LB
4862static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4863{
4864 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4865 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4866
4867 if (func_id != BPF_FUNC_map_update_elem)
4868 return false;
4869
4870 /* It's not possible to get access to a locked struct sock in these
4871 * contexts, so updating is safe.
4872 */
4873 switch (type) {
4874 case BPF_PROG_TYPE_TRACING:
4875 if (eatype == BPF_TRACE_ITER)
4876 return true;
4877 break;
4878 case BPF_PROG_TYPE_SOCKET_FILTER:
4879 case BPF_PROG_TYPE_SCHED_CLS:
4880 case BPF_PROG_TYPE_SCHED_ACT:
4881 case BPF_PROG_TYPE_XDP:
4882 case BPF_PROG_TYPE_SK_REUSEPORT:
4883 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4884 case BPF_PROG_TYPE_SK_LOOKUP:
4885 return true;
4886 default:
4887 break;
4888 }
4889
4890 verbose(env, "cannot update sockmap in this context\n");
4891 return false;
4892}
4893
e411901c
MF
4894static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4895{
4896 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4897}
4898
61bd5218
JK
4899static int check_map_func_compatibility(struct bpf_verifier_env *env,
4900 struct bpf_map *map, int func_id)
35578d79 4901{
35578d79
KX
4902 if (!map)
4903 return 0;
4904
6aff67c8
AS
4905 /* We need a two way check, first is from map perspective ... */
4906 switch (map->map_type) {
4907 case BPF_MAP_TYPE_PROG_ARRAY:
4908 if (func_id != BPF_FUNC_tail_call)
4909 goto error;
4910 break;
4911 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4912 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4913 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4914 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4915 func_id != BPF_FUNC_perf_event_read_value &&
4916 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4917 goto error;
4918 break;
457f4436
AN
4919 case BPF_MAP_TYPE_RINGBUF:
4920 if (func_id != BPF_FUNC_ringbuf_output &&
4921 func_id != BPF_FUNC_ringbuf_reserve &&
4922 func_id != BPF_FUNC_ringbuf_submit &&
4923 func_id != BPF_FUNC_ringbuf_discard &&
4924 func_id != BPF_FUNC_ringbuf_query)
4925 goto error;
4926 break;
6aff67c8
AS
4927 case BPF_MAP_TYPE_STACK_TRACE:
4928 if (func_id != BPF_FUNC_get_stackid)
4929 goto error;
4930 break;
4ed8ec52 4931 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4932 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4933 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4934 goto error;
4935 break;
cd339431 4936 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4937 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4938 if (func_id != BPF_FUNC_get_local_storage)
4939 goto error;
4940 break;
546ac1ff 4941 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4942 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4943 if (func_id != BPF_FUNC_redirect_map &&
4944 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4945 goto error;
4946 break;
fbfc504a
BT
4947 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4948 * appear.
4949 */
6710e112
JDB
4950 case BPF_MAP_TYPE_CPUMAP:
4951 if (func_id != BPF_FUNC_redirect_map)
4952 goto error;
4953 break;
fada7fdc
JL
4954 case BPF_MAP_TYPE_XSKMAP:
4955 if (func_id != BPF_FUNC_redirect_map &&
4956 func_id != BPF_FUNC_map_lookup_elem)
4957 goto error;
4958 break;
56f668df 4959 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4960 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4961 if (func_id != BPF_FUNC_map_lookup_elem)
4962 goto error;
16a43625 4963 break;
174a79ff
JF
4964 case BPF_MAP_TYPE_SOCKMAP:
4965 if (func_id != BPF_FUNC_sk_redirect_map &&
4966 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4967 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4968 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4969 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4970 func_id != BPF_FUNC_map_lookup_elem &&
4971 !may_update_sockmap(env, func_id))
174a79ff
JF
4972 goto error;
4973 break;
81110384
JF
4974 case BPF_MAP_TYPE_SOCKHASH:
4975 if (func_id != BPF_FUNC_sk_redirect_hash &&
4976 func_id != BPF_FUNC_sock_hash_update &&
4977 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4978 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 4979 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4980 func_id != BPF_FUNC_map_lookup_elem &&
4981 !may_update_sockmap(env, func_id))
81110384
JF
4982 goto error;
4983 break;
2dbb9b9e
MKL
4984 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4985 if (func_id != BPF_FUNC_sk_select_reuseport)
4986 goto error;
4987 break;
f1a2e44a
MV
4988 case BPF_MAP_TYPE_QUEUE:
4989 case BPF_MAP_TYPE_STACK:
4990 if (func_id != BPF_FUNC_map_peek_elem &&
4991 func_id != BPF_FUNC_map_pop_elem &&
4992 func_id != BPF_FUNC_map_push_elem)
4993 goto error;
4994 break;
6ac99e8f
MKL
4995 case BPF_MAP_TYPE_SK_STORAGE:
4996 if (func_id != BPF_FUNC_sk_storage_get &&
4997 func_id != BPF_FUNC_sk_storage_delete)
4998 goto error;
4999 break;
8ea63684
KS
5000 case BPF_MAP_TYPE_INODE_STORAGE:
5001 if (func_id != BPF_FUNC_inode_storage_get &&
5002 func_id != BPF_FUNC_inode_storage_delete)
5003 goto error;
5004 break;
4cf1bc1f
KS
5005 case BPF_MAP_TYPE_TASK_STORAGE:
5006 if (func_id != BPF_FUNC_task_storage_get &&
5007 func_id != BPF_FUNC_task_storage_delete)
5008 goto error;
5009 break;
6aff67c8
AS
5010 default:
5011 break;
5012 }
5013
5014 /* ... and second from the function itself. */
5015 switch (func_id) {
5016 case BPF_FUNC_tail_call:
5017 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5018 goto error;
e411901c
MF
5019 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5020 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5021 return -EINVAL;
5022 }
6aff67c8
AS
5023 break;
5024 case BPF_FUNC_perf_event_read:
5025 case BPF_FUNC_perf_event_output:
908432ca 5026 case BPF_FUNC_perf_event_read_value:
a7658e1a 5027 case BPF_FUNC_skb_output:
d831ee84 5028 case BPF_FUNC_xdp_output:
6aff67c8
AS
5029 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5030 goto error;
5031 break;
5032 case BPF_FUNC_get_stackid:
5033 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5034 goto error;
5035 break;
60d20f91 5036 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5037 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5038 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5039 goto error;
5040 break;
97f91a7c 5041 case BPF_FUNC_redirect_map:
9c270af3 5042 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5043 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5044 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5045 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5046 goto error;
5047 break;
174a79ff 5048 case BPF_FUNC_sk_redirect_map:
4f738adb 5049 case BPF_FUNC_msg_redirect_map:
81110384 5050 case BPF_FUNC_sock_map_update:
174a79ff
JF
5051 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5052 goto error;
5053 break;
81110384
JF
5054 case BPF_FUNC_sk_redirect_hash:
5055 case BPF_FUNC_msg_redirect_hash:
5056 case BPF_FUNC_sock_hash_update:
5057 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5058 goto error;
5059 break;
cd339431 5060 case BPF_FUNC_get_local_storage:
b741f163
RG
5061 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5062 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5063 goto error;
5064 break;
2dbb9b9e 5065 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5066 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5067 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5068 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5069 goto error;
5070 break;
f1a2e44a
MV
5071 case BPF_FUNC_map_peek_elem:
5072 case BPF_FUNC_map_pop_elem:
5073 case BPF_FUNC_map_push_elem:
5074 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5075 map->map_type != BPF_MAP_TYPE_STACK)
5076 goto error;
5077 break;
6ac99e8f
MKL
5078 case BPF_FUNC_sk_storage_get:
5079 case BPF_FUNC_sk_storage_delete:
5080 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5081 goto error;
5082 break;
8ea63684
KS
5083 case BPF_FUNC_inode_storage_get:
5084 case BPF_FUNC_inode_storage_delete:
5085 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5086 goto error;
5087 break;
4cf1bc1f
KS
5088 case BPF_FUNC_task_storage_get:
5089 case BPF_FUNC_task_storage_delete:
5090 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5091 goto error;
5092 break;
6aff67c8
AS
5093 default:
5094 break;
35578d79
KX
5095 }
5096
5097 return 0;
6aff67c8 5098error:
61bd5218 5099 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5100 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5101 return -EINVAL;
35578d79
KX
5102}
5103
90133415 5104static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5105{
5106 int count = 0;
5107
39f19ebb 5108 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5109 count++;
39f19ebb 5110 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5111 count++;
39f19ebb 5112 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5113 count++;
39f19ebb 5114 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5115 count++;
39f19ebb 5116 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5117 count++;
5118
90133415
DB
5119 /* We only support one arg being in raw mode at the moment,
5120 * which is sufficient for the helper functions we have
5121 * right now.
5122 */
5123 return count <= 1;
5124}
5125
5126static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5127 enum bpf_arg_type arg_next)
5128{
5129 return (arg_type_is_mem_ptr(arg_curr) &&
5130 !arg_type_is_mem_size(arg_next)) ||
5131 (!arg_type_is_mem_ptr(arg_curr) &&
5132 arg_type_is_mem_size(arg_next));
5133}
5134
5135static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5136{
5137 /* bpf_xxx(..., buf, len) call will access 'len'
5138 * bytes from memory 'buf'. Both arg types need
5139 * to be paired, so make sure there's no buggy
5140 * helper function specification.
5141 */
5142 if (arg_type_is_mem_size(fn->arg1_type) ||
5143 arg_type_is_mem_ptr(fn->arg5_type) ||
5144 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5145 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5146 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5147 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5148 return false;
5149
5150 return true;
5151}
5152
1b986589 5153static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5154{
5155 int count = 0;
5156
1b986589 5157 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5158 count++;
1b986589 5159 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5160 count++;
1b986589 5161 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5162 count++;
1b986589 5163 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5164 count++;
1b986589 5165 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5166 count++;
5167
1b986589
MKL
5168 /* A reference acquiring function cannot acquire
5169 * another refcounted ptr.
5170 */
64d85290 5171 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5172 return false;
5173
fd978bf7
JS
5174 /* We only support one arg being unreferenced at the moment,
5175 * which is sufficient for the helper functions we have right now.
5176 */
5177 return count <= 1;
5178}
5179
9436ef6e
LB
5180static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5181{
5182 int i;
5183
1df8f55a 5184 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5185 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5186 return false;
5187
1df8f55a
MKL
5188 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5189 return false;
5190 }
5191
9436ef6e
LB
5192 return true;
5193}
5194
1b986589 5195static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5196{
5197 return check_raw_mode_ok(fn) &&
fd978bf7 5198 check_arg_pair_ok(fn) &&
9436ef6e 5199 check_btf_id_ok(fn) &&
1b986589 5200 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5201}
5202
de8f3a83
DB
5203/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5204 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5205 */
f4d7e40a
AS
5206static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5207 struct bpf_func_state *state)
969bf05e 5208{
58e2af8b 5209 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5210 int i;
5211
5212 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5213 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5214 mark_reg_unknown(env, regs, i);
969bf05e 5215
f3709f69
JS
5216 bpf_for_each_spilled_reg(i, state, reg) {
5217 if (!reg)
969bf05e 5218 continue;
de8f3a83 5219 if (reg_is_pkt_pointer_any(reg))
f54c7898 5220 __mark_reg_unknown(env, reg);
969bf05e
AS
5221 }
5222}
5223
f4d7e40a
AS
5224static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5225{
5226 struct bpf_verifier_state *vstate = env->cur_state;
5227 int i;
5228
5229 for (i = 0; i <= vstate->curframe; i++)
5230 __clear_all_pkt_pointers(env, vstate->frame[i]);
5231}
5232
6d94e741
AS
5233enum {
5234 AT_PKT_END = -1,
5235 BEYOND_PKT_END = -2,
5236};
5237
5238static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5239{
5240 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5241 struct bpf_reg_state *reg = &state->regs[regn];
5242
5243 if (reg->type != PTR_TO_PACKET)
5244 /* PTR_TO_PACKET_META is not supported yet */
5245 return;
5246
5247 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5248 * How far beyond pkt_end it goes is unknown.
5249 * if (!range_open) it's the case of pkt >= pkt_end
5250 * if (range_open) it's the case of pkt > pkt_end
5251 * hence this pointer is at least 1 byte bigger than pkt_end
5252 */
5253 if (range_open)
5254 reg->range = BEYOND_PKT_END;
5255 else
5256 reg->range = AT_PKT_END;
5257}
5258
fd978bf7 5259static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5260 struct bpf_func_state *state,
5261 int ref_obj_id)
fd978bf7
JS
5262{
5263 struct bpf_reg_state *regs = state->regs, *reg;
5264 int i;
5265
5266 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5267 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5268 mark_reg_unknown(env, regs, i);
5269
5270 bpf_for_each_spilled_reg(i, state, reg) {
5271 if (!reg)
5272 continue;
1b986589 5273 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5274 __mark_reg_unknown(env, reg);
fd978bf7
JS
5275 }
5276}
5277
5278/* The pointer with the specified id has released its reference to kernel
5279 * resources. Identify all copies of the same pointer and clear the reference.
5280 */
5281static int release_reference(struct bpf_verifier_env *env,
1b986589 5282 int ref_obj_id)
fd978bf7
JS
5283{
5284 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5285 int err;
fd978bf7
JS
5286 int i;
5287
1b986589
MKL
5288 err = release_reference_state(cur_func(env), ref_obj_id);
5289 if (err)
5290 return err;
5291
fd978bf7 5292 for (i = 0; i <= vstate->curframe; i++)
1b986589 5293 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5294
1b986589 5295 return 0;
fd978bf7
JS
5296}
5297
51c39bb1
AS
5298static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5299 struct bpf_reg_state *regs)
5300{
5301 int i;
5302
5303 /* after the call registers r0 - r5 were scratched */
5304 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5305 mark_reg_not_init(env, regs, caller_saved[i]);
5306 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5307 }
5308}
5309
14351375
YS
5310typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5311 struct bpf_func_state *caller,
5312 struct bpf_func_state *callee,
5313 int insn_idx);
5314
5315static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5316 int *insn_idx, int subprog,
5317 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
5318{
5319 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5320 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5321 struct bpf_func_state *caller, *callee;
14351375 5322 int err;
51c39bb1 5323 bool is_global = false;
f4d7e40a 5324
aada9ce6 5325 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5326 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5327 state->curframe + 2);
f4d7e40a
AS
5328 return -E2BIG;
5329 }
5330
f4d7e40a
AS
5331 caller = state->frame[state->curframe];
5332 if (state->frame[state->curframe + 1]) {
5333 verbose(env, "verifier bug. Frame %d already allocated\n",
5334 state->curframe + 1);
5335 return -EFAULT;
5336 }
5337
51c39bb1
AS
5338 func_info_aux = env->prog->aux->func_info_aux;
5339 if (func_info_aux)
5340 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5341 err = btf_check_func_arg_match(env, subprog, caller->regs);
5342 if (err == -EFAULT)
5343 return err;
5344 if (is_global) {
5345 if (err) {
5346 verbose(env, "Caller passes invalid args into func#%d\n",
5347 subprog);
5348 return err;
5349 } else {
5350 if (env->log.level & BPF_LOG_LEVEL)
5351 verbose(env,
5352 "Func#%d is global and valid. Skipping.\n",
5353 subprog);
5354 clear_caller_saved_regs(env, caller->regs);
5355
45159b27 5356 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5357 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 5358 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5359
5360 /* continue with next insn after call */
5361 return 0;
5362 }
5363 }
5364
f4d7e40a
AS
5365 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5366 if (!callee)
5367 return -ENOMEM;
5368 state->frame[state->curframe + 1] = callee;
5369
5370 /* callee cannot access r0, r6 - r9 for reading and has to write
5371 * into its own stack before reading from it.
5372 * callee can read/write into caller's stack
5373 */
5374 init_func_state(env, callee,
5375 /* remember the callsite, it will be used by bpf_exit */
5376 *insn_idx /* callsite */,
5377 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5378 subprog /* subprog number within this prog */);
f4d7e40a 5379
fd978bf7
JS
5380 /* Transfer references to the callee */
5381 err = transfer_reference_state(callee, caller);
5382 if (err)
5383 return err;
5384
14351375
YS
5385 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5386 if (err)
5387 return err;
f4d7e40a 5388
51c39bb1 5389 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5390
5391 /* only increment it after check_reg_arg() finished */
5392 state->curframe++;
5393
5394 /* and go analyze first insn of the callee */
14351375 5395 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 5396
06ee7115 5397 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5398 verbose(env, "caller:\n");
5399 print_verifier_state(env, caller);
5400 verbose(env, "callee:\n");
5401 print_verifier_state(env, callee);
5402 }
5403 return 0;
5404}
5405
14351375
YS
5406static int set_callee_state(struct bpf_verifier_env *env,
5407 struct bpf_func_state *caller,
5408 struct bpf_func_state *callee, int insn_idx)
5409{
5410 int i;
5411
5412 /* copy r1 - r5 args that callee can access. The copy includes parent
5413 * pointers, which connects us up to the liveness chain
5414 */
5415 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5416 callee->regs[i] = caller->regs[i];
5417 return 0;
5418}
5419
5420static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5421 int *insn_idx)
5422{
5423 int subprog, target_insn;
5424
5425 target_insn = *insn_idx + insn->imm + 1;
5426 subprog = find_subprog(env, target_insn);
5427 if (subprog < 0) {
5428 verbose(env, "verifier bug. No program starts at insn %d\n",
5429 target_insn);
5430 return -EFAULT;
5431 }
5432
5433 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5434}
5435
69c087ba
YS
5436static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5437 struct bpf_func_state *caller,
5438 struct bpf_func_state *callee,
5439 int insn_idx)
5440{
5441 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5442 struct bpf_map *map;
5443 int err;
5444
5445 if (bpf_map_ptr_poisoned(insn_aux)) {
5446 verbose(env, "tail_call abusing map_ptr\n");
5447 return -EINVAL;
5448 }
5449
5450 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5451 if (!map->ops->map_set_for_each_callback_args ||
5452 !map->ops->map_for_each_callback) {
5453 verbose(env, "callback function not allowed for map\n");
5454 return -ENOTSUPP;
5455 }
5456
5457 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5458 if (err)
5459 return err;
5460
5461 callee->in_callback_fn = true;
5462 return 0;
5463}
5464
f4d7e40a
AS
5465static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5466{
5467 struct bpf_verifier_state *state = env->cur_state;
5468 struct bpf_func_state *caller, *callee;
5469 struct bpf_reg_state *r0;
fd978bf7 5470 int err;
f4d7e40a
AS
5471
5472 callee = state->frame[state->curframe];
5473 r0 = &callee->regs[BPF_REG_0];
5474 if (r0->type == PTR_TO_STACK) {
5475 /* technically it's ok to return caller's stack pointer
5476 * (or caller's caller's pointer) back to the caller,
5477 * since these pointers are valid. Only current stack
5478 * pointer will be invalid as soon as function exits,
5479 * but let's be conservative
5480 */
5481 verbose(env, "cannot return stack pointer to the caller\n");
5482 return -EINVAL;
5483 }
5484
5485 state->curframe--;
5486 caller = state->frame[state->curframe];
69c087ba
YS
5487 if (callee->in_callback_fn) {
5488 /* enforce R0 return value range [0, 1]. */
5489 struct tnum range = tnum_range(0, 1);
5490
5491 if (r0->type != SCALAR_VALUE) {
5492 verbose(env, "R0 not a scalar value\n");
5493 return -EACCES;
5494 }
5495 if (!tnum_in(range, r0->var_off)) {
5496 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5497 return -EINVAL;
5498 }
5499 } else {
5500 /* return to the caller whatever r0 had in the callee */
5501 caller->regs[BPF_REG_0] = *r0;
5502 }
f4d7e40a 5503
fd978bf7
JS
5504 /* Transfer references to the caller */
5505 err = transfer_reference_state(caller, callee);
5506 if (err)
5507 return err;
5508
f4d7e40a 5509 *insn_idx = callee->callsite + 1;
06ee7115 5510 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5511 verbose(env, "returning from callee:\n");
5512 print_verifier_state(env, callee);
5513 verbose(env, "to caller at %d:\n", *insn_idx);
5514 print_verifier_state(env, caller);
5515 }
5516 /* clear everything in the callee */
5517 free_func_state(callee);
5518 state->frame[state->curframe + 1] = NULL;
5519 return 0;
5520}
5521
849fa506
YS
5522static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5523 int func_id,
5524 struct bpf_call_arg_meta *meta)
5525{
5526 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5527
5528 if (ret_type != RET_INTEGER ||
5529 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
5530 func_id != BPF_FUNC_probe_read_str &&
5531 func_id != BPF_FUNC_probe_read_kernel_str &&
5532 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5533 return;
5534
10060503 5535 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5536 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5537 ret_reg->smin_value = -MAX_ERRNO;
5538 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5539 __reg_deduce_bounds(ret_reg);
5540 __reg_bound_offset(ret_reg);
10060503 5541 __update_reg_bounds(ret_reg);
849fa506
YS
5542}
5543
c93552c4
DB
5544static int
5545record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5546 int func_id, int insn_idx)
5547{
5548 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5549 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5550
5551 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5552 func_id != BPF_FUNC_map_lookup_elem &&
5553 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5554 func_id != BPF_FUNC_map_delete_elem &&
5555 func_id != BPF_FUNC_map_push_elem &&
5556 func_id != BPF_FUNC_map_pop_elem &&
69c087ba
YS
5557 func_id != BPF_FUNC_map_peek_elem &&
5558 func_id != BPF_FUNC_for_each_map_elem)
c93552c4 5559 return 0;
09772d92 5560
591fe988 5561 if (map == NULL) {
c93552c4
DB
5562 verbose(env, "kernel subsystem misconfigured verifier\n");
5563 return -EINVAL;
5564 }
5565
591fe988
DB
5566 /* In case of read-only, some additional restrictions
5567 * need to be applied in order to prevent altering the
5568 * state of the map from program side.
5569 */
5570 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5571 (func_id == BPF_FUNC_map_delete_elem ||
5572 func_id == BPF_FUNC_map_update_elem ||
5573 func_id == BPF_FUNC_map_push_elem ||
5574 func_id == BPF_FUNC_map_pop_elem)) {
5575 verbose(env, "write into map forbidden\n");
5576 return -EACCES;
5577 }
5578
d2e4c1e6 5579 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5580 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5581 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5582 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5583 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5584 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5585 return 0;
5586}
5587
d2e4c1e6
DB
5588static int
5589record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5590 int func_id, int insn_idx)
5591{
5592 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5593 struct bpf_reg_state *regs = cur_regs(env), *reg;
5594 struct bpf_map *map = meta->map_ptr;
5595 struct tnum range;
5596 u64 val;
cc52d914 5597 int err;
d2e4c1e6
DB
5598
5599 if (func_id != BPF_FUNC_tail_call)
5600 return 0;
5601 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5602 verbose(env, "kernel subsystem misconfigured verifier\n");
5603 return -EINVAL;
5604 }
5605
5606 range = tnum_range(0, map->max_entries - 1);
5607 reg = &regs[BPF_REG_3];
5608
5609 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5610 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5611 return 0;
5612 }
5613
cc52d914
DB
5614 err = mark_chain_precision(env, BPF_REG_3);
5615 if (err)
5616 return err;
5617
d2e4c1e6
DB
5618 val = reg->var_off.value;
5619 if (bpf_map_key_unseen(aux))
5620 bpf_map_key_store(aux, val);
5621 else if (!bpf_map_key_poisoned(aux) &&
5622 bpf_map_key_immediate(aux) != val)
5623 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5624 return 0;
5625}
5626
fd978bf7
JS
5627static int check_reference_leak(struct bpf_verifier_env *env)
5628{
5629 struct bpf_func_state *state = cur_func(env);
5630 int i;
5631
5632 for (i = 0; i < state->acquired_refs; i++) {
5633 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5634 state->refs[i].id, state->refs[i].insn_idx);
5635 }
5636 return state->acquired_refs ? -EINVAL : 0;
5637}
5638
69c087ba
YS
5639static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5640 int *insn_idx_p)
17a52670 5641{
17a52670 5642 const struct bpf_func_proto *fn = NULL;
638f5b90 5643 struct bpf_reg_state *regs;
33ff9823 5644 struct bpf_call_arg_meta meta;
69c087ba 5645 int insn_idx = *insn_idx_p;
969bf05e 5646 bool changes_data;
69c087ba 5647 int i, err, func_id;
17a52670
AS
5648
5649 /* find function prototype */
69c087ba 5650 func_id = insn->imm;
17a52670 5651 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5652 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5653 func_id);
17a52670
AS
5654 return -EINVAL;
5655 }
5656
00176a34 5657 if (env->ops->get_func_proto)
5e43f899 5658 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5659 if (!fn) {
61bd5218
JK
5660 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5661 func_id);
17a52670
AS
5662 return -EINVAL;
5663 }
5664
5665 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5666 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5667 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5668 return -EINVAL;
5669 }
5670
eae2e83e
JO
5671 if (fn->allowed && !fn->allowed(env->prog)) {
5672 verbose(env, "helper call is not allowed in probe\n");
5673 return -EINVAL;
5674 }
5675
04514d13 5676 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5677 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5678 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5679 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5680 func_id_name(func_id), func_id);
5681 return -EINVAL;
5682 }
969bf05e 5683
33ff9823 5684 memset(&meta, 0, sizeof(meta));
36bbef52 5685 meta.pkt_access = fn->pkt_access;
33ff9823 5686
1b986589 5687 err = check_func_proto(fn, func_id);
435faee1 5688 if (err) {
61bd5218 5689 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 5690 func_id_name(func_id), func_id);
435faee1
DB
5691 return err;
5692 }
5693
d83525ca 5694 meta.func_id = func_id;
17a52670 5695 /* check args */
523a4cf4 5696 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 5697 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
5698 if (err)
5699 return err;
5700 }
17a52670 5701
c93552c4
DB
5702 err = record_func_map(env, &meta, func_id, insn_idx);
5703 if (err)
5704 return err;
5705
d2e4c1e6
DB
5706 err = record_func_key(env, &meta, func_id, insn_idx);
5707 if (err)
5708 return err;
5709
435faee1
DB
5710 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5711 * is inferred from register state.
5712 */
5713 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
5714 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5715 BPF_WRITE, -1, false);
435faee1
DB
5716 if (err)
5717 return err;
5718 }
5719
fd978bf7
JS
5720 if (func_id == BPF_FUNC_tail_call) {
5721 err = check_reference_leak(env);
5722 if (err) {
5723 verbose(env, "tail_call would lead to reference leak\n");
5724 return err;
5725 }
5726 } else if (is_release_function(func_id)) {
1b986589 5727 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
5728 if (err) {
5729 verbose(env, "func %s#%d reference has not been acquired before\n",
5730 func_id_name(func_id), func_id);
fd978bf7 5731 return err;
46f8bc92 5732 }
fd978bf7
JS
5733 }
5734
638f5b90 5735 regs = cur_regs(env);
cd339431
RG
5736
5737 /* check that flags argument in get_local_storage(map, flags) is 0,
5738 * this is required because get_local_storage() can't return an error.
5739 */
5740 if (func_id == BPF_FUNC_get_local_storage &&
5741 !register_is_null(&regs[BPF_REG_2])) {
5742 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5743 return -EINVAL;
5744 }
5745
69c087ba
YS
5746 if (func_id == BPF_FUNC_for_each_map_elem) {
5747 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
5748 set_map_elem_callback_state);
5749 if (err < 0)
5750 return -EINVAL;
5751 }
5752
17a52670 5753 /* reset caller saved regs */
dc503a8a 5754 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5755 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5756 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5757 }
17a52670 5758
5327ed3d
JW
5759 /* helper call returns 64-bit value. */
5760 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5761
dc503a8a 5762 /* update return register (already marked as written above) */
17a52670 5763 if (fn->ret_type == RET_INTEGER) {
f1174f77 5764 /* sets type to SCALAR_VALUE */
61bd5218 5765 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5766 } else if (fn->ret_type == RET_VOID) {
5767 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5768 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5769 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5770 /* There is no offset yet applied, variable or fixed */
61bd5218 5771 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5772 /* remember map_ptr, so that check_map_access()
5773 * can check 'value_size' boundary of memory access
5774 * to map element returned from bpf_map_lookup_elem()
5775 */
33ff9823 5776 if (meta.map_ptr == NULL) {
61bd5218
JK
5777 verbose(env,
5778 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5779 return -EINVAL;
5780 }
33ff9823 5781 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5782 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5783 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5784 if (map_value_has_spin_lock(meta.map_ptr))
5785 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5786 } else {
5787 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 5788 }
c64b7983
JS
5789 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5790 mark_reg_known_zero(env, regs, BPF_REG_0);
5791 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
5792 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5793 mark_reg_known_zero(env, regs, BPF_REG_0);
5794 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
5795 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5796 mark_reg_known_zero(env, regs, BPF_REG_0);
5797 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
5798 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5799 mark_reg_known_zero(env, regs, BPF_REG_0);
5800 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 5801 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
5802 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5803 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
5804 const struct btf_type *t;
5805
5806 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 5807 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
5808 if (!btf_type_is_struct(t)) {
5809 u32 tsize;
5810 const struct btf_type *ret;
5811 const char *tname;
5812
5813 /* resolve the type size of ksym. */
22dc4a0f 5814 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 5815 if (IS_ERR(ret)) {
22dc4a0f 5816 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
5817 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5818 tname, PTR_ERR(ret));
5819 return -EINVAL;
5820 }
63d9b80d
HL
5821 regs[BPF_REG_0].type =
5822 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5823 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
5824 regs[BPF_REG_0].mem_size = tsize;
5825 } else {
63d9b80d
HL
5826 regs[BPF_REG_0].type =
5827 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5828 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 5829 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
5830 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5831 }
3ca1032a
KS
5832 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5833 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
5834 int ret_btf_id;
5835
5836 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
5837 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5838 PTR_TO_BTF_ID :
5839 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
5840 ret_btf_id = *fn->ret_btf_id;
5841 if (ret_btf_id == 0) {
5842 verbose(env, "invalid return type %d of func %s#%d\n",
5843 fn->ret_type, func_id_name(func_id), func_id);
5844 return -EINVAL;
5845 }
22dc4a0f
AN
5846 /* current BPF helper definitions are only coming from
5847 * built-in code with type IDs from vmlinux BTF
5848 */
5849 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 5850 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5851 } else {
61bd5218 5852 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5853 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5854 return -EINVAL;
5855 }
04fd61ab 5856
93c230e3
MKL
5857 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5858 regs[BPF_REG_0].id = ++env->id_gen;
5859
0f3adc28 5860 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5861 /* For release_reference() */
5862 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5863 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5864 int id = acquire_reference_state(env, insn_idx);
5865
5866 if (id < 0)
5867 return id;
5868 /* For mark_ptr_or_null_reg() */
5869 regs[BPF_REG_0].id = id;
5870 /* For release_reference() */
5871 regs[BPF_REG_0].ref_obj_id = id;
5872 }
1b986589 5873
849fa506
YS
5874 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5875
61bd5218 5876 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5877 if (err)
5878 return err;
04fd61ab 5879
fa28dcb8
SL
5880 if ((func_id == BPF_FUNC_get_stack ||
5881 func_id == BPF_FUNC_get_task_stack) &&
5882 !env->prog->has_callchain_buf) {
c195651e
YS
5883 const char *err_str;
5884
5885#ifdef CONFIG_PERF_EVENTS
5886 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5887 err_str = "cannot get callchain buffer for func %s#%d\n";
5888#else
5889 err = -ENOTSUPP;
5890 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5891#endif
5892 if (err) {
5893 verbose(env, err_str, func_id_name(func_id), func_id);
5894 return err;
5895 }
5896
5897 env->prog->has_callchain_buf = true;
5898 }
5899
5d99cb2c
SL
5900 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5901 env->prog->call_get_stack = true;
5902
969bf05e
AS
5903 if (changes_data)
5904 clear_all_pkt_pointers(env);
5905 return 0;
5906}
5907
b03c9f9f
EC
5908static bool signed_add_overflows(s64 a, s64 b)
5909{
5910 /* Do the add in u64, where overflow is well-defined */
5911 s64 res = (s64)((u64)a + (u64)b);
5912
5913 if (b < 0)
5914 return res > a;
5915 return res < a;
5916}
5917
bc895e8b 5918static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
5919{
5920 /* Do the add in u32, where overflow is well-defined */
5921 s32 res = (s32)((u32)a + (u32)b);
5922
5923 if (b < 0)
5924 return res > a;
5925 return res < a;
5926}
5927
bc895e8b 5928static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
5929{
5930 /* Do the sub in u64, where overflow is well-defined */
5931 s64 res = (s64)((u64)a - (u64)b);
5932
5933 if (b < 0)
5934 return res < a;
5935 return res > a;
969bf05e
AS
5936}
5937
3f50f132
JF
5938static bool signed_sub32_overflows(s32 a, s32 b)
5939{
bc895e8b 5940 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
5941 s32 res = (s32)((u32)a - (u32)b);
5942
5943 if (b < 0)
5944 return res < a;
5945 return res > a;
5946}
5947
bb7f0f98
AS
5948static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5949 const struct bpf_reg_state *reg,
5950 enum bpf_reg_type type)
5951{
5952 bool known = tnum_is_const(reg->var_off);
5953 s64 val = reg->var_off.value;
5954 s64 smin = reg->smin_value;
5955
5956 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5957 verbose(env, "math between %s pointer and %lld is not allowed\n",
5958 reg_type_str[type], val);
5959 return false;
5960 }
5961
5962 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5963 verbose(env, "%s pointer offset %d is not allowed\n",
5964 reg_type_str[type], reg->off);
5965 return false;
5966 }
5967
5968 if (smin == S64_MIN) {
5969 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5970 reg_type_str[type]);
5971 return false;
5972 }
5973
5974 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5975 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5976 smin, reg_type_str[type]);
5977 return false;
5978 }
5979
5980 return true;
5981}
5982
979d63d5
DB
5983static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5984{
5985 return &env->insn_aux_data[env->insn_idx];
5986}
5987
5988static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5989 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5990{
5991 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5992 (opcode == BPF_SUB && !off_is_neg);
5993 u32 off;
5994
5995 switch (ptr_reg->type) {
5996 case PTR_TO_STACK:
088ec26d
AI
5997 /* Indirect variable offset stack access is prohibited in
5998 * unprivileged mode so it's not handled here.
5999 */
979d63d5
DB
6000 off = ptr_reg->off + ptr_reg->var_off.value;
6001 if (mask_to_left)
6002 *ptr_limit = MAX_BPF_STACK + off;
6003 else
6004 *ptr_limit = -off;
6005 return 0;
69c087ba
YS
6006 case PTR_TO_MAP_KEY:
6007 /* Currently, this code is not exercised as the only use
6008 * is bpf_for_each_map_elem() helper which requires
6009 * bpf_capble. The code has been tested manually for
6010 * future use.
6011 */
6012 if (mask_to_left) {
6013 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6014 } else {
6015 off = ptr_reg->smin_value + ptr_reg->off;
6016 *ptr_limit = ptr_reg->map_ptr->key_size - off;
6017 }
6018 return 0;
979d63d5
DB
6019 case PTR_TO_MAP_VALUE:
6020 if (mask_to_left) {
6021 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6022 } else {
6023 off = ptr_reg->smin_value + ptr_reg->off;
6024 *ptr_limit = ptr_reg->map_ptr->value_size - off;
6025 }
6026 return 0;
6027 default:
6028 return -EINVAL;
6029 }
6030}
6031
d3bd7413
DB
6032static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6033 const struct bpf_insn *insn)
6034{
2c78ee89 6035 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
6036}
6037
6038static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6039 u32 alu_state, u32 alu_limit)
6040{
6041 /* If we arrived here from different branches with different
6042 * state or limits to sanitize, then this won't work.
6043 */
6044 if (aux->alu_state &&
6045 (aux->alu_state != alu_state ||
6046 aux->alu_limit != alu_limit))
6047 return -EACCES;
6048
e6ac5933 6049 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
6050 aux->alu_state = alu_state;
6051 aux->alu_limit = alu_limit;
6052 return 0;
6053}
6054
6055static int sanitize_val_alu(struct bpf_verifier_env *env,
6056 struct bpf_insn *insn)
6057{
6058 struct bpf_insn_aux_data *aux = cur_aux(env);
6059
6060 if (can_skip_alu_sanitation(env, insn))
6061 return 0;
6062
6063 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6064}
6065
979d63d5
DB
6066static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6067 struct bpf_insn *insn,
6068 const struct bpf_reg_state *ptr_reg,
6069 struct bpf_reg_state *dst_reg,
6070 bool off_is_neg)
6071{
6072 struct bpf_verifier_state *vstate = env->cur_state;
6073 struct bpf_insn_aux_data *aux = cur_aux(env);
6074 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6075 u8 opcode = BPF_OP(insn->code);
6076 u32 alu_state, alu_limit;
6077 struct bpf_reg_state tmp;
6078 bool ret;
6079
d3bd7413 6080 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
6081 return 0;
6082
6083 /* We already marked aux for masking from non-speculative
6084 * paths, thus we got here in the first place. We only care
6085 * to explore bad access from here.
6086 */
6087 if (vstate->speculative)
6088 goto do_sim;
6089
6090 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6091 alu_state |= ptr_is_dst_reg ?
6092 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6093
6094 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
6095 return 0;
d3bd7413 6096 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 6097 return -EACCES;
979d63d5
DB
6098do_sim:
6099 /* Simulate and find potential out-of-bounds access under
6100 * speculative execution from truncation as a result of
6101 * masking when off was not within expected range. If off
6102 * sits in dst, then we temporarily need to move ptr there
6103 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6104 * for cases where we use K-based arithmetic in one direction
6105 * and truncated reg-based in the other in order to explore
6106 * bad access.
6107 */
6108 if (!ptr_is_dst_reg) {
6109 tmp = *dst_reg;
6110 *dst_reg = *ptr_reg;
6111 }
6112 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 6113 if (!ptr_is_dst_reg && ret)
979d63d5
DB
6114 *dst_reg = tmp;
6115 return !ret ? -EFAULT : 0;
6116}
6117
01f810ac
AM
6118/* check that stack access falls within stack limits and that 'reg' doesn't
6119 * have a variable offset.
6120 *
6121 * Variable offset is prohibited for unprivileged mode for simplicity since it
6122 * requires corresponding support in Spectre masking for stack ALU. See also
6123 * retrieve_ptr_limit().
6124 *
6125 *
6126 * 'off' includes 'reg->off'.
6127 */
6128static int check_stack_access_for_ptr_arithmetic(
6129 struct bpf_verifier_env *env,
6130 int regno,
6131 const struct bpf_reg_state *reg,
6132 int off)
6133{
6134 if (!tnum_is_const(reg->var_off)) {
6135 char tn_buf[48];
6136
6137 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6138 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6139 regno, tn_buf, off);
6140 return -EACCES;
6141 }
6142
6143 if (off >= 0 || off < -MAX_BPF_STACK) {
6144 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6145 "prohibited for !root; off=%d\n", regno, off);
6146 return -EACCES;
6147 }
6148
6149 return 0;
6150}
6151
6152
f1174f77 6153/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
6154 * Caller should also handle BPF_MOV case separately.
6155 * If we return -EACCES, caller may want to try again treating pointer as a
6156 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6157 */
6158static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6159 struct bpf_insn *insn,
6160 const struct bpf_reg_state *ptr_reg,
6161 const struct bpf_reg_state *off_reg)
969bf05e 6162{
f4d7e40a
AS
6163 struct bpf_verifier_state *vstate = env->cur_state;
6164 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6165 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 6166 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
6167 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6168 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6169 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6170 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 6171 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 6172 u8 opcode = BPF_OP(insn->code);
979d63d5 6173 int ret;
969bf05e 6174
f1174f77 6175 dst_reg = &regs[dst];
969bf05e 6176
6f16101e
DB
6177 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6178 smin_val > smax_val || umin_val > umax_val) {
6179 /* Taint dst register if offset had invalid bounds derived from
6180 * e.g. dead branches.
6181 */
f54c7898 6182 __mark_reg_unknown(env, dst_reg);
6f16101e 6183 return 0;
f1174f77
EC
6184 }
6185
6186 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6187 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6188 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6189 __mark_reg_unknown(env, dst_reg);
6190 return 0;
6191 }
6192
82abbf8d
AS
6193 verbose(env,
6194 "R%d 32-bit pointer arithmetic prohibited\n",
6195 dst);
f1174f77 6196 return -EACCES;
969bf05e
AS
6197 }
6198
aad2eeaf
JS
6199 switch (ptr_reg->type) {
6200 case PTR_TO_MAP_VALUE_OR_NULL:
6201 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6202 dst, reg_type_str[ptr_reg->type]);
f1174f77 6203 return -EACCES;
aad2eeaf 6204 case CONST_PTR_TO_MAP:
7c696732
YS
6205 /* smin_val represents the known value */
6206 if (known && smin_val == 0 && opcode == BPF_ADD)
6207 break;
8731745e 6208 fallthrough;
aad2eeaf 6209 case PTR_TO_PACKET_END:
c64b7983
JS
6210 case PTR_TO_SOCKET:
6211 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6212 case PTR_TO_SOCK_COMMON:
6213 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6214 case PTR_TO_TCP_SOCK:
6215 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6216 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6217 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6218 dst, reg_type_str[ptr_reg->type]);
f1174f77 6219 return -EACCES;
69c087ba 6220 case PTR_TO_MAP_KEY:
9d7eceed
DB
6221 case PTR_TO_MAP_VALUE:
6222 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6223 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6224 off_reg == dst_reg ? dst : src);
6225 return -EACCES;
6226 }
df561f66 6227 fallthrough;
aad2eeaf
JS
6228 default:
6229 break;
f1174f77
EC
6230 }
6231
6232 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6233 * The id may be overwritten later if we create a new variable offset.
969bf05e 6234 */
f1174f77
EC
6235 dst_reg->type = ptr_reg->type;
6236 dst_reg->id = ptr_reg->id;
969bf05e 6237
bb7f0f98
AS
6238 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6239 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6240 return -EINVAL;
6241
3f50f132
JF
6242 /* pointer types do not carry 32-bit bounds at the moment. */
6243 __mark_reg32_unbounded(dst_reg);
6244
f1174f77
EC
6245 switch (opcode) {
6246 case BPF_ADD:
979d63d5
DB
6247 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6248 if (ret < 0) {
6249 verbose(env, "R%d tried to add from different maps or paths\n", dst);
6250 return ret;
6251 }
f1174f77
EC
6252 /* We can take a fixed offset as long as it doesn't overflow
6253 * the s32 'off' field
969bf05e 6254 */
b03c9f9f
EC
6255 if (known && (ptr_reg->off + smin_val ==
6256 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6257 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6258 dst_reg->smin_value = smin_ptr;
6259 dst_reg->smax_value = smax_ptr;
6260 dst_reg->umin_value = umin_ptr;
6261 dst_reg->umax_value = umax_ptr;
f1174f77 6262 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6263 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6264 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6265 break;
6266 }
f1174f77
EC
6267 /* A new variable offset is created. Note that off_reg->off
6268 * == 0, since it's a scalar.
6269 * dst_reg gets the pointer type and since some positive
6270 * integer value was added to the pointer, give it a new 'id'
6271 * if it's a PTR_TO_PACKET.
6272 * this creates a new 'base' pointer, off_reg (variable) gets
6273 * added into the variable offset, and we copy the fixed offset
6274 * from ptr_reg.
969bf05e 6275 */
b03c9f9f
EC
6276 if (signed_add_overflows(smin_ptr, smin_val) ||
6277 signed_add_overflows(smax_ptr, smax_val)) {
6278 dst_reg->smin_value = S64_MIN;
6279 dst_reg->smax_value = S64_MAX;
6280 } else {
6281 dst_reg->smin_value = smin_ptr + smin_val;
6282 dst_reg->smax_value = smax_ptr + smax_val;
6283 }
6284 if (umin_ptr + umin_val < umin_ptr ||
6285 umax_ptr + umax_val < umax_ptr) {
6286 dst_reg->umin_value = 0;
6287 dst_reg->umax_value = U64_MAX;
6288 } else {
6289 dst_reg->umin_value = umin_ptr + umin_val;
6290 dst_reg->umax_value = umax_ptr + umax_val;
6291 }
f1174f77
EC
6292 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6293 dst_reg->off = ptr_reg->off;
0962590e 6294 dst_reg->raw = ptr_reg->raw;
de8f3a83 6295 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6296 dst_reg->id = ++env->id_gen;
6297 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6298 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6299 }
6300 break;
6301 case BPF_SUB:
979d63d5
DB
6302 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6303 if (ret < 0) {
6304 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6305 return ret;
6306 }
f1174f77
EC
6307 if (dst_reg == off_reg) {
6308 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6309 verbose(env, "R%d tried to subtract pointer from scalar\n",
6310 dst);
f1174f77
EC
6311 return -EACCES;
6312 }
6313 /* We don't allow subtraction from FP, because (according to
6314 * test_verifier.c test "invalid fp arithmetic", JITs might not
6315 * be able to deal with it.
969bf05e 6316 */
f1174f77 6317 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6318 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6319 dst);
f1174f77
EC
6320 return -EACCES;
6321 }
b03c9f9f
EC
6322 if (known && (ptr_reg->off - smin_val ==
6323 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6324 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6325 dst_reg->smin_value = smin_ptr;
6326 dst_reg->smax_value = smax_ptr;
6327 dst_reg->umin_value = umin_ptr;
6328 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6329 dst_reg->var_off = ptr_reg->var_off;
6330 dst_reg->id = ptr_reg->id;
b03c9f9f 6331 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6332 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6333 break;
6334 }
f1174f77
EC
6335 /* A new variable offset is created. If the subtrahend is known
6336 * nonnegative, then any reg->range we had before is still good.
969bf05e 6337 */
b03c9f9f
EC
6338 if (signed_sub_overflows(smin_ptr, smax_val) ||
6339 signed_sub_overflows(smax_ptr, smin_val)) {
6340 /* Overflow possible, we know nothing */
6341 dst_reg->smin_value = S64_MIN;
6342 dst_reg->smax_value = S64_MAX;
6343 } else {
6344 dst_reg->smin_value = smin_ptr - smax_val;
6345 dst_reg->smax_value = smax_ptr - smin_val;
6346 }
6347 if (umin_ptr < umax_val) {
6348 /* Overflow possible, we know nothing */
6349 dst_reg->umin_value = 0;
6350 dst_reg->umax_value = U64_MAX;
6351 } else {
6352 /* Cannot overflow (as long as bounds are consistent) */
6353 dst_reg->umin_value = umin_ptr - umax_val;
6354 dst_reg->umax_value = umax_ptr - umin_val;
6355 }
f1174f77
EC
6356 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6357 dst_reg->off = ptr_reg->off;
0962590e 6358 dst_reg->raw = ptr_reg->raw;
de8f3a83 6359 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6360 dst_reg->id = ++env->id_gen;
6361 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6362 if (smin_val < 0)
22dc4a0f 6363 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6364 }
f1174f77
EC
6365 break;
6366 case BPF_AND:
6367 case BPF_OR:
6368 case BPF_XOR:
82abbf8d
AS
6369 /* bitwise ops on pointers are troublesome, prohibit. */
6370 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6371 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6372 return -EACCES;
6373 default:
6374 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6375 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6376 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6377 return -EACCES;
43188702
JF
6378 }
6379
bb7f0f98
AS
6380 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6381 return -EINVAL;
6382
b03c9f9f
EC
6383 __update_reg_bounds(dst_reg);
6384 __reg_deduce_bounds(dst_reg);
6385 __reg_bound_offset(dst_reg);
0d6303db
DB
6386
6387 /* For unprivileged we require that resulting offset must be in bounds
6388 * in order to be able to sanitize access later on.
6389 */
2c78ee89 6390 if (!env->bypass_spec_v1) {
e4298d25
DB
6391 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6392 check_map_access(env, dst, dst_reg->off, 1, false)) {
6393 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6394 "prohibited for !root\n", dst);
6395 return -EACCES;
6396 } else if (dst_reg->type == PTR_TO_STACK &&
01f810ac
AM
6397 check_stack_access_for_ptr_arithmetic(
6398 env, dst, dst_reg, dst_reg->off +
6399 dst_reg->var_off.value)) {
e4298d25
DB
6400 return -EACCES;
6401 }
0d6303db
DB
6402 }
6403
43188702
JF
6404 return 0;
6405}
6406
3f50f132
JF
6407static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6408 struct bpf_reg_state *src_reg)
6409{
6410 s32 smin_val = src_reg->s32_min_value;
6411 s32 smax_val = src_reg->s32_max_value;
6412 u32 umin_val = src_reg->u32_min_value;
6413 u32 umax_val = src_reg->u32_max_value;
6414
6415 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6416 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6417 dst_reg->s32_min_value = S32_MIN;
6418 dst_reg->s32_max_value = S32_MAX;
6419 } else {
6420 dst_reg->s32_min_value += smin_val;
6421 dst_reg->s32_max_value += smax_val;
6422 }
6423 if (dst_reg->u32_min_value + umin_val < umin_val ||
6424 dst_reg->u32_max_value + umax_val < umax_val) {
6425 dst_reg->u32_min_value = 0;
6426 dst_reg->u32_max_value = U32_MAX;
6427 } else {
6428 dst_reg->u32_min_value += umin_val;
6429 dst_reg->u32_max_value += umax_val;
6430 }
6431}
6432
07cd2631
JF
6433static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6434 struct bpf_reg_state *src_reg)
6435{
6436 s64 smin_val = src_reg->smin_value;
6437 s64 smax_val = src_reg->smax_value;
6438 u64 umin_val = src_reg->umin_value;
6439 u64 umax_val = src_reg->umax_value;
6440
6441 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6442 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6443 dst_reg->smin_value = S64_MIN;
6444 dst_reg->smax_value = S64_MAX;
6445 } else {
6446 dst_reg->smin_value += smin_val;
6447 dst_reg->smax_value += smax_val;
6448 }
6449 if (dst_reg->umin_value + umin_val < umin_val ||
6450 dst_reg->umax_value + umax_val < umax_val) {
6451 dst_reg->umin_value = 0;
6452 dst_reg->umax_value = U64_MAX;
6453 } else {
6454 dst_reg->umin_value += umin_val;
6455 dst_reg->umax_value += umax_val;
6456 }
3f50f132
JF
6457}
6458
6459static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6460 struct bpf_reg_state *src_reg)
6461{
6462 s32 smin_val = src_reg->s32_min_value;
6463 s32 smax_val = src_reg->s32_max_value;
6464 u32 umin_val = src_reg->u32_min_value;
6465 u32 umax_val = src_reg->u32_max_value;
6466
6467 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6468 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6469 /* Overflow possible, we know nothing */
6470 dst_reg->s32_min_value = S32_MIN;
6471 dst_reg->s32_max_value = S32_MAX;
6472 } else {
6473 dst_reg->s32_min_value -= smax_val;
6474 dst_reg->s32_max_value -= smin_val;
6475 }
6476 if (dst_reg->u32_min_value < umax_val) {
6477 /* Overflow possible, we know nothing */
6478 dst_reg->u32_min_value = 0;
6479 dst_reg->u32_max_value = U32_MAX;
6480 } else {
6481 /* Cannot overflow (as long as bounds are consistent) */
6482 dst_reg->u32_min_value -= umax_val;
6483 dst_reg->u32_max_value -= umin_val;
6484 }
07cd2631
JF
6485}
6486
6487static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6488 struct bpf_reg_state *src_reg)
6489{
6490 s64 smin_val = src_reg->smin_value;
6491 s64 smax_val = src_reg->smax_value;
6492 u64 umin_val = src_reg->umin_value;
6493 u64 umax_val = src_reg->umax_value;
6494
6495 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6496 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6497 /* Overflow possible, we know nothing */
6498 dst_reg->smin_value = S64_MIN;
6499 dst_reg->smax_value = S64_MAX;
6500 } else {
6501 dst_reg->smin_value -= smax_val;
6502 dst_reg->smax_value -= smin_val;
6503 }
6504 if (dst_reg->umin_value < umax_val) {
6505 /* Overflow possible, we know nothing */
6506 dst_reg->umin_value = 0;
6507 dst_reg->umax_value = U64_MAX;
6508 } else {
6509 /* Cannot overflow (as long as bounds are consistent) */
6510 dst_reg->umin_value -= umax_val;
6511 dst_reg->umax_value -= umin_val;
6512 }
3f50f132
JF
6513}
6514
6515static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6516 struct bpf_reg_state *src_reg)
6517{
6518 s32 smin_val = src_reg->s32_min_value;
6519 u32 umin_val = src_reg->u32_min_value;
6520 u32 umax_val = src_reg->u32_max_value;
6521
6522 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6523 /* Ain't nobody got time to multiply that sign */
6524 __mark_reg32_unbounded(dst_reg);
6525 return;
6526 }
6527 /* Both values are positive, so we can work with unsigned and
6528 * copy the result to signed (unless it exceeds S32_MAX).
6529 */
6530 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6531 /* Potential overflow, we know nothing */
6532 __mark_reg32_unbounded(dst_reg);
6533 return;
6534 }
6535 dst_reg->u32_min_value *= umin_val;
6536 dst_reg->u32_max_value *= umax_val;
6537 if (dst_reg->u32_max_value > S32_MAX) {
6538 /* Overflow possible, we know nothing */
6539 dst_reg->s32_min_value = S32_MIN;
6540 dst_reg->s32_max_value = S32_MAX;
6541 } else {
6542 dst_reg->s32_min_value = dst_reg->u32_min_value;
6543 dst_reg->s32_max_value = dst_reg->u32_max_value;
6544 }
07cd2631
JF
6545}
6546
6547static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6548 struct bpf_reg_state *src_reg)
6549{
6550 s64 smin_val = src_reg->smin_value;
6551 u64 umin_val = src_reg->umin_value;
6552 u64 umax_val = src_reg->umax_value;
6553
07cd2631
JF
6554 if (smin_val < 0 || dst_reg->smin_value < 0) {
6555 /* Ain't nobody got time to multiply that sign */
3f50f132 6556 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6557 return;
6558 }
6559 /* Both values are positive, so we can work with unsigned and
6560 * copy the result to signed (unless it exceeds S64_MAX).
6561 */
6562 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6563 /* Potential overflow, we know nothing */
3f50f132 6564 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
6565 return;
6566 }
6567 dst_reg->umin_value *= umin_val;
6568 dst_reg->umax_value *= umax_val;
6569 if (dst_reg->umax_value > S64_MAX) {
6570 /* Overflow possible, we know nothing */
6571 dst_reg->smin_value = S64_MIN;
6572 dst_reg->smax_value = S64_MAX;
6573 } else {
6574 dst_reg->smin_value = dst_reg->umin_value;
6575 dst_reg->smax_value = dst_reg->umax_value;
6576 }
6577}
6578
3f50f132
JF
6579static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6580 struct bpf_reg_state *src_reg)
6581{
6582 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6583 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6584 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6585 s32 smin_val = src_reg->s32_min_value;
6586 u32 umax_val = src_reg->u32_max_value;
6587
6588 /* Assuming scalar64_min_max_and will be called so its safe
6589 * to skip updating register for known 32-bit case.
6590 */
6591 if (src_known && dst_known)
6592 return;
6593
6594 /* We get our minimum from the var_off, since that's inherently
6595 * bitwise. Our maximum is the minimum of the operands' maxima.
6596 */
6597 dst_reg->u32_min_value = var32_off.value;
6598 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6599 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6600 /* Lose signed bounds when ANDing negative numbers,
6601 * ain't nobody got time for that.
6602 */
6603 dst_reg->s32_min_value = S32_MIN;
6604 dst_reg->s32_max_value = S32_MAX;
6605 } else {
6606 /* ANDing two positives gives a positive, so safe to
6607 * cast result into s64.
6608 */
6609 dst_reg->s32_min_value = dst_reg->u32_min_value;
6610 dst_reg->s32_max_value = dst_reg->u32_max_value;
6611 }
6612
6613}
6614
07cd2631
JF
6615static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6616 struct bpf_reg_state *src_reg)
6617{
3f50f132
JF
6618 bool src_known = tnum_is_const(src_reg->var_off);
6619 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
6620 s64 smin_val = src_reg->smin_value;
6621 u64 umax_val = src_reg->umax_value;
6622
3f50f132 6623 if (src_known && dst_known) {
4fbb38a3 6624 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
6625 return;
6626 }
6627
07cd2631
JF
6628 /* We get our minimum from the var_off, since that's inherently
6629 * bitwise. Our maximum is the minimum of the operands' maxima.
6630 */
07cd2631
JF
6631 dst_reg->umin_value = dst_reg->var_off.value;
6632 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6633 if (dst_reg->smin_value < 0 || smin_val < 0) {
6634 /* Lose signed bounds when ANDing negative numbers,
6635 * ain't nobody got time for that.
6636 */
6637 dst_reg->smin_value = S64_MIN;
6638 dst_reg->smax_value = S64_MAX;
6639 } else {
6640 /* ANDing two positives gives a positive, so safe to
6641 * cast result into s64.
6642 */
6643 dst_reg->smin_value = dst_reg->umin_value;
6644 dst_reg->smax_value = dst_reg->umax_value;
6645 }
6646 /* We may learn something more from the var_off */
6647 __update_reg_bounds(dst_reg);
6648}
6649
3f50f132
JF
6650static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6651 struct bpf_reg_state *src_reg)
6652{
6653 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6654 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6655 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
6656 s32 smin_val = src_reg->s32_min_value;
6657 u32 umin_val = src_reg->u32_min_value;
3f50f132
JF
6658
6659 /* Assuming scalar64_min_max_or will be called so it is safe
6660 * to skip updating register for known case.
6661 */
6662 if (src_known && dst_known)
6663 return;
6664
6665 /* We get our maximum from the var_off, and our minimum is the
6666 * maximum of the operands' minima
6667 */
6668 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6669 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6670 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6671 /* Lose signed bounds when ORing negative numbers,
6672 * ain't nobody got time for that.
6673 */
6674 dst_reg->s32_min_value = S32_MIN;
6675 dst_reg->s32_max_value = S32_MAX;
6676 } else {
6677 /* ORing two positives gives a positive, so safe to
6678 * cast result into s64.
6679 */
5b9fbeb7
DB
6680 dst_reg->s32_min_value = dst_reg->u32_min_value;
6681 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
6682 }
6683}
6684
07cd2631
JF
6685static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6686 struct bpf_reg_state *src_reg)
6687{
3f50f132
JF
6688 bool src_known = tnum_is_const(src_reg->var_off);
6689 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
6690 s64 smin_val = src_reg->smin_value;
6691 u64 umin_val = src_reg->umin_value;
6692
3f50f132 6693 if (src_known && dst_known) {
4fbb38a3 6694 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
6695 return;
6696 }
6697
07cd2631
JF
6698 /* We get our maximum from the var_off, and our minimum is the
6699 * maximum of the operands' minima
6700 */
07cd2631
JF
6701 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6702 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6703 if (dst_reg->smin_value < 0 || smin_val < 0) {
6704 /* Lose signed bounds when ORing negative numbers,
6705 * ain't nobody got time for that.
6706 */
6707 dst_reg->smin_value = S64_MIN;
6708 dst_reg->smax_value = S64_MAX;
6709 } else {
6710 /* ORing two positives gives a positive, so safe to
6711 * cast result into s64.
6712 */
6713 dst_reg->smin_value = dst_reg->umin_value;
6714 dst_reg->smax_value = dst_reg->umax_value;
6715 }
6716 /* We may learn something more from the var_off */
6717 __update_reg_bounds(dst_reg);
6718}
6719
2921c90d
YS
6720static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6721 struct bpf_reg_state *src_reg)
6722{
6723 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6724 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6725 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6726 s32 smin_val = src_reg->s32_min_value;
6727
6728 /* Assuming scalar64_min_max_xor will be called so it is safe
6729 * to skip updating register for known case.
6730 */
6731 if (src_known && dst_known)
6732 return;
6733
6734 /* We get both minimum and maximum from the var32_off. */
6735 dst_reg->u32_min_value = var32_off.value;
6736 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6737
6738 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6739 /* XORing two positive sign numbers gives a positive,
6740 * so safe to cast u32 result into s32.
6741 */
6742 dst_reg->s32_min_value = dst_reg->u32_min_value;
6743 dst_reg->s32_max_value = dst_reg->u32_max_value;
6744 } else {
6745 dst_reg->s32_min_value = S32_MIN;
6746 dst_reg->s32_max_value = S32_MAX;
6747 }
6748}
6749
6750static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6751 struct bpf_reg_state *src_reg)
6752{
6753 bool src_known = tnum_is_const(src_reg->var_off);
6754 bool dst_known = tnum_is_const(dst_reg->var_off);
6755 s64 smin_val = src_reg->smin_value;
6756
6757 if (src_known && dst_known) {
6758 /* dst_reg->var_off.value has been updated earlier */
6759 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6760 return;
6761 }
6762
6763 /* We get both minimum and maximum from the var_off. */
6764 dst_reg->umin_value = dst_reg->var_off.value;
6765 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6766
6767 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6768 /* XORing two positive sign numbers gives a positive,
6769 * so safe to cast u64 result into s64.
6770 */
6771 dst_reg->smin_value = dst_reg->umin_value;
6772 dst_reg->smax_value = dst_reg->umax_value;
6773 } else {
6774 dst_reg->smin_value = S64_MIN;
6775 dst_reg->smax_value = S64_MAX;
6776 }
6777
6778 __update_reg_bounds(dst_reg);
6779}
6780
3f50f132
JF
6781static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6782 u64 umin_val, u64 umax_val)
07cd2631 6783{
07cd2631
JF
6784 /* We lose all sign bit information (except what we can pick
6785 * up from var_off)
6786 */
3f50f132
JF
6787 dst_reg->s32_min_value = S32_MIN;
6788 dst_reg->s32_max_value = S32_MAX;
6789 /* If we might shift our top bit out, then we know nothing */
6790 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6791 dst_reg->u32_min_value = 0;
6792 dst_reg->u32_max_value = U32_MAX;
6793 } else {
6794 dst_reg->u32_min_value <<= umin_val;
6795 dst_reg->u32_max_value <<= umax_val;
6796 }
6797}
6798
6799static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6800 struct bpf_reg_state *src_reg)
6801{
6802 u32 umax_val = src_reg->u32_max_value;
6803 u32 umin_val = src_reg->u32_min_value;
6804 /* u32 alu operation will zext upper bits */
6805 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6806
6807 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6808 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6809 /* Not required but being careful mark reg64 bounds as unknown so
6810 * that we are forced to pick them up from tnum and zext later and
6811 * if some path skips this step we are still safe.
6812 */
6813 __mark_reg64_unbounded(dst_reg);
6814 __update_reg32_bounds(dst_reg);
6815}
6816
6817static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6818 u64 umin_val, u64 umax_val)
6819{
6820 /* Special case <<32 because it is a common compiler pattern to sign
6821 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6822 * positive we know this shift will also be positive so we can track
6823 * bounds correctly. Otherwise we lose all sign bit information except
6824 * what we can pick up from var_off. Perhaps we can generalize this
6825 * later to shifts of any length.
6826 */
6827 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6828 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6829 else
6830 dst_reg->smax_value = S64_MAX;
6831
6832 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6833 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6834 else
6835 dst_reg->smin_value = S64_MIN;
6836
07cd2631
JF
6837 /* If we might shift our top bit out, then we know nothing */
6838 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6839 dst_reg->umin_value = 0;
6840 dst_reg->umax_value = U64_MAX;
6841 } else {
6842 dst_reg->umin_value <<= umin_val;
6843 dst_reg->umax_value <<= umax_val;
6844 }
3f50f132
JF
6845}
6846
6847static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6848 struct bpf_reg_state *src_reg)
6849{
6850 u64 umax_val = src_reg->umax_value;
6851 u64 umin_val = src_reg->umin_value;
6852
6853 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6854 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6855 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6856
07cd2631
JF
6857 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6858 /* We may learn something more from the var_off */
6859 __update_reg_bounds(dst_reg);
6860}
6861
3f50f132
JF
6862static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6863 struct bpf_reg_state *src_reg)
6864{
6865 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6866 u32 umax_val = src_reg->u32_max_value;
6867 u32 umin_val = src_reg->u32_min_value;
6868
6869 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6870 * be negative, then either:
6871 * 1) src_reg might be zero, so the sign bit of the result is
6872 * unknown, so we lose our signed bounds
6873 * 2) it's known negative, thus the unsigned bounds capture the
6874 * signed bounds
6875 * 3) the signed bounds cross zero, so they tell us nothing
6876 * about the result
6877 * If the value in dst_reg is known nonnegative, then again the
18b24d78 6878 * unsigned bounds capture the signed bounds.
3f50f132
JF
6879 * Thus, in all cases it suffices to blow away our signed bounds
6880 * and rely on inferring new ones from the unsigned bounds and
6881 * var_off of the result.
6882 */
6883 dst_reg->s32_min_value = S32_MIN;
6884 dst_reg->s32_max_value = S32_MAX;
6885
6886 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6887 dst_reg->u32_min_value >>= umax_val;
6888 dst_reg->u32_max_value >>= umin_val;
6889
6890 __mark_reg64_unbounded(dst_reg);
6891 __update_reg32_bounds(dst_reg);
6892}
6893
07cd2631
JF
6894static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6895 struct bpf_reg_state *src_reg)
6896{
6897 u64 umax_val = src_reg->umax_value;
6898 u64 umin_val = src_reg->umin_value;
6899
6900 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6901 * be negative, then either:
6902 * 1) src_reg might be zero, so the sign bit of the result is
6903 * unknown, so we lose our signed bounds
6904 * 2) it's known negative, thus the unsigned bounds capture the
6905 * signed bounds
6906 * 3) the signed bounds cross zero, so they tell us nothing
6907 * about the result
6908 * If the value in dst_reg is known nonnegative, then again the
18b24d78 6909 * unsigned bounds capture the signed bounds.
07cd2631
JF
6910 * Thus, in all cases it suffices to blow away our signed bounds
6911 * and rely on inferring new ones from the unsigned bounds and
6912 * var_off of the result.
6913 */
6914 dst_reg->smin_value = S64_MIN;
6915 dst_reg->smax_value = S64_MAX;
6916 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6917 dst_reg->umin_value >>= umax_val;
6918 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6919
6920 /* Its not easy to operate on alu32 bounds here because it depends
6921 * on bits being shifted in. Take easy way out and mark unbounded
6922 * so we can recalculate later from tnum.
6923 */
6924 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6925 __update_reg_bounds(dst_reg);
6926}
6927
3f50f132
JF
6928static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6929 struct bpf_reg_state *src_reg)
07cd2631 6930{
3f50f132 6931 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6932
6933 /* Upon reaching here, src_known is true and
6934 * umax_val is equal to umin_val.
6935 */
3f50f132
JF
6936 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6937 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6938
3f50f132
JF
6939 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6940
6941 /* blow away the dst_reg umin_value/umax_value and rely on
6942 * dst_reg var_off to refine the result.
6943 */
6944 dst_reg->u32_min_value = 0;
6945 dst_reg->u32_max_value = U32_MAX;
6946
6947 __mark_reg64_unbounded(dst_reg);
6948 __update_reg32_bounds(dst_reg);
6949}
6950
6951static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6952 struct bpf_reg_state *src_reg)
6953{
6954 u64 umin_val = src_reg->umin_value;
6955
6956 /* Upon reaching here, src_known is true and umax_val is equal
6957 * to umin_val.
6958 */
6959 dst_reg->smin_value >>= umin_val;
6960 dst_reg->smax_value >>= umin_val;
6961
6962 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
6963
6964 /* blow away the dst_reg umin_value/umax_value and rely on
6965 * dst_reg var_off to refine the result.
6966 */
6967 dst_reg->umin_value = 0;
6968 dst_reg->umax_value = U64_MAX;
3f50f132
JF
6969
6970 /* Its not easy to operate on alu32 bounds here because it depends
6971 * on bits being shifted in from upper 32-bits. Take easy way out
6972 * and mark unbounded so we can recalculate later from tnum.
6973 */
6974 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6975 __update_reg_bounds(dst_reg);
6976}
6977
468f6eaf
JH
6978/* WARNING: This function does calculations on 64-bit values, but the actual
6979 * execution may occur on 32-bit values. Therefore, things like bitshifts
6980 * need extra checks in the 32-bit case.
6981 */
f1174f77
EC
6982static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6983 struct bpf_insn *insn,
6984 struct bpf_reg_state *dst_reg,
6985 struct bpf_reg_state src_reg)
969bf05e 6986{
638f5b90 6987 struct bpf_reg_state *regs = cur_regs(env);
48461135 6988 u8 opcode = BPF_OP(insn->code);
b0b3fb67 6989 bool src_known;
b03c9f9f
EC
6990 s64 smin_val, smax_val;
6991 u64 umin_val, umax_val;
3f50f132
JF
6992 s32 s32_min_val, s32_max_val;
6993 u32 u32_min_val, u32_max_val;
468f6eaf 6994 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
6995 u32 dst = insn->dst_reg;
6996 int ret;
3f50f132 6997 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 6998
b03c9f9f
EC
6999 smin_val = src_reg.smin_value;
7000 smax_val = src_reg.smax_value;
7001 umin_val = src_reg.umin_value;
7002 umax_val = src_reg.umax_value;
f23cc643 7003
3f50f132
JF
7004 s32_min_val = src_reg.s32_min_value;
7005 s32_max_val = src_reg.s32_max_value;
7006 u32_min_val = src_reg.u32_min_value;
7007 u32_max_val = src_reg.u32_max_value;
7008
7009 if (alu32) {
7010 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
7011 if ((src_known &&
7012 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7013 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7014 /* Taint dst register if offset had invalid bounds
7015 * derived from e.g. dead branches.
7016 */
7017 __mark_reg_unknown(env, dst_reg);
7018 return 0;
7019 }
7020 } else {
7021 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
7022 if ((src_known &&
7023 (smin_val != smax_val || umin_val != umax_val)) ||
7024 smin_val > smax_val || umin_val > umax_val) {
7025 /* Taint dst register if offset had invalid bounds
7026 * derived from e.g. dead branches.
7027 */
7028 __mark_reg_unknown(env, dst_reg);
7029 return 0;
7030 }
6f16101e
DB
7031 }
7032
bb7f0f98
AS
7033 if (!src_known &&
7034 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 7035 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
7036 return 0;
7037 }
7038
3f50f132
JF
7039 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7040 * There are two classes of instructions: The first class we track both
7041 * alu32 and alu64 sign/unsigned bounds independently this provides the
7042 * greatest amount of precision when alu operations are mixed with jmp32
7043 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7044 * and BPF_OR. This is possible because these ops have fairly easy to
7045 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7046 * See alu32 verifier tests for examples. The second class of
7047 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7048 * with regards to tracking sign/unsigned bounds because the bits may
7049 * cross subreg boundaries in the alu64 case. When this happens we mark
7050 * the reg unbounded in the subreg bound space and use the resulting
7051 * tnum to calculate an approximation of the sign/unsigned bounds.
7052 */
48461135
JB
7053 switch (opcode) {
7054 case BPF_ADD:
d3bd7413
DB
7055 ret = sanitize_val_alu(env, insn);
7056 if (ret < 0) {
7057 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7058 return ret;
7059 }
3f50f132 7060 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 7061 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 7062 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
7063 break;
7064 case BPF_SUB:
d3bd7413
DB
7065 ret = sanitize_val_alu(env, insn);
7066 if (ret < 0) {
7067 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7068 return ret;
7069 }
3f50f132 7070 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 7071 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 7072 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
7073 break;
7074 case BPF_MUL:
3f50f132
JF
7075 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7076 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 7077 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
7078 break;
7079 case BPF_AND:
3f50f132
JF
7080 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7081 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 7082 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
7083 break;
7084 case BPF_OR:
3f50f132
JF
7085 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7086 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 7087 scalar_min_max_or(dst_reg, &src_reg);
48461135 7088 break;
2921c90d
YS
7089 case BPF_XOR:
7090 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7091 scalar32_min_max_xor(dst_reg, &src_reg);
7092 scalar_min_max_xor(dst_reg, &src_reg);
7093 break;
48461135 7094 case BPF_LSH:
468f6eaf
JH
7095 if (umax_val >= insn_bitness) {
7096 /* Shifts greater than 31 or 63 are undefined.
7097 * This includes shifts by a negative number.
b03c9f9f 7098 */
61bd5218 7099 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7100 break;
7101 }
3f50f132
JF
7102 if (alu32)
7103 scalar32_min_max_lsh(dst_reg, &src_reg);
7104 else
7105 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
7106 break;
7107 case BPF_RSH:
468f6eaf
JH
7108 if (umax_val >= insn_bitness) {
7109 /* Shifts greater than 31 or 63 are undefined.
7110 * This includes shifts by a negative number.
b03c9f9f 7111 */
61bd5218 7112 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7113 break;
7114 }
3f50f132
JF
7115 if (alu32)
7116 scalar32_min_max_rsh(dst_reg, &src_reg);
7117 else
7118 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 7119 break;
9cbe1f5a
YS
7120 case BPF_ARSH:
7121 if (umax_val >= insn_bitness) {
7122 /* Shifts greater than 31 or 63 are undefined.
7123 * This includes shifts by a negative number.
7124 */
7125 mark_reg_unknown(env, regs, insn->dst_reg);
7126 break;
7127 }
3f50f132
JF
7128 if (alu32)
7129 scalar32_min_max_arsh(dst_reg, &src_reg);
7130 else
7131 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 7132 break;
48461135 7133 default:
61bd5218 7134 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
7135 break;
7136 }
7137
3f50f132
JF
7138 /* ALU32 ops are zero extended into 64bit register */
7139 if (alu32)
7140 zext_32_to_64(dst_reg);
468f6eaf 7141
294f2fc6 7142 __update_reg_bounds(dst_reg);
b03c9f9f
EC
7143 __reg_deduce_bounds(dst_reg);
7144 __reg_bound_offset(dst_reg);
f1174f77
EC
7145 return 0;
7146}
7147
7148/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7149 * and var_off.
7150 */
7151static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7152 struct bpf_insn *insn)
7153{
f4d7e40a
AS
7154 struct bpf_verifier_state *vstate = env->cur_state;
7155 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7156 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
7157 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7158 u8 opcode = BPF_OP(insn->code);
b5dc0163 7159 int err;
f1174f77
EC
7160
7161 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
7162 src_reg = NULL;
7163 if (dst_reg->type != SCALAR_VALUE)
7164 ptr_reg = dst_reg;
75748837
AS
7165 else
7166 /* Make sure ID is cleared otherwise dst_reg min/max could be
7167 * incorrectly propagated into other registers by find_equal_scalars()
7168 */
7169 dst_reg->id = 0;
f1174f77
EC
7170 if (BPF_SRC(insn->code) == BPF_X) {
7171 src_reg = &regs[insn->src_reg];
f1174f77
EC
7172 if (src_reg->type != SCALAR_VALUE) {
7173 if (dst_reg->type != SCALAR_VALUE) {
7174 /* Combining two pointers by any ALU op yields
82abbf8d
AS
7175 * an arbitrary scalar. Disallow all math except
7176 * pointer subtraction
f1174f77 7177 */
dd066823 7178 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
7179 mark_reg_unknown(env, regs, insn->dst_reg);
7180 return 0;
f1174f77 7181 }
82abbf8d
AS
7182 verbose(env, "R%d pointer %s pointer prohibited\n",
7183 insn->dst_reg,
7184 bpf_alu_string[opcode >> 4]);
7185 return -EACCES;
f1174f77
EC
7186 } else {
7187 /* scalar += pointer
7188 * This is legal, but we have to reverse our
7189 * src/dest handling in computing the range
7190 */
b5dc0163
AS
7191 err = mark_chain_precision(env, insn->dst_reg);
7192 if (err)
7193 return err;
82abbf8d
AS
7194 return adjust_ptr_min_max_vals(env, insn,
7195 src_reg, dst_reg);
f1174f77
EC
7196 }
7197 } else if (ptr_reg) {
7198 /* pointer += scalar */
b5dc0163
AS
7199 err = mark_chain_precision(env, insn->src_reg);
7200 if (err)
7201 return err;
82abbf8d
AS
7202 return adjust_ptr_min_max_vals(env, insn,
7203 dst_reg, src_reg);
f1174f77
EC
7204 }
7205 } else {
7206 /* Pretend the src is a reg with a known value, since we only
7207 * need to be able to read from this state.
7208 */
7209 off_reg.type = SCALAR_VALUE;
b03c9f9f 7210 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7211 src_reg = &off_reg;
82abbf8d
AS
7212 if (ptr_reg) /* pointer += K */
7213 return adjust_ptr_min_max_vals(env, insn,
7214 ptr_reg, src_reg);
f1174f77
EC
7215 }
7216
7217 /* Got here implies adding two SCALAR_VALUEs */
7218 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7219 print_verifier_state(env, state);
61bd5218 7220 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7221 return -EINVAL;
7222 }
7223 if (WARN_ON(!src_reg)) {
f4d7e40a 7224 print_verifier_state(env, state);
61bd5218 7225 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7226 return -EINVAL;
7227 }
7228 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7229}
7230
17a52670 7231/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7232static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7233{
638f5b90 7234 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7235 u8 opcode = BPF_OP(insn->code);
7236 int err;
7237
7238 if (opcode == BPF_END || opcode == BPF_NEG) {
7239 if (opcode == BPF_NEG) {
7240 if (BPF_SRC(insn->code) != 0 ||
7241 insn->src_reg != BPF_REG_0 ||
7242 insn->off != 0 || insn->imm != 0) {
61bd5218 7243 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7244 return -EINVAL;
7245 }
7246 } else {
7247 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7248 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7249 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7250 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7251 return -EINVAL;
7252 }
7253 }
7254
7255 /* check src operand */
dc503a8a 7256 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7257 if (err)
7258 return err;
7259
1be7f75d 7260 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7261 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7262 insn->dst_reg);
7263 return -EACCES;
7264 }
7265
17a52670 7266 /* check dest operand */
dc503a8a 7267 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7268 if (err)
7269 return err;
7270
7271 } else if (opcode == BPF_MOV) {
7272
7273 if (BPF_SRC(insn->code) == BPF_X) {
7274 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7275 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7276 return -EINVAL;
7277 }
7278
7279 /* check src operand */
dc503a8a 7280 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7281 if (err)
7282 return err;
7283 } else {
7284 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7285 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7286 return -EINVAL;
7287 }
7288 }
7289
fbeb1603
AF
7290 /* check dest operand, mark as required later */
7291 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7292 if (err)
7293 return err;
7294
7295 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7296 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7297 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7298
17a52670
AS
7299 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7300 /* case: R1 = R2
7301 * copy register state to dest reg
7302 */
75748837
AS
7303 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7304 /* Assign src and dst registers the same ID
7305 * that will be used by find_equal_scalars()
7306 * to propagate min/max range.
7307 */
7308 src_reg->id = ++env->id_gen;
e434b8cd
JW
7309 *dst_reg = *src_reg;
7310 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7311 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7312 } else {
f1174f77 7313 /* R1 = (u32) R2 */
1be7f75d 7314 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7315 verbose(env,
7316 "R%d partial copy of pointer\n",
1be7f75d
AS
7317 insn->src_reg);
7318 return -EACCES;
e434b8cd
JW
7319 } else if (src_reg->type == SCALAR_VALUE) {
7320 *dst_reg = *src_reg;
75748837
AS
7321 /* Make sure ID is cleared otherwise
7322 * dst_reg min/max could be incorrectly
7323 * propagated into src_reg by find_equal_scalars()
7324 */
7325 dst_reg->id = 0;
e434b8cd 7326 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7327 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7328 } else {
7329 mark_reg_unknown(env, regs,
7330 insn->dst_reg);
1be7f75d 7331 }
3f50f132 7332 zext_32_to_64(dst_reg);
17a52670
AS
7333 }
7334 } else {
7335 /* case: R = imm
7336 * remember the value we stored into this reg
7337 */
fbeb1603
AF
7338 /* clear any state __mark_reg_known doesn't set */
7339 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7340 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7341 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7342 __mark_reg_known(regs + insn->dst_reg,
7343 insn->imm);
7344 } else {
7345 __mark_reg_known(regs + insn->dst_reg,
7346 (u32)insn->imm);
7347 }
17a52670
AS
7348 }
7349
7350 } else if (opcode > BPF_END) {
61bd5218 7351 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7352 return -EINVAL;
7353
7354 } else { /* all other ALU ops: and, sub, xor, add, ... */
7355
17a52670
AS
7356 if (BPF_SRC(insn->code) == BPF_X) {
7357 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7358 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7359 return -EINVAL;
7360 }
7361 /* check src1 operand */
dc503a8a 7362 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7363 if (err)
7364 return err;
7365 } else {
7366 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7367 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7368 return -EINVAL;
7369 }
7370 }
7371
7372 /* check src2 operand */
dc503a8a 7373 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7374 if (err)
7375 return err;
7376
7377 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7378 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7379 verbose(env, "div by zero\n");
17a52670
AS
7380 return -EINVAL;
7381 }
7382
229394e8
RV
7383 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7384 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7385 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7386
7387 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7388 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7389 return -EINVAL;
7390 }
7391 }
7392
1a0dc1ac 7393 /* check dest operand */
dc503a8a 7394 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7395 if (err)
7396 return err;
7397
f1174f77 7398 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7399 }
7400
7401 return 0;
7402}
7403
c6a9efa1
PC
7404static void __find_good_pkt_pointers(struct bpf_func_state *state,
7405 struct bpf_reg_state *dst_reg,
6d94e741 7406 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7407{
7408 struct bpf_reg_state *reg;
7409 int i;
7410
7411 for (i = 0; i < MAX_BPF_REG; i++) {
7412 reg = &state->regs[i];
7413 if (reg->type == type && reg->id == dst_reg->id)
7414 /* keep the maximum range already checked */
7415 reg->range = max(reg->range, new_range);
7416 }
7417
7418 bpf_for_each_spilled_reg(i, state, reg) {
7419 if (!reg)
7420 continue;
7421 if (reg->type == type && reg->id == dst_reg->id)
7422 reg->range = max(reg->range, new_range);
7423 }
7424}
7425
f4d7e40a 7426static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7427 struct bpf_reg_state *dst_reg,
f8ddadc4 7428 enum bpf_reg_type type,
fb2a311a 7429 bool range_right_open)
969bf05e 7430{
6d94e741 7431 int new_range, i;
2d2be8ca 7432
fb2a311a
DB
7433 if (dst_reg->off < 0 ||
7434 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7435 /* This doesn't give us any range */
7436 return;
7437
b03c9f9f
EC
7438 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7439 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7440 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7441 * than pkt_end, but that's because it's also less than pkt.
7442 */
7443 return;
7444
fb2a311a
DB
7445 new_range = dst_reg->off;
7446 if (range_right_open)
7447 new_range--;
7448
7449 /* Examples for register markings:
2d2be8ca 7450 *
fb2a311a 7451 * pkt_data in dst register:
2d2be8ca
DB
7452 *
7453 * r2 = r3;
7454 * r2 += 8;
7455 * if (r2 > pkt_end) goto <handle exception>
7456 * <access okay>
7457 *
b4e432f1
DB
7458 * r2 = r3;
7459 * r2 += 8;
7460 * if (r2 < pkt_end) goto <access okay>
7461 * <handle exception>
7462 *
2d2be8ca
DB
7463 * Where:
7464 * r2 == dst_reg, pkt_end == src_reg
7465 * r2=pkt(id=n,off=8,r=0)
7466 * r3=pkt(id=n,off=0,r=0)
7467 *
fb2a311a 7468 * pkt_data in src register:
2d2be8ca
DB
7469 *
7470 * r2 = r3;
7471 * r2 += 8;
7472 * if (pkt_end >= r2) goto <access okay>
7473 * <handle exception>
7474 *
b4e432f1
DB
7475 * r2 = r3;
7476 * r2 += 8;
7477 * if (pkt_end <= r2) goto <handle exception>
7478 * <access okay>
7479 *
2d2be8ca
DB
7480 * Where:
7481 * pkt_end == dst_reg, r2 == src_reg
7482 * r2=pkt(id=n,off=8,r=0)
7483 * r3=pkt(id=n,off=0,r=0)
7484 *
7485 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
7486 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7487 * and [r3, r3 + 8-1) respectively is safe to access depending on
7488 * the check.
969bf05e 7489 */
2d2be8ca 7490
f1174f77
EC
7491 /* If our ids match, then we must have the same max_value. And we
7492 * don't care about the other reg's fixed offset, since if it's too big
7493 * the range won't allow anything.
7494 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7495 */
c6a9efa1
PC
7496 for (i = 0; i <= vstate->curframe; i++)
7497 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7498 new_range);
969bf05e
AS
7499}
7500
3f50f132 7501static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 7502{
3f50f132
JF
7503 struct tnum subreg = tnum_subreg(reg->var_off);
7504 s32 sval = (s32)val;
a72dafaf 7505
3f50f132
JF
7506 switch (opcode) {
7507 case BPF_JEQ:
7508 if (tnum_is_const(subreg))
7509 return !!tnum_equals_const(subreg, val);
7510 break;
7511 case BPF_JNE:
7512 if (tnum_is_const(subreg))
7513 return !tnum_equals_const(subreg, val);
7514 break;
7515 case BPF_JSET:
7516 if ((~subreg.mask & subreg.value) & val)
7517 return 1;
7518 if (!((subreg.mask | subreg.value) & val))
7519 return 0;
7520 break;
7521 case BPF_JGT:
7522 if (reg->u32_min_value > val)
7523 return 1;
7524 else if (reg->u32_max_value <= val)
7525 return 0;
7526 break;
7527 case BPF_JSGT:
7528 if (reg->s32_min_value > sval)
7529 return 1;
ee114dd6 7530 else if (reg->s32_max_value <= sval)
3f50f132
JF
7531 return 0;
7532 break;
7533 case BPF_JLT:
7534 if (reg->u32_max_value < val)
7535 return 1;
7536 else if (reg->u32_min_value >= val)
7537 return 0;
7538 break;
7539 case BPF_JSLT:
7540 if (reg->s32_max_value < sval)
7541 return 1;
7542 else if (reg->s32_min_value >= sval)
7543 return 0;
7544 break;
7545 case BPF_JGE:
7546 if (reg->u32_min_value >= val)
7547 return 1;
7548 else if (reg->u32_max_value < val)
7549 return 0;
7550 break;
7551 case BPF_JSGE:
7552 if (reg->s32_min_value >= sval)
7553 return 1;
7554 else if (reg->s32_max_value < sval)
7555 return 0;
7556 break;
7557 case BPF_JLE:
7558 if (reg->u32_max_value <= val)
7559 return 1;
7560 else if (reg->u32_min_value > val)
7561 return 0;
7562 break;
7563 case BPF_JSLE:
7564 if (reg->s32_max_value <= sval)
7565 return 1;
7566 else if (reg->s32_min_value > sval)
7567 return 0;
7568 break;
7569 }
4f7b3e82 7570
3f50f132
JF
7571 return -1;
7572}
092ed096 7573
3f50f132
JF
7574
7575static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7576{
7577 s64 sval = (s64)val;
a72dafaf 7578
4f7b3e82
AS
7579 switch (opcode) {
7580 case BPF_JEQ:
7581 if (tnum_is_const(reg->var_off))
7582 return !!tnum_equals_const(reg->var_off, val);
7583 break;
7584 case BPF_JNE:
7585 if (tnum_is_const(reg->var_off))
7586 return !tnum_equals_const(reg->var_off, val);
7587 break;
960ea056
JK
7588 case BPF_JSET:
7589 if ((~reg->var_off.mask & reg->var_off.value) & val)
7590 return 1;
7591 if (!((reg->var_off.mask | reg->var_off.value) & val))
7592 return 0;
7593 break;
4f7b3e82
AS
7594 case BPF_JGT:
7595 if (reg->umin_value > val)
7596 return 1;
7597 else if (reg->umax_value <= val)
7598 return 0;
7599 break;
7600 case BPF_JSGT:
a72dafaf 7601 if (reg->smin_value > sval)
4f7b3e82 7602 return 1;
ee114dd6 7603 else if (reg->smax_value <= sval)
4f7b3e82
AS
7604 return 0;
7605 break;
7606 case BPF_JLT:
7607 if (reg->umax_value < val)
7608 return 1;
7609 else if (reg->umin_value >= val)
7610 return 0;
7611 break;
7612 case BPF_JSLT:
a72dafaf 7613 if (reg->smax_value < sval)
4f7b3e82 7614 return 1;
a72dafaf 7615 else if (reg->smin_value >= sval)
4f7b3e82
AS
7616 return 0;
7617 break;
7618 case BPF_JGE:
7619 if (reg->umin_value >= val)
7620 return 1;
7621 else if (reg->umax_value < val)
7622 return 0;
7623 break;
7624 case BPF_JSGE:
a72dafaf 7625 if (reg->smin_value >= sval)
4f7b3e82 7626 return 1;
a72dafaf 7627 else if (reg->smax_value < sval)
4f7b3e82
AS
7628 return 0;
7629 break;
7630 case BPF_JLE:
7631 if (reg->umax_value <= val)
7632 return 1;
7633 else if (reg->umin_value > val)
7634 return 0;
7635 break;
7636 case BPF_JSLE:
a72dafaf 7637 if (reg->smax_value <= sval)
4f7b3e82 7638 return 1;
a72dafaf 7639 else if (reg->smin_value > sval)
4f7b3e82
AS
7640 return 0;
7641 break;
7642 }
7643
7644 return -1;
7645}
7646
3f50f132
JF
7647/* compute branch direction of the expression "if (reg opcode val) goto target;"
7648 * and return:
7649 * 1 - branch will be taken and "goto target" will be executed
7650 * 0 - branch will not be taken and fall-through to next insn
7651 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7652 * range [0,10]
604dca5e 7653 */
3f50f132
JF
7654static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7655 bool is_jmp32)
604dca5e 7656{
cac616db
JF
7657 if (__is_pointer_value(false, reg)) {
7658 if (!reg_type_not_null(reg->type))
7659 return -1;
7660
7661 /* If pointer is valid tests against zero will fail so we can
7662 * use this to direct branch taken.
7663 */
7664 if (val != 0)
7665 return -1;
7666
7667 switch (opcode) {
7668 case BPF_JEQ:
7669 return 0;
7670 case BPF_JNE:
7671 return 1;
7672 default:
7673 return -1;
7674 }
7675 }
604dca5e 7676
3f50f132
JF
7677 if (is_jmp32)
7678 return is_branch32_taken(reg, val, opcode);
7679 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
7680}
7681
6d94e741
AS
7682static int flip_opcode(u32 opcode)
7683{
7684 /* How can we transform "a <op> b" into "b <op> a"? */
7685 static const u8 opcode_flip[16] = {
7686 /* these stay the same */
7687 [BPF_JEQ >> 4] = BPF_JEQ,
7688 [BPF_JNE >> 4] = BPF_JNE,
7689 [BPF_JSET >> 4] = BPF_JSET,
7690 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7691 [BPF_JGE >> 4] = BPF_JLE,
7692 [BPF_JGT >> 4] = BPF_JLT,
7693 [BPF_JLE >> 4] = BPF_JGE,
7694 [BPF_JLT >> 4] = BPF_JGT,
7695 [BPF_JSGE >> 4] = BPF_JSLE,
7696 [BPF_JSGT >> 4] = BPF_JSLT,
7697 [BPF_JSLE >> 4] = BPF_JSGE,
7698 [BPF_JSLT >> 4] = BPF_JSGT
7699 };
7700 return opcode_flip[opcode >> 4];
7701}
7702
7703static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7704 struct bpf_reg_state *src_reg,
7705 u8 opcode)
7706{
7707 struct bpf_reg_state *pkt;
7708
7709 if (src_reg->type == PTR_TO_PACKET_END) {
7710 pkt = dst_reg;
7711 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7712 pkt = src_reg;
7713 opcode = flip_opcode(opcode);
7714 } else {
7715 return -1;
7716 }
7717
7718 if (pkt->range >= 0)
7719 return -1;
7720
7721 switch (opcode) {
7722 case BPF_JLE:
7723 /* pkt <= pkt_end */
7724 fallthrough;
7725 case BPF_JGT:
7726 /* pkt > pkt_end */
7727 if (pkt->range == BEYOND_PKT_END)
7728 /* pkt has at last one extra byte beyond pkt_end */
7729 return opcode == BPF_JGT;
7730 break;
7731 case BPF_JLT:
7732 /* pkt < pkt_end */
7733 fallthrough;
7734 case BPF_JGE:
7735 /* pkt >= pkt_end */
7736 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7737 return opcode == BPF_JGE;
7738 break;
7739 }
7740 return -1;
7741}
7742
48461135
JB
7743/* Adjusts the register min/max values in the case that the dst_reg is the
7744 * variable register that we are working on, and src_reg is a constant or we're
7745 * simply doing a BPF_K check.
f1174f77 7746 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
7747 */
7748static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
7749 struct bpf_reg_state *false_reg,
7750 u64 val, u32 val32,
092ed096 7751 u8 opcode, bool is_jmp32)
48461135 7752{
3f50f132
JF
7753 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7754 struct tnum false_64off = false_reg->var_off;
7755 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7756 struct tnum true_64off = true_reg->var_off;
7757 s64 sval = (s64)val;
7758 s32 sval32 = (s32)val32;
a72dafaf 7759
f1174f77
EC
7760 /* If the dst_reg is a pointer, we can't learn anything about its
7761 * variable offset from the compare (unless src_reg were a pointer into
7762 * the same object, but we don't bother with that.
7763 * Since false_reg and true_reg have the same type by construction, we
7764 * only need to check one of them for pointerness.
7765 */
7766 if (__is_pointer_value(false, false_reg))
7767 return;
4cabc5b1 7768
48461135
JB
7769 switch (opcode) {
7770 case BPF_JEQ:
48461135 7771 case BPF_JNE:
a72dafaf
JW
7772 {
7773 struct bpf_reg_state *reg =
7774 opcode == BPF_JEQ ? true_reg : false_reg;
7775
e688c3db
AS
7776 /* JEQ/JNE comparison doesn't change the register equivalence.
7777 * r1 = r2;
7778 * if (r1 == 42) goto label;
7779 * ...
7780 * label: // here both r1 and r2 are known to be 42.
7781 *
7782 * Hence when marking register as known preserve it's ID.
48461135 7783 */
3f50f132
JF
7784 if (is_jmp32)
7785 __mark_reg32_known(reg, val32);
7786 else
e688c3db 7787 ___mark_reg_known(reg, val);
48461135 7788 break;
a72dafaf 7789 }
960ea056 7790 case BPF_JSET:
3f50f132
JF
7791 if (is_jmp32) {
7792 false_32off = tnum_and(false_32off, tnum_const(~val32));
7793 if (is_power_of_2(val32))
7794 true_32off = tnum_or(true_32off,
7795 tnum_const(val32));
7796 } else {
7797 false_64off = tnum_and(false_64off, tnum_const(~val));
7798 if (is_power_of_2(val))
7799 true_64off = tnum_or(true_64off,
7800 tnum_const(val));
7801 }
960ea056 7802 break;
48461135 7803 case BPF_JGE:
a72dafaf
JW
7804 case BPF_JGT:
7805 {
3f50f132
JF
7806 if (is_jmp32) {
7807 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7808 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7809
7810 false_reg->u32_max_value = min(false_reg->u32_max_value,
7811 false_umax);
7812 true_reg->u32_min_value = max(true_reg->u32_min_value,
7813 true_umin);
7814 } else {
7815 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7816 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7817
7818 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7819 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7820 }
b03c9f9f 7821 break;
a72dafaf 7822 }
48461135 7823 case BPF_JSGE:
a72dafaf
JW
7824 case BPF_JSGT:
7825 {
3f50f132
JF
7826 if (is_jmp32) {
7827 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7828 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 7829
3f50f132
JF
7830 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7831 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7832 } else {
7833 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7834 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7835
7836 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7837 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7838 }
48461135 7839 break;
a72dafaf 7840 }
b4e432f1 7841 case BPF_JLE:
a72dafaf
JW
7842 case BPF_JLT:
7843 {
3f50f132
JF
7844 if (is_jmp32) {
7845 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7846 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7847
7848 false_reg->u32_min_value = max(false_reg->u32_min_value,
7849 false_umin);
7850 true_reg->u32_max_value = min(true_reg->u32_max_value,
7851 true_umax);
7852 } else {
7853 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7854 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7855
7856 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7857 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7858 }
b4e432f1 7859 break;
a72dafaf 7860 }
b4e432f1 7861 case BPF_JSLE:
a72dafaf
JW
7862 case BPF_JSLT:
7863 {
3f50f132
JF
7864 if (is_jmp32) {
7865 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7866 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 7867
3f50f132
JF
7868 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7869 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7870 } else {
7871 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7872 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7873
7874 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7875 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7876 }
b4e432f1 7877 break;
a72dafaf 7878 }
48461135 7879 default:
0fc31b10 7880 return;
48461135
JB
7881 }
7882
3f50f132
JF
7883 if (is_jmp32) {
7884 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7885 tnum_subreg(false_32off));
7886 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7887 tnum_subreg(true_32off));
7888 __reg_combine_32_into_64(false_reg);
7889 __reg_combine_32_into_64(true_reg);
7890 } else {
7891 false_reg->var_off = false_64off;
7892 true_reg->var_off = true_64off;
7893 __reg_combine_64_into_32(false_reg);
7894 __reg_combine_64_into_32(true_reg);
7895 }
48461135
JB
7896}
7897
f1174f77
EC
7898/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7899 * the variable reg.
48461135
JB
7900 */
7901static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
7902 struct bpf_reg_state *false_reg,
7903 u64 val, u32 val32,
092ed096 7904 u8 opcode, bool is_jmp32)
48461135 7905{
6d94e741 7906 opcode = flip_opcode(opcode);
0fc31b10
JH
7907 /* This uses zero as "not present in table"; luckily the zero opcode,
7908 * BPF_JA, can't get here.
b03c9f9f 7909 */
0fc31b10 7910 if (opcode)
3f50f132 7911 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7912}
7913
7914/* Regs are known to be equal, so intersect their min/max/var_off */
7915static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7916 struct bpf_reg_state *dst_reg)
7917{
b03c9f9f
EC
7918 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7919 dst_reg->umin_value);
7920 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7921 dst_reg->umax_value);
7922 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7923 dst_reg->smin_value);
7924 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7925 dst_reg->smax_value);
f1174f77
EC
7926 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7927 dst_reg->var_off);
b03c9f9f
EC
7928 /* We might have learned new bounds from the var_off. */
7929 __update_reg_bounds(src_reg);
7930 __update_reg_bounds(dst_reg);
7931 /* We might have learned something about the sign bit. */
7932 __reg_deduce_bounds(src_reg);
7933 __reg_deduce_bounds(dst_reg);
7934 /* We might have learned some bits from the bounds. */
7935 __reg_bound_offset(src_reg);
7936 __reg_bound_offset(dst_reg);
7937 /* Intersecting with the old var_off might have improved our bounds
7938 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7939 * then new var_off is (0; 0x7f...fc) which improves our umax.
7940 */
7941 __update_reg_bounds(src_reg);
7942 __update_reg_bounds(dst_reg);
f1174f77
EC
7943}
7944
7945static void reg_combine_min_max(struct bpf_reg_state *true_src,
7946 struct bpf_reg_state *true_dst,
7947 struct bpf_reg_state *false_src,
7948 struct bpf_reg_state *false_dst,
7949 u8 opcode)
7950{
7951 switch (opcode) {
7952 case BPF_JEQ:
7953 __reg_combine_min_max(true_src, true_dst);
7954 break;
7955 case BPF_JNE:
7956 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 7957 break;
4cabc5b1 7958 }
48461135
JB
7959}
7960
fd978bf7
JS
7961static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7962 struct bpf_reg_state *reg, u32 id,
840b9615 7963 bool is_null)
57a09bf0 7964{
93c230e3
MKL
7965 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7966 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
7967 /* Old offset (both fixed and variable parts) should
7968 * have been known-zero, because we don't allow pointer
7969 * arithmetic on pointers that might be NULL.
7970 */
b03c9f9f
EC
7971 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7972 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 7973 reg->off)) {
b03c9f9f
EC
7974 __mark_reg_known_zero(reg);
7975 reg->off = 0;
f1174f77
EC
7976 }
7977 if (is_null) {
7978 reg->type = SCALAR_VALUE;
1b986589
MKL
7979 /* We don't need id and ref_obj_id from this point
7980 * onwards anymore, thus we should better reset it,
7981 * so that state pruning has chances to take effect.
7982 */
7983 reg->id = 0;
7984 reg->ref_obj_id = 0;
4ddb7416
DB
7985
7986 return;
7987 }
7988
7989 mark_ptr_not_null_reg(reg);
7990
7991 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
7992 /* For not-NULL ptr, reg->ref_obj_id will be reset
7993 * in release_reg_references().
7994 *
7995 * reg->id is still used by spin_lock ptr. Other
7996 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
7997 */
7998 reg->id = 0;
56f668df 7999 }
57a09bf0
TG
8000 }
8001}
8002
c6a9efa1
PC
8003static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8004 bool is_null)
8005{
8006 struct bpf_reg_state *reg;
8007 int i;
8008
8009 for (i = 0; i < MAX_BPF_REG; i++)
8010 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8011
8012 bpf_for_each_spilled_reg(i, state, reg) {
8013 if (!reg)
8014 continue;
8015 mark_ptr_or_null_reg(state, reg, id, is_null);
8016 }
8017}
8018
57a09bf0
TG
8019/* The logic is similar to find_good_pkt_pointers(), both could eventually
8020 * be folded together at some point.
8021 */
840b9615
JS
8022static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8023 bool is_null)
57a09bf0 8024{
f4d7e40a 8025 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 8026 struct bpf_reg_state *regs = state->regs;
1b986589 8027 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 8028 u32 id = regs[regno].id;
c6a9efa1 8029 int i;
57a09bf0 8030
1b986589
MKL
8031 if (ref_obj_id && ref_obj_id == id && is_null)
8032 /* regs[regno] is in the " == NULL" branch.
8033 * No one could have freed the reference state before
8034 * doing the NULL check.
8035 */
8036 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 8037
c6a9efa1
PC
8038 for (i = 0; i <= vstate->curframe; i++)
8039 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
8040}
8041
5beca081
DB
8042static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8043 struct bpf_reg_state *dst_reg,
8044 struct bpf_reg_state *src_reg,
8045 struct bpf_verifier_state *this_branch,
8046 struct bpf_verifier_state *other_branch)
8047{
8048 if (BPF_SRC(insn->code) != BPF_X)
8049 return false;
8050
092ed096
JW
8051 /* Pointers are always 64-bit. */
8052 if (BPF_CLASS(insn->code) == BPF_JMP32)
8053 return false;
8054
5beca081
DB
8055 switch (BPF_OP(insn->code)) {
8056 case BPF_JGT:
8057 if ((dst_reg->type == PTR_TO_PACKET &&
8058 src_reg->type == PTR_TO_PACKET_END) ||
8059 (dst_reg->type == PTR_TO_PACKET_META &&
8060 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8061 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8062 find_good_pkt_pointers(this_branch, dst_reg,
8063 dst_reg->type, false);
6d94e741 8064 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
8065 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8066 src_reg->type == PTR_TO_PACKET) ||
8067 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8068 src_reg->type == PTR_TO_PACKET_META)) {
8069 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8070 find_good_pkt_pointers(other_branch, src_reg,
8071 src_reg->type, true);
6d94e741 8072 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
8073 } else {
8074 return false;
8075 }
8076 break;
8077 case BPF_JLT:
8078 if ((dst_reg->type == PTR_TO_PACKET &&
8079 src_reg->type == PTR_TO_PACKET_END) ||
8080 (dst_reg->type == PTR_TO_PACKET_META &&
8081 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8082 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8083 find_good_pkt_pointers(other_branch, dst_reg,
8084 dst_reg->type, true);
6d94e741 8085 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
8086 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8087 src_reg->type == PTR_TO_PACKET) ||
8088 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8089 src_reg->type == PTR_TO_PACKET_META)) {
8090 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8091 find_good_pkt_pointers(this_branch, src_reg,
8092 src_reg->type, false);
6d94e741 8093 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
8094 } else {
8095 return false;
8096 }
8097 break;
8098 case BPF_JGE:
8099 if ((dst_reg->type == PTR_TO_PACKET &&
8100 src_reg->type == PTR_TO_PACKET_END) ||
8101 (dst_reg->type == PTR_TO_PACKET_META &&
8102 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8103 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8104 find_good_pkt_pointers(this_branch, dst_reg,
8105 dst_reg->type, true);
6d94e741 8106 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
8107 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8108 src_reg->type == PTR_TO_PACKET) ||
8109 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8110 src_reg->type == PTR_TO_PACKET_META)) {
8111 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8112 find_good_pkt_pointers(other_branch, src_reg,
8113 src_reg->type, false);
6d94e741 8114 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
8115 } else {
8116 return false;
8117 }
8118 break;
8119 case BPF_JLE:
8120 if ((dst_reg->type == PTR_TO_PACKET &&
8121 src_reg->type == PTR_TO_PACKET_END) ||
8122 (dst_reg->type == PTR_TO_PACKET_META &&
8123 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8124 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8125 find_good_pkt_pointers(other_branch, dst_reg,
8126 dst_reg->type, false);
6d94e741 8127 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
8128 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8129 src_reg->type == PTR_TO_PACKET) ||
8130 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8131 src_reg->type == PTR_TO_PACKET_META)) {
8132 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8133 find_good_pkt_pointers(this_branch, src_reg,
8134 src_reg->type, true);
6d94e741 8135 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
8136 } else {
8137 return false;
8138 }
8139 break;
8140 default:
8141 return false;
8142 }
8143
8144 return true;
8145}
8146
75748837
AS
8147static void find_equal_scalars(struct bpf_verifier_state *vstate,
8148 struct bpf_reg_state *known_reg)
8149{
8150 struct bpf_func_state *state;
8151 struct bpf_reg_state *reg;
8152 int i, j;
8153
8154 for (i = 0; i <= vstate->curframe; i++) {
8155 state = vstate->frame[i];
8156 for (j = 0; j < MAX_BPF_REG; j++) {
8157 reg = &state->regs[j];
8158 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8159 *reg = *known_reg;
8160 }
8161
8162 bpf_for_each_spilled_reg(j, state, reg) {
8163 if (!reg)
8164 continue;
8165 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8166 *reg = *known_reg;
8167 }
8168 }
8169}
8170
58e2af8b 8171static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8172 struct bpf_insn *insn, int *insn_idx)
8173{
f4d7e40a
AS
8174 struct bpf_verifier_state *this_branch = env->cur_state;
8175 struct bpf_verifier_state *other_branch;
8176 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8177 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8178 u8 opcode = BPF_OP(insn->code);
092ed096 8179 bool is_jmp32;
fb8d251e 8180 int pred = -1;
17a52670
AS
8181 int err;
8182
092ed096
JW
8183 /* Only conditional jumps are expected to reach here. */
8184 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8185 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8186 return -EINVAL;
8187 }
8188
8189 if (BPF_SRC(insn->code) == BPF_X) {
8190 if (insn->imm != 0) {
092ed096 8191 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8192 return -EINVAL;
8193 }
8194
8195 /* check src1 operand */
dc503a8a 8196 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8197 if (err)
8198 return err;
1be7f75d
AS
8199
8200 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8201 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8202 insn->src_reg);
8203 return -EACCES;
8204 }
fb8d251e 8205 src_reg = &regs[insn->src_reg];
17a52670
AS
8206 } else {
8207 if (insn->src_reg != BPF_REG_0) {
092ed096 8208 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8209 return -EINVAL;
8210 }
8211 }
8212
8213 /* check src2 operand */
dc503a8a 8214 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8215 if (err)
8216 return err;
8217
1a0dc1ac 8218 dst_reg = &regs[insn->dst_reg];
092ed096 8219 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8220
3f50f132
JF
8221 if (BPF_SRC(insn->code) == BPF_K) {
8222 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8223 } else if (src_reg->type == SCALAR_VALUE &&
8224 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8225 pred = is_branch_taken(dst_reg,
8226 tnum_subreg(src_reg->var_off).value,
8227 opcode,
8228 is_jmp32);
8229 } else if (src_reg->type == SCALAR_VALUE &&
8230 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8231 pred = is_branch_taken(dst_reg,
8232 src_reg->var_off.value,
8233 opcode,
8234 is_jmp32);
6d94e741
AS
8235 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8236 reg_is_pkt_pointer_any(src_reg) &&
8237 !is_jmp32) {
8238 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8239 }
8240
b5dc0163 8241 if (pred >= 0) {
cac616db
JF
8242 /* If we get here with a dst_reg pointer type it is because
8243 * above is_branch_taken() special cased the 0 comparison.
8244 */
8245 if (!__is_pointer_value(false, dst_reg))
8246 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8247 if (BPF_SRC(insn->code) == BPF_X && !err &&
8248 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8249 err = mark_chain_precision(env, insn->src_reg);
8250 if (err)
8251 return err;
8252 }
fb8d251e
AS
8253 if (pred == 1) {
8254 /* only follow the goto, ignore fall-through */
8255 *insn_idx += insn->off;
8256 return 0;
8257 } else if (pred == 0) {
8258 /* only follow fall-through branch, since
8259 * that's where the program will go
8260 */
8261 return 0;
17a52670
AS
8262 }
8263
979d63d5
DB
8264 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8265 false);
17a52670
AS
8266 if (!other_branch)
8267 return -EFAULT;
f4d7e40a 8268 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8269
48461135
JB
8270 /* detect if we are comparing against a constant value so we can adjust
8271 * our min/max values for our dst register.
f1174f77
EC
8272 * this is only legit if both are scalars (or pointers to the same
8273 * object, I suppose, but we don't support that right now), because
8274 * otherwise the different base pointers mean the offsets aren't
8275 * comparable.
48461135
JB
8276 */
8277 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8278 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8279
f1174f77 8280 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8281 src_reg->type == SCALAR_VALUE) {
8282 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8283 (is_jmp32 &&
8284 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8285 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8286 dst_reg,
3f50f132
JF
8287 src_reg->var_off.value,
8288 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8289 opcode, is_jmp32);
8290 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8291 (is_jmp32 &&
8292 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8293 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8294 src_reg,
3f50f132
JF
8295 dst_reg->var_off.value,
8296 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8297 opcode, is_jmp32);
8298 else if (!is_jmp32 &&
8299 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8300 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8301 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8302 &other_branch_regs[insn->dst_reg],
092ed096 8303 src_reg, dst_reg, opcode);
e688c3db
AS
8304 if (src_reg->id &&
8305 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8306 find_equal_scalars(this_branch, src_reg);
8307 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8308 }
8309
f1174f77
EC
8310 }
8311 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8312 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8313 dst_reg, insn->imm, (u32)insn->imm,
8314 opcode, is_jmp32);
48461135
JB
8315 }
8316
e688c3db
AS
8317 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8318 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8319 find_equal_scalars(this_branch, dst_reg);
8320 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8321 }
8322
092ed096
JW
8323 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8324 * NOTE: these optimizations below are related with pointer comparison
8325 * which will never be JMP32.
8326 */
8327 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8328 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8329 reg_type_may_be_null(dst_reg->type)) {
8330 /* Mark all identical registers in each branch as either
57a09bf0
TG
8331 * safe or unknown depending R == 0 or R != 0 conditional.
8332 */
840b9615
JS
8333 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8334 opcode == BPF_JNE);
8335 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8336 opcode == BPF_JEQ);
5beca081
DB
8337 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8338 this_branch, other_branch) &&
8339 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8340 verbose(env, "R%d pointer comparison prohibited\n",
8341 insn->dst_reg);
1be7f75d 8342 return -EACCES;
17a52670 8343 }
06ee7115 8344 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8345 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8346 return 0;
8347}
8348
17a52670 8349/* verify BPF_LD_IMM64 instruction */
58e2af8b 8350static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8351{
d8eca5bb 8352 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8353 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8354 struct bpf_reg_state *dst_reg;
d8eca5bb 8355 struct bpf_map *map;
17a52670
AS
8356 int err;
8357
8358 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8359 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8360 return -EINVAL;
8361 }
8362 if (insn->off != 0) {
61bd5218 8363 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8364 return -EINVAL;
8365 }
8366
dc503a8a 8367 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8368 if (err)
8369 return err;
8370
4976b718 8371 dst_reg = &regs[insn->dst_reg];
6b173873 8372 if (insn->src_reg == 0) {
6b173873
JK
8373 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8374
4976b718 8375 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8376 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8377 return 0;
6b173873 8378 }
17a52670 8379
4976b718
HL
8380 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8381 mark_reg_known_zero(env, regs, insn->dst_reg);
8382
8383 dst_reg->type = aux->btf_var.reg_type;
8384 switch (dst_reg->type) {
8385 case PTR_TO_MEM:
8386 dst_reg->mem_size = aux->btf_var.mem_size;
8387 break;
8388 case PTR_TO_BTF_ID:
eaa6bcb7 8389 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8390 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8391 dst_reg->btf_id = aux->btf_var.btf_id;
8392 break;
8393 default:
8394 verbose(env, "bpf verifier is misconfigured\n");
8395 return -EFAULT;
8396 }
8397 return 0;
8398 }
8399
69c087ba
YS
8400 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8401 struct bpf_prog_aux *aux = env->prog->aux;
8402 u32 subprogno = insn[1].imm;
8403
8404 if (!aux->func_info) {
8405 verbose(env, "missing btf func_info\n");
8406 return -EINVAL;
8407 }
8408 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8409 verbose(env, "callback function not static\n");
8410 return -EINVAL;
8411 }
8412
8413 dst_reg->type = PTR_TO_FUNC;
8414 dst_reg->subprogno = subprogno;
8415 return 0;
8416 }
8417
d8eca5bb
DB
8418 map = env->used_maps[aux->map_index];
8419 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8420 dst_reg->map_ptr = map;
d8eca5bb
DB
8421
8422 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
4976b718
HL
8423 dst_reg->type = PTR_TO_MAP_VALUE;
8424 dst_reg->off = aux->map_off;
d8eca5bb 8425 if (map_value_has_spin_lock(map))
4976b718 8426 dst_reg->id = ++env->id_gen;
d8eca5bb 8427 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
4976b718 8428 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8429 } else {
8430 verbose(env, "bpf verifier is misconfigured\n");
8431 return -EINVAL;
8432 }
17a52670 8433
17a52670
AS
8434 return 0;
8435}
8436
96be4325
DB
8437static bool may_access_skb(enum bpf_prog_type type)
8438{
8439 switch (type) {
8440 case BPF_PROG_TYPE_SOCKET_FILTER:
8441 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 8442 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
8443 return true;
8444 default:
8445 return false;
8446 }
8447}
8448
ddd872bc
AS
8449/* verify safety of LD_ABS|LD_IND instructions:
8450 * - they can only appear in the programs where ctx == skb
8451 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8452 * preserve R6-R9, and store return value into R0
8453 *
8454 * Implicit input:
8455 * ctx == skb == R6 == CTX
8456 *
8457 * Explicit input:
8458 * SRC == any register
8459 * IMM == 32-bit immediate
8460 *
8461 * Output:
8462 * R0 - 8/16/32-bit skb data converted to cpu endianness
8463 */
58e2af8b 8464static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 8465{
638f5b90 8466 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 8467 static const int ctx_reg = BPF_REG_6;
ddd872bc 8468 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
8469 int i, err;
8470
7e40781c 8471 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 8472 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
8473 return -EINVAL;
8474 }
8475
e0cea7ce
DB
8476 if (!env->ops->gen_ld_abs) {
8477 verbose(env, "bpf verifier is misconfigured\n");
8478 return -EINVAL;
8479 }
8480
ddd872bc 8481 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 8482 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 8483 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 8484 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
8485 return -EINVAL;
8486 }
8487
8488 /* check whether implicit source operand (register R6) is readable */
6d4f151a 8489 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
8490 if (err)
8491 return err;
8492
fd978bf7
JS
8493 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8494 * gen_ld_abs() may terminate the program at runtime, leading to
8495 * reference leak.
8496 */
8497 err = check_reference_leak(env);
8498 if (err) {
8499 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8500 return err;
8501 }
8502
d83525ca
AS
8503 if (env->cur_state->active_spin_lock) {
8504 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8505 return -EINVAL;
8506 }
8507
6d4f151a 8508 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
8509 verbose(env,
8510 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
8511 return -EINVAL;
8512 }
8513
8514 if (mode == BPF_IND) {
8515 /* check explicit source operand */
dc503a8a 8516 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
8517 if (err)
8518 return err;
8519 }
8520
6d4f151a
DB
8521 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8522 if (err < 0)
8523 return err;
8524
ddd872bc 8525 /* reset caller saved regs to unreadable */
dc503a8a 8526 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 8527 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
8528 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8529 }
ddd872bc
AS
8530
8531 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
8532 * the value fetched from the packet.
8533 * Already marked as written above.
ddd872bc 8534 */
61bd5218 8535 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
8536 /* ld_abs load up to 32-bit skb data. */
8537 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
8538 return 0;
8539}
8540
390ee7e2
AS
8541static int check_return_code(struct bpf_verifier_env *env)
8542{
5cf1e914 8543 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 8544 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
8545 struct bpf_reg_state *reg;
8546 struct tnum range = tnum_range(0, 1);
7e40781c 8547 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 8548 int err;
f782e2c3 8549 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 8550
9e4e01df 8551 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
8552 if (!is_subprog &&
8553 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 8554 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
8555 !prog->aux->attach_func_proto->type)
8556 return 0;
8557
8558 /* eBPF calling convetion is such that R0 is used
8559 * to return the value from eBPF program.
8560 * Make sure that it's readable at this time
8561 * of bpf_exit, which means that program wrote
8562 * something into it earlier
8563 */
8564 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8565 if (err)
8566 return err;
8567
8568 if (is_pointer_value(env, BPF_REG_0)) {
8569 verbose(env, "R0 leaks addr as return value\n");
8570 return -EACCES;
8571 }
390ee7e2 8572
f782e2c3
DB
8573 reg = cur_regs(env) + BPF_REG_0;
8574 if (is_subprog) {
8575 if (reg->type != SCALAR_VALUE) {
8576 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8577 reg_type_str[reg->type]);
8578 return -EINVAL;
8579 }
8580 return 0;
8581 }
8582
7e40781c 8583 switch (prog_type) {
983695fa
DB
8584 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8585 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
8586 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8587 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8588 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8589 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8590 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 8591 range = tnum_range(1, 1);
77241217
SF
8592 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8593 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8594 range = tnum_range(0, 3);
ed4ed404 8595 break;
390ee7e2 8596 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 8597 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8598 range = tnum_range(0, 3);
8599 enforce_attach_type_range = tnum_range(2, 3);
8600 }
ed4ed404 8601 break;
390ee7e2
AS
8602 case BPF_PROG_TYPE_CGROUP_SOCK:
8603 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 8604 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 8605 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 8606 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 8607 break;
15ab09bd
AS
8608 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8609 if (!env->prog->aux->attach_btf_id)
8610 return 0;
8611 range = tnum_const(0);
8612 break;
15d83c4d 8613 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
8614 switch (env->prog->expected_attach_type) {
8615 case BPF_TRACE_FENTRY:
8616 case BPF_TRACE_FEXIT:
8617 range = tnum_const(0);
8618 break;
8619 case BPF_TRACE_RAW_TP:
8620 case BPF_MODIFY_RETURN:
15d83c4d 8621 return 0;
2ec0616e
DB
8622 case BPF_TRACE_ITER:
8623 break;
e92888c7
YS
8624 default:
8625 return -ENOTSUPP;
8626 }
15d83c4d 8627 break;
e9ddbb77
JS
8628 case BPF_PROG_TYPE_SK_LOOKUP:
8629 range = tnum_range(SK_DROP, SK_PASS);
8630 break;
e92888c7
YS
8631 case BPF_PROG_TYPE_EXT:
8632 /* freplace program can return anything as its return value
8633 * depends on the to-be-replaced kernel func or bpf program.
8634 */
390ee7e2
AS
8635 default:
8636 return 0;
8637 }
8638
390ee7e2 8639 if (reg->type != SCALAR_VALUE) {
61bd5218 8640 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
8641 reg_type_str[reg->type]);
8642 return -EINVAL;
8643 }
8644
8645 if (!tnum_in(range, reg->var_off)) {
bc2591d6 8646 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
8647 return -EINVAL;
8648 }
5cf1e914 8649
8650 if (!tnum_is_unknown(enforce_attach_type_range) &&
8651 tnum_in(enforce_attach_type_range, reg->var_off))
8652 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
8653 return 0;
8654}
8655
475fb78f
AS
8656/* non-recursive DFS pseudo code
8657 * 1 procedure DFS-iterative(G,v):
8658 * 2 label v as discovered
8659 * 3 let S be a stack
8660 * 4 S.push(v)
8661 * 5 while S is not empty
8662 * 6 t <- S.pop()
8663 * 7 if t is what we're looking for:
8664 * 8 return t
8665 * 9 for all edges e in G.adjacentEdges(t) do
8666 * 10 if edge e is already labelled
8667 * 11 continue with the next edge
8668 * 12 w <- G.adjacentVertex(t,e)
8669 * 13 if vertex w is not discovered and not explored
8670 * 14 label e as tree-edge
8671 * 15 label w as discovered
8672 * 16 S.push(w)
8673 * 17 continue at 5
8674 * 18 else if vertex w is discovered
8675 * 19 label e as back-edge
8676 * 20 else
8677 * 21 // vertex w is explored
8678 * 22 label e as forward- or cross-edge
8679 * 23 label t as explored
8680 * 24 S.pop()
8681 *
8682 * convention:
8683 * 0x10 - discovered
8684 * 0x11 - discovered and fall-through edge labelled
8685 * 0x12 - discovered and fall-through and branch edges labelled
8686 * 0x20 - explored
8687 */
8688
8689enum {
8690 DISCOVERED = 0x10,
8691 EXPLORED = 0x20,
8692 FALLTHROUGH = 1,
8693 BRANCH = 2,
8694};
8695
dc2a4ebc
AS
8696static u32 state_htab_size(struct bpf_verifier_env *env)
8697{
8698 return env->prog->len;
8699}
8700
5d839021
AS
8701static struct bpf_verifier_state_list **explored_state(
8702 struct bpf_verifier_env *env,
8703 int idx)
8704{
dc2a4ebc
AS
8705 struct bpf_verifier_state *cur = env->cur_state;
8706 struct bpf_func_state *state = cur->frame[cur->curframe];
8707
8708 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
8709}
8710
8711static void init_explored_state(struct bpf_verifier_env *env, int idx)
8712{
a8f500af 8713 env->insn_aux_data[idx].prune_point = true;
5d839021 8714}
f1bca824 8715
59e2e27d
WAF
8716enum {
8717 DONE_EXPLORING = 0,
8718 KEEP_EXPLORING = 1,
8719};
8720
475fb78f
AS
8721/* t, w, e - match pseudo-code above:
8722 * t - index of current instruction
8723 * w - next instruction
8724 * e - edge
8725 */
2589726d
AS
8726static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8727 bool loop_ok)
475fb78f 8728{
7df737e9
AS
8729 int *insn_stack = env->cfg.insn_stack;
8730 int *insn_state = env->cfg.insn_state;
8731
475fb78f 8732 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 8733 return DONE_EXPLORING;
475fb78f
AS
8734
8735 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 8736 return DONE_EXPLORING;
475fb78f
AS
8737
8738 if (w < 0 || w >= env->prog->len) {
d9762e84 8739 verbose_linfo(env, t, "%d: ", t);
61bd5218 8740 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
8741 return -EINVAL;
8742 }
8743
f1bca824
AS
8744 if (e == BRANCH)
8745 /* mark branch target for state pruning */
5d839021 8746 init_explored_state(env, w);
f1bca824 8747
475fb78f
AS
8748 if (insn_state[w] == 0) {
8749 /* tree-edge */
8750 insn_state[t] = DISCOVERED | e;
8751 insn_state[w] = DISCOVERED;
7df737e9 8752 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 8753 return -E2BIG;
7df737e9 8754 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 8755 return KEEP_EXPLORING;
475fb78f 8756 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 8757 if (loop_ok && env->bpf_capable)
59e2e27d 8758 return DONE_EXPLORING;
d9762e84
MKL
8759 verbose_linfo(env, t, "%d: ", t);
8760 verbose_linfo(env, w, "%d: ", w);
61bd5218 8761 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
8762 return -EINVAL;
8763 } else if (insn_state[w] == EXPLORED) {
8764 /* forward- or cross-edge */
8765 insn_state[t] = DISCOVERED | e;
8766 } else {
61bd5218 8767 verbose(env, "insn state internal bug\n");
475fb78f
AS
8768 return -EFAULT;
8769 }
59e2e27d
WAF
8770 return DONE_EXPLORING;
8771}
8772
efdb22de
YS
8773static int visit_func_call_insn(int t, int insn_cnt,
8774 struct bpf_insn *insns,
8775 struct bpf_verifier_env *env,
8776 bool visit_callee)
8777{
8778 int ret;
8779
8780 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8781 if (ret)
8782 return ret;
8783
8784 if (t + 1 < insn_cnt)
8785 init_explored_state(env, t + 1);
8786 if (visit_callee) {
8787 init_explored_state(env, t);
8788 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8789 env, false);
8790 }
8791 return ret;
8792}
8793
59e2e27d
WAF
8794/* Visits the instruction at index t and returns one of the following:
8795 * < 0 - an error occurred
8796 * DONE_EXPLORING - the instruction was fully explored
8797 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8798 */
8799static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8800{
8801 struct bpf_insn *insns = env->prog->insnsi;
8802 int ret;
8803
69c087ba
YS
8804 if (bpf_pseudo_func(insns + t))
8805 return visit_func_call_insn(t, insn_cnt, insns, env, true);
8806
59e2e27d
WAF
8807 /* All non-branch instructions have a single fall-through edge. */
8808 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8809 BPF_CLASS(insns[t].code) != BPF_JMP32)
8810 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8811
8812 switch (BPF_OP(insns[t].code)) {
8813 case BPF_EXIT:
8814 return DONE_EXPLORING;
8815
8816 case BPF_CALL:
efdb22de
YS
8817 return visit_func_call_insn(t, insn_cnt, insns, env,
8818 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
8819
8820 case BPF_JA:
8821 if (BPF_SRC(insns[t].code) != BPF_K)
8822 return -EINVAL;
8823
8824 /* unconditional jump with single edge */
8825 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8826 true);
8827 if (ret)
8828 return ret;
8829
8830 /* unconditional jmp is not a good pruning point,
8831 * but it's marked, since backtracking needs
8832 * to record jmp history in is_state_visited().
8833 */
8834 init_explored_state(env, t + insns[t].off + 1);
8835 /* tell verifier to check for equivalent states
8836 * after every call and jump
8837 */
8838 if (t + 1 < insn_cnt)
8839 init_explored_state(env, t + 1);
8840
8841 return ret;
8842
8843 default:
8844 /* conditional jump with two edges */
8845 init_explored_state(env, t);
8846 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8847 if (ret)
8848 return ret;
8849
8850 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8851 }
475fb78f
AS
8852}
8853
8854/* non-recursive depth-first-search to detect loops in BPF program
8855 * loop == back-edge in directed graph
8856 */
58e2af8b 8857static int check_cfg(struct bpf_verifier_env *env)
475fb78f 8858{
475fb78f 8859 int insn_cnt = env->prog->len;
7df737e9 8860 int *insn_stack, *insn_state;
475fb78f 8861 int ret = 0;
59e2e27d 8862 int i;
475fb78f 8863
7df737e9 8864 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
8865 if (!insn_state)
8866 return -ENOMEM;
8867
7df737e9 8868 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 8869 if (!insn_stack) {
71dde681 8870 kvfree(insn_state);
475fb78f
AS
8871 return -ENOMEM;
8872 }
8873
8874 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8875 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 8876 env->cfg.cur_stack = 1;
475fb78f 8877
59e2e27d
WAF
8878 while (env->cfg.cur_stack > 0) {
8879 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 8880
59e2e27d
WAF
8881 ret = visit_insn(t, insn_cnt, env);
8882 switch (ret) {
8883 case DONE_EXPLORING:
8884 insn_state[t] = EXPLORED;
8885 env->cfg.cur_stack--;
8886 break;
8887 case KEEP_EXPLORING:
8888 break;
8889 default:
8890 if (ret > 0) {
8891 verbose(env, "visit_insn internal bug\n");
8892 ret = -EFAULT;
475fb78f 8893 }
475fb78f 8894 goto err_free;
59e2e27d 8895 }
475fb78f
AS
8896 }
8897
59e2e27d 8898 if (env->cfg.cur_stack < 0) {
61bd5218 8899 verbose(env, "pop stack internal bug\n");
475fb78f
AS
8900 ret = -EFAULT;
8901 goto err_free;
8902 }
475fb78f 8903
475fb78f
AS
8904 for (i = 0; i < insn_cnt; i++) {
8905 if (insn_state[i] != EXPLORED) {
61bd5218 8906 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
8907 ret = -EINVAL;
8908 goto err_free;
8909 }
8910 }
8911 ret = 0; /* cfg looks good */
8912
8913err_free:
71dde681
AS
8914 kvfree(insn_state);
8915 kvfree(insn_stack);
7df737e9 8916 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
8917 return ret;
8918}
8919
09b28d76
AS
8920static int check_abnormal_return(struct bpf_verifier_env *env)
8921{
8922 int i;
8923
8924 for (i = 1; i < env->subprog_cnt; i++) {
8925 if (env->subprog_info[i].has_ld_abs) {
8926 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8927 return -EINVAL;
8928 }
8929 if (env->subprog_info[i].has_tail_call) {
8930 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8931 return -EINVAL;
8932 }
8933 }
8934 return 0;
8935}
8936
838e9690
YS
8937/* The minimum supported BTF func info size */
8938#define MIN_BPF_FUNCINFO_SIZE 8
8939#define MAX_FUNCINFO_REC_SIZE 252
8940
c454a46b
MKL
8941static int check_btf_func(struct bpf_verifier_env *env,
8942 const union bpf_attr *attr,
8943 union bpf_attr __user *uattr)
838e9690 8944{
09b28d76 8945 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 8946 u32 i, nfuncs, urec_size, min_size;
838e9690 8947 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 8948 struct bpf_func_info *krecord;
8c1b6e69 8949 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
8950 struct bpf_prog *prog;
8951 const struct btf *btf;
838e9690 8952 void __user *urecord;
d0b2818e 8953 u32 prev_offset = 0;
09b28d76 8954 bool scalar_return;
e7ed83d6 8955 int ret = -ENOMEM;
838e9690
YS
8956
8957 nfuncs = attr->func_info_cnt;
09b28d76
AS
8958 if (!nfuncs) {
8959 if (check_abnormal_return(env))
8960 return -EINVAL;
838e9690 8961 return 0;
09b28d76 8962 }
838e9690
YS
8963
8964 if (nfuncs != env->subprog_cnt) {
8965 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8966 return -EINVAL;
8967 }
8968
8969 urec_size = attr->func_info_rec_size;
8970 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8971 urec_size > MAX_FUNCINFO_REC_SIZE ||
8972 urec_size % sizeof(u32)) {
8973 verbose(env, "invalid func info rec size %u\n", urec_size);
8974 return -EINVAL;
8975 }
8976
c454a46b
MKL
8977 prog = env->prog;
8978 btf = prog->aux->btf;
838e9690
YS
8979
8980 urecord = u64_to_user_ptr(attr->func_info);
8981 min_size = min_t(u32, krec_size, urec_size);
8982
ba64e7d8 8983 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
8984 if (!krecord)
8985 return -ENOMEM;
8c1b6e69
AS
8986 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8987 if (!info_aux)
8988 goto err_free;
ba64e7d8 8989
838e9690
YS
8990 for (i = 0; i < nfuncs; i++) {
8991 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8992 if (ret) {
8993 if (ret == -E2BIG) {
8994 verbose(env, "nonzero tailing record in func info");
8995 /* set the size kernel expects so loader can zero
8996 * out the rest of the record.
8997 */
8998 if (put_user(min_size, &uattr->func_info_rec_size))
8999 ret = -EFAULT;
9000 }
c454a46b 9001 goto err_free;
838e9690
YS
9002 }
9003
ba64e7d8 9004 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 9005 ret = -EFAULT;
c454a46b 9006 goto err_free;
838e9690
YS
9007 }
9008
d30d42e0 9009 /* check insn_off */
09b28d76 9010 ret = -EINVAL;
838e9690 9011 if (i == 0) {
d30d42e0 9012 if (krecord[i].insn_off) {
838e9690 9013 verbose(env,
d30d42e0
MKL
9014 "nonzero insn_off %u for the first func info record",
9015 krecord[i].insn_off);
c454a46b 9016 goto err_free;
838e9690 9017 }
d30d42e0 9018 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
9019 verbose(env,
9020 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 9021 krecord[i].insn_off, prev_offset);
c454a46b 9022 goto err_free;
838e9690
YS
9023 }
9024
d30d42e0 9025 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 9026 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 9027 goto err_free;
838e9690
YS
9028 }
9029
9030 /* check type_id */
ba64e7d8 9031 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 9032 if (!type || !btf_type_is_func(type)) {
838e9690 9033 verbose(env, "invalid type id %d in func info",
ba64e7d8 9034 krecord[i].type_id);
c454a46b 9035 goto err_free;
838e9690 9036 }
51c39bb1 9037 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
9038
9039 func_proto = btf_type_by_id(btf, type->type);
9040 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9041 /* btf_func_check() already verified it during BTF load */
9042 goto err_free;
9043 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9044 scalar_return =
9045 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9046 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9047 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9048 goto err_free;
9049 }
9050 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9051 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9052 goto err_free;
9053 }
9054
d30d42e0 9055 prev_offset = krecord[i].insn_off;
838e9690
YS
9056 urecord += urec_size;
9057 }
9058
ba64e7d8
YS
9059 prog->aux->func_info = krecord;
9060 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 9061 prog->aux->func_info_aux = info_aux;
838e9690
YS
9062 return 0;
9063
c454a46b 9064err_free:
ba64e7d8 9065 kvfree(krecord);
8c1b6e69 9066 kfree(info_aux);
838e9690
YS
9067 return ret;
9068}
9069
ba64e7d8
YS
9070static void adjust_btf_func(struct bpf_verifier_env *env)
9071{
8c1b6e69 9072 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
9073 int i;
9074
8c1b6e69 9075 if (!aux->func_info)
ba64e7d8
YS
9076 return;
9077
9078 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 9079 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
9080}
9081
c454a46b
MKL
9082#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9083 sizeof(((struct bpf_line_info *)(0))->line_col))
9084#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9085
9086static int check_btf_line(struct bpf_verifier_env *env,
9087 const union bpf_attr *attr,
9088 union bpf_attr __user *uattr)
9089{
9090 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9091 struct bpf_subprog_info *sub;
9092 struct bpf_line_info *linfo;
9093 struct bpf_prog *prog;
9094 const struct btf *btf;
9095 void __user *ulinfo;
9096 int err;
9097
9098 nr_linfo = attr->line_info_cnt;
9099 if (!nr_linfo)
9100 return 0;
9101
9102 rec_size = attr->line_info_rec_size;
9103 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9104 rec_size > MAX_LINEINFO_REC_SIZE ||
9105 rec_size & (sizeof(u32) - 1))
9106 return -EINVAL;
9107
9108 /* Need to zero it in case the userspace may
9109 * pass in a smaller bpf_line_info object.
9110 */
9111 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9112 GFP_KERNEL | __GFP_NOWARN);
9113 if (!linfo)
9114 return -ENOMEM;
9115
9116 prog = env->prog;
9117 btf = prog->aux->btf;
9118
9119 s = 0;
9120 sub = env->subprog_info;
9121 ulinfo = u64_to_user_ptr(attr->line_info);
9122 expected_size = sizeof(struct bpf_line_info);
9123 ncopy = min_t(u32, expected_size, rec_size);
9124 for (i = 0; i < nr_linfo; i++) {
9125 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9126 if (err) {
9127 if (err == -E2BIG) {
9128 verbose(env, "nonzero tailing record in line_info");
9129 if (put_user(expected_size,
9130 &uattr->line_info_rec_size))
9131 err = -EFAULT;
9132 }
9133 goto err_free;
9134 }
9135
9136 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9137 err = -EFAULT;
9138 goto err_free;
9139 }
9140
9141 /*
9142 * Check insn_off to ensure
9143 * 1) strictly increasing AND
9144 * 2) bounded by prog->len
9145 *
9146 * The linfo[0].insn_off == 0 check logically falls into
9147 * the later "missing bpf_line_info for func..." case
9148 * because the first linfo[0].insn_off must be the
9149 * first sub also and the first sub must have
9150 * subprog_info[0].start == 0.
9151 */
9152 if ((i && linfo[i].insn_off <= prev_offset) ||
9153 linfo[i].insn_off >= prog->len) {
9154 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9155 i, linfo[i].insn_off, prev_offset,
9156 prog->len);
9157 err = -EINVAL;
9158 goto err_free;
9159 }
9160
fdbaa0be
MKL
9161 if (!prog->insnsi[linfo[i].insn_off].code) {
9162 verbose(env,
9163 "Invalid insn code at line_info[%u].insn_off\n",
9164 i);
9165 err = -EINVAL;
9166 goto err_free;
9167 }
9168
23127b33
MKL
9169 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9170 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
9171 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9172 err = -EINVAL;
9173 goto err_free;
9174 }
9175
9176 if (s != env->subprog_cnt) {
9177 if (linfo[i].insn_off == sub[s].start) {
9178 sub[s].linfo_idx = i;
9179 s++;
9180 } else if (sub[s].start < linfo[i].insn_off) {
9181 verbose(env, "missing bpf_line_info for func#%u\n", s);
9182 err = -EINVAL;
9183 goto err_free;
9184 }
9185 }
9186
9187 prev_offset = linfo[i].insn_off;
9188 ulinfo += rec_size;
9189 }
9190
9191 if (s != env->subprog_cnt) {
9192 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9193 env->subprog_cnt - s, s);
9194 err = -EINVAL;
9195 goto err_free;
9196 }
9197
9198 prog->aux->linfo = linfo;
9199 prog->aux->nr_linfo = nr_linfo;
9200
9201 return 0;
9202
9203err_free:
9204 kvfree(linfo);
9205 return err;
9206}
9207
9208static int check_btf_info(struct bpf_verifier_env *env,
9209 const union bpf_attr *attr,
9210 union bpf_attr __user *uattr)
9211{
9212 struct btf *btf;
9213 int err;
9214
09b28d76
AS
9215 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9216 if (check_abnormal_return(env))
9217 return -EINVAL;
c454a46b 9218 return 0;
09b28d76 9219 }
c454a46b
MKL
9220
9221 btf = btf_get_by_fd(attr->prog_btf_fd);
9222 if (IS_ERR(btf))
9223 return PTR_ERR(btf);
9224 env->prog->aux->btf = btf;
9225
9226 err = check_btf_func(env, attr, uattr);
9227 if (err)
9228 return err;
9229
9230 err = check_btf_line(env, attr, uattr);
9231 if (err)
9232 return err;
9233
9234 return 0;
ba64e7d8
YS
9235}
9236
f1174f77
EC
9237/* check %cur's range satisfies %old's */
9238static bool range_within(struct bpf_reg_state *old,
9239 struct bpf_reg_state *cur)
9240{
b03c9f9f
EC
9241 return old->umin_value <= cur->umin_value &&
9242 old->umax_value >= cur->umax_value &&
9243 old->smin_value <= cur->smin_value &&
fd675184
DB
9244 old->smax_value >= cur->smax_value &&
9245 old->u32_min_value <= cur->u32_min_value &&
9246 old->u32_max_value >= cur->u32_max_value &&
9247 old->s32_min_value <= cur->s32_min_value &&
9248 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9249}
9250
9251/* Maximum number of register states that can exist at once */
9252#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9253struct idpair {
9254 u32 old;
9255 u32 cur;
9256};
9257
9258/* If in the old state two registers had the same id, then they need to have
9259 * the same id in the new state as well. But that id could be different from
9260 * the old state, so we need to track the mapping from old to new ids.
9261 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9262 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9263 * regs with a different old id could still have new id 9, we don't care about
9264 * that.
9265 * So we look through our idmap to see if this old id has been seen before. If
9266 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9267 */
f1174f77 9268static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 9269{
f1174f77 9270 unsigned int i;
969bf05e 9271
f1174f77
EC
9272 for (i = 0; i < ID_MAP_SIZE; i++) {
9273 if (!idmap[i].old) {
9274 /* Reached an empty slot; haven't seen this id before */
9275 idmap[i].old = old_id;
9276 idmap[i].cur = cur_id;
9277 return true;
9278 }
9279 if (idmap[i].old == old_id)
9280 return idmap[i].cur == cur_id;
9281 }
9282 /* We ran out of idmap slots, which should be impossible */
9283 WARN_ON_ONCE(1);
9284 return false;
9285}
9286
9242b5f5
AS
9287static void clean_func_state(struct bpf_verifier_env *env,
9288 struct bpf_func_state *st)
9289{
9290 enum bpf_reg_liveness live;
9291 int i, j;
9292
9293 for (i = 0; i < BPF_REG_FP; i++) {
9294 live = st->regs[i].live;
9295 /* liveness must not touch this register anymore */
9296 st->regs[i].live |= REG_LIVE_DONE;
9297 if (!(live & REG_LIVE_READ))
9298 /* since the register is unused, clear its state
9299 * to make further comparison simpler
9300 */
f54c7898 9301 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9302 }
9303
9304 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9305 live = st->stack[i].spilled_ptr.live;
9306 /* liveness must not touch this stack slot anymore */
9307 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9308 if (!(live & REG_LIVE_READ)) {
f54c7898 9309 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9310 for (j = 0; j < BPF_REG_SIZE; j++)
9311 st->stack[i].slot_type[j] = STACK_INVALID;
9312 }
9313 }
9314}
9315
9316static void clean_verifier_state(struct bpf_verifier_env *env,
9317 struct bpf_verifier_state *st)
9318{
9319 int i;
9320
9321 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9322 /* all regs in this state in all frames were already marked */
9323 return;
9324
9325 for (i = 0; i <= st->curframe; i++)
9326 clean_func_state(env, st->frame[i]);
9327}
9328
9329/* the parentage chains form a tree.
9330 * the verifier states are added to state lists at given insn and
9331 * pushed into state stack for future exploration.
9332 * when the verifier reaches bpf_exit insn some of the verifer states
9333 * stored in the state lists have their final liveness state already,
9334 * but a lot of states will get revised from liveness point of view when
9335 * the verifier explores other branches.
9336 * Example:
9337 * 1: r0 = 1
9338 * 2: if r1 == 100 goto pc+1
9339 * 3: r0 = 2
9340 * 4: exit
9341 * when the verifier reaches exit insn the register r0 in the state list of
9342 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9343 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9344 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9345 *
9346 * Since the verifier pushes the branch states as it sees them while exploring
9347 * the program the condition of walking the branch instruction for the second
9348 * time means that all states below this branch were already explored and
9349 * their final liveness markes are already propagated.
9350 * Hence when the verifier completes the search of state list in is_state_visited()
9351 * we can call this clean_live_states() function to mark all liveness states
9352 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9353 * will not be used.
9354 * This function also clears the registers and stack for states that !READ
9355 * to simplify state merging.
9356 *
9357 * Important note here that walking the same branch instruction in the callee
9358 * doesn't meant that the states are DONE. The verifier has to compare
9359 * the callsites
9360 */
9361static void clean_live_states(struct bpf_verifier_env *env, int insn,
9362 struct bpf_verifier_state *cur)
9363{
9364 struct bpf_verifier_state_list *sl;
9365 int i;
9366
5d839021 9367 sl = *explored_state(env, insn);
a8f500af 9368 while (sl) {
2589726d
AS
9369 if (sl->state.branches)
9370 goto next;
dc2a4ebc
AS
9371 if (sl->state.insn_idx != insn ||
9372 sl->state.curframe != cur->curframe)
9242b5f5
AS
9373 goto next;
9374 for (i = 0; i <= cur->curframe; i++)
9375 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9376 goto next;
9377 clean_verifier_state(env, &sl->state);
9378next:
9379 sl = sl->next;
9380 }
9381}
9382
f1174f77 9383/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
9384static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9385 struct idpair *idmap)
f1174f77 9386{
f4d7e40a
AS
9387 bool equal;
9388
dc503a8a
EC
9389 if (!(rold->live & REG_LIVE_READ))
9390 /* explored state didn't use this */
9391 return true;
9392
679c782d 9393 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9394
9395 if (rold->type == PTR_TO_STACK)
9396 /* two stack pointers are equal only if they're pointing to
9397 * the same stack frame, since fp-8 in foo != fp-8 in bar
9398 */
9399 return equal && rold->frameno == rcur->frameno;
9400
9401 if (equal)
969bf05e
AS
9402 return true;
9403
f1174f77
EC
9404 if (rold->type == NOT_INIT)
9405 /* explored state can't have used this */
969bf05e 9406 return true;
f1174f77
EC
9407 if (rcur->type == NOT_INIT)
9408 return false;
9409 switch (rold->type) {
9410 case SCALAR_VALUE:
9411 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9412 if (!rold->precise && !rcur->precise)
9413 return true;
f1174f77
EC
9414 /* new val must satisfy old val knowledge */
9415 return range_within(rold, rcur) &&
9416 tnum_in(rold->var_off, rcur->var_off);
9417 } else {
179d1c56
JH
9418 /* We're trying to use a pointer in place of a scalar.
9419 * Even if the scalar was unbounded, this could lead to
9420 * pointer leaks because scalars are allowed to leak
9421 * while pointers are not. We could make this safe in
9422 * special cases if root is calling us, but it's
9423 * probably not worth the hassle.
f1174f77 9424 */
179d1c56 9425 return false;
f1174f77 9426 }
69c087ba 9427 case PTR_TO_MAP_KEY:
f1174f77 9428 case PTR_TO_MAP_VALUE:
1b688a19
EC
9429 /* If the new min/max/var_off satisfy the old ones and
9430 * everything else matches, we are OK.
d83525ca
AS
9431 * 'id' is not compared, since it's only used for maps with
9432 * bpf_spin_lock inside map element and in such cases if
9433 * the rest of the prog is valid for one map element then
9434 * it's valid for all map elements regardless of the key
9435 * used in bpf_map_lookup()
1b688a19
EC
9436 */
9437 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9438 range_within(rold, rcur) &&
9439 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
9440 case PTR_TO_MAP_VALUE_OR_NULL:
9441 /* a PTR_TO_MAP_VALUE could be safe to use as a
9442 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9443 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9444 * checked, doing so could have affected others with the same
9445 * id, and we can't check for that because we lost the id when
9446 * we converted to a PTR_TO_MAP_VALUE.
9447 */
9448 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9449 return false;
9450 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9451 return false;
9452 /* Check our ids match any regs they're supposed to */
9453 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 9454 case PTR_TO_PACKET_META:
f1174f77 9455 case PTR_TO_PACKET:
de8f3a83 9456 if (rcur->type != rold->type)
f1174f77
EC
9457 return false;
9458 /* We must have at least as much range as the old ptr
9459 * did, so that any accesses which were safe before are
9460 * still safe. This is true even if old range < old off,
9461 * since someone could have accessed through (ptr - k), or
9462 * even done ptr -= k in a register, to get a safe access.
9463 */
9464 if (rold->range > rcur->range)
9465 return false;
9466 /* If the offsets don't match, we can't trust our alignment;
9467 * nor can we be sure that we won't fall out of range.
9468 */
9469 if (rold->off != rcur->off)
9470 return false;
9471 /* id relations must be preserved */
9472 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9473 return false;
9474 /* new val must satisfy old val knowledge */
9475 return range_within(rold, rcur) &&
9476 tnum_in(rold->var_off, rcur->var_off);
9477 case PTR_TO_CTX:
9478 case CONST_PTR_TO_MAP:
f1174f77 9479 case PTR_TO_PACKET_END:
d58e468b 9480 case PTR_TO_FLOW_KEYS:
c64b7983
JS
9481 case PTR_TO_SOCKET:
9482 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9483 case PTR_TO_SOCK_COMMON:
9484 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9485 case PTR_TO_TCP_SOCK:
9486 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9487 case PTR_TO_XDP_SOCK:
f1174f77
EC
9488 /* Only valid matches are exact, which memcmp() above
9489 * would have accepted
9490 */
9491 default:
9492 /* Don't know what's going on, just say it's not safe */
9493 return false;
9494 }
969bf05e 9495
f1174f77
EC
9496 /* Shouldn't get here; if we do, say it's not safe */
9497 WARN_ON_ONCE(1);
969bf05e
AS
9498 return false;
9499}
9500
f4d7e40a
AS
9501static bool stacksafe(struct bpf_func_state *old,
9502 struct bpf_func_state *cur,
638f5b90
AS
9503 struct idpair *idmap)
9504{
9505 int i, spi;
9506
638f5b90
AS
9507 /* walk slots of the explored stack and ignore any additional
9508 * slots in the current stack, since explored(safe) state
9509 * didn't use them
9510 */
9511 for (i = 0; i < old->allocated_stack; i++) {
9512 spi = i / BPF_REG_SIZE;
9513
b233920c
AS
9514 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9515 i += BPF_REG_SIZE - 1;
cc2b14d5 9516 /* explored state didn't use this */
fd05e57b 9517 continue;
b233920c 9518 }
cc2b14d5 9519
638f5b90
AS
9520 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9521 continue;
19e2dbb7
AS
9522
9523 /* explored stack has more populated slots than current stack
9524 * and these slots were used
9525 */
9526 if (i >= cur->allocated_stack)
9527 return false;
9528
cc2b14d5
AS
9529 /* if old state was safe with misc data in the stack
9530 * it will be safe with zero-initialized stack.
9531 * The opposite is not true
9532 */
9533 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9534 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9535 continue;
638f5b90
AS
9536 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9537 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9538 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 9539 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
9540 * this verifier states are not equivalent,
9541 * return false to continue verification of this path
9542 */
9543 return false;
9544 if (i % BPF_REG_SIZE)
9545 continue;
9546 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9547 continue;
9548 if (!regsafe(&old->stack[spi].spilled_ptr,
9549 &cur->stack[spi].spilled_ptr,
9550 idmap))
9551 /* when explored and current stack slot are both storing
9552 * spilled registers, check that stored pointers types
9553 * are the same as well.
9554 * Ex: explored safe path could have stored
9555 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9556 * but current path has stored:
9557 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9558 * such verifier states are not equivalent.
9559 * return false to continue verification of this path
9560 */
9561 return false;
9562 }
9563 return true;
9564}
9565
fd978bf7
JS
9566static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9567{
9568 if (old->acquired_refs != cur->acquired_refs)
9569 return false;
9570 return !memcmp(old->refs, cur->refs,
9571 sizeof(*old->refs) * old->acquired_refs);
9572}
9573
f1bca824
AS
9574/* compare two verifier states
9575 *
9576 * all states stored in state_list are known to be valid, since
9577 * verifier reached 'bpf_exit' instruction through them
9578 *
9579 * this function is called when verifier exploring different branches of
9580 * execution popped from the state stack. If it sees an old state that has
9581 * more strict register state and more strict stack state then this execution
9582 * branch doesn't need to be explored further, since verifier already
9583 * concluded that more strict state leads to valid finish.
9584 *
9585 * Therefore two states are equivalent if register state is more conservative
9586 * and explored stack state is more conservative than the current one.
9587 * Example:
9588 * explored current
9589 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9590 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9591 *
9592 * In other words if current stack state (one being explored) has more
9593 * valid slots than old one that already passed validation, it means
9594 * the verifier can stop exploring and conclude that current state is valid too
9595 *
9596 * Similarly with registers. If explored state has register type as invalid
9597 * whereas register type in current state is meaningful, it means that
9598 * the current state will reach 'bpf_exit' instruction safely
9599 */
f4d7e40a
AS
9600static bool func_states_equal(struct bpf_func_state *old,
9601 struct bpf_func_state *cur)
f1bca824 9602{
f1174f77
EC
9603 struct idpair *idmap;
9604 bool ret = false;
f1bca824
AS
9605 int i;
9606
f1174f77
EC
9607 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9608 /* If we failed to allocate the idmap, just say it's not safe */
9609 if (!idmap)
1a0dc1ac 9610 return false;
f1174f77
EC
9611
9612 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 9613 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 9614 goto out_free;
f1bca824
AS
9615 }
9616
638f5b90
AS
9617 if (!stacksafe(old, cur, idmap))
9618 goto out_free;
fd978bf7
JS
9619
9620 if (!refsafe(old, cur))
9621 goto out_free;
f1174f77
EC
9622 ret = true;
9623out_free:
9624 kfree(idmap);
9625 return ret;
f1bca824
AS
9626}
9627
f4d7e40a
AS
9628static bool states_equal(struct bpf_verifier_env *env,
9629 struct bpf_verifier_state *old,
9630 struct bpf_verifier_state *cur)
9631{
9632 int i;
9633
9634 if (old->curframe != cur->curframe)
9635 return false;
9636
979d63d5
DB
9637 /* Verification state from speculative execution simulation
9638 * must never prune a non-speculative execution one.
9639 */
9640 if (old->speculative && !cur->speculative)
9641 return false;
9642
d83525ca
AS
9643 if (old->active_spin_lock != cur->active_spin_lock)
9644 return false;
9645
f4d7e40a
AS
9646 /* for states to be equal callsites have to be the same
9647 * and all frame states need to be equivalent
9648 */
9649 for (i = 0; i <= old->curframe; i++) {
9650 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9651 return false;
9652 if (!func_states_equal(old->frame[i], cur->frame[i]))
9653 return false;
9654 }
9655 return true;
9656}
9657
5327ed3d
JW
9658/* Return 0 if no propagation happened. Return negative error code if error
9659 * happened. Otherwise, return the propagated bit.
9660 */
55e7f3b5
JW
9661static int propagate_liveness_reg(struct bpf_verifier_env *env,
9662 struct bpf_reg_state *reg,
9663 struct bpf_reg_state *parent_reg)
9664{
5327ed3d
JW
9665 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9666 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
9667 int err;
9668
5327ed3d
JW
9669 /* When comes here, read flags of PARENT_REG or REG could be any of
9670 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9671 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9672 */
9673 if (parent_flag == REG_LIVE_READ64 ||
9674 /* Or if there is no read flag from REG. */
9675 !flag ||
9676 /* Or if the read flag from REG is the same as PARENT_REG. */
9677 parent_flag == flag)
55e7f3b5
JW
9678 return 0;
9679
5327ed3d 9680 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
9681 if (err)
9682 return err;
9683
5327ed3d 9684 return flag;
55e7f3b5
JW
9685}
9686
8e9cd9ce 9687/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
9688 * straight-line code between a state and its parent. When we arrive at an
9689 * equivalent state (jump target or such) we didn't arrive by the straight-line
9690 * code, so read marks in the state must propagate to the parent regardless
9691 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 9692 * in mark_reg_read() is for.
8e9cd9ce 9693 */
f4d7e40a
AS
9694static int propagate_liveness(struct bpf_verifier_env *env,
9695 const struct bpf_verifier_state *vstate,
9696 struct bpf_verifier_state *vparent)
dc503a8a 9697{
3f8cafa4 9698 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 9699 struct bpf_func_state *state, *parent;
3f8cafa4 9700 int i, frame, err = 0;
dc503a8a 9701
f4d7e40a
AS
9702 if (vparent->curframe != vstate->curframe) {
9703 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9704 vparent->curframe, vstate->curframe);
9705 return -EFAULT;
9706 }
dc503a8a
EC
9707 /* Propagate read liveness of registers... */
9708 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 9709 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
9710 parent = vparent->frame[frame];
9711 state = vstate->frame[frame];
9712 parent_reg = parent->regs;
9713 state_reg = state->regs;
83d16312
JK
9714 /* We don't need to worry about FP liveness, it's read-only */
9715 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
9716 err = propagate_liveness_reg(env, &state_reg[i],
9717 &parent_reg[i]);
5327ed3d 9718 if (err < 0)
3f8cafa4 9719 return err;
5327ed3d
JW
9720 if (err == REG_LIVE_READ64)
9721 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 9722 }
f4d7e40a 9723
1b04aee7 9724 /* Propagate stack slots. */
f4d7e40a
AS
9725 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9726 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
9727 parent_reg = &parent->stack[i].spilled_ptr;
9728 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
9729 err = propagate_liveness_reg(env, state_reg,
9730 parent_reg);
5327ed3d 9731 if (err < 0)
3f8cafa4 9732 return err;
dc503a8a
EC
9733 }
9734 }
5327ed3d 9735 return 0;
dc503a8a
EC
9736}
9737
a3ce685d
AS
9738/* find precise scalars in the previous equivalent state and
9739 * propagate them into the current state
9740 */
9741static int propagate_precision(struct bpf_verifier_env *env,
9742 const struct bpf_verifier_state *old)
9743{
9744 struct bpf_reg_state *state_reg;
9745 struct bpf_func_state *state;
9746 int i, err = 0;
9747
9748 state = old->frame[old->curframe];
9749 state_reg = state->regs;
9750 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9751 if (state_reg->type != SCALAR_VALUE ||
9752 !state_reg->precise)
9753 continue;
9754 if (env->log.level & BPF_LOG_LEVEL2)
9755 verbose(env, "propagating r%d\n", i);
9756 err = mark_chain_precision(env, i);
9757 if (err < 0)
9758 return err;
9759 }
9760
9761 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9762 if (state->stack[i].slot_type[0] != STACK_SPILL)
9763 continue;
9764 state_reg = &state->stack[i].spilled_ptr;
9765 if (state_reg->type != SCALAR_VALUE ||
9766 !state_reg->precise)
9767 continue;
9768 if (env->log.level & BPF_LOG_LEVEL2)
9769 verbose(env, "propagating fp%d\n",
9770 (-i - 1) * BPF_REG_SIZE);
9771 err = mark_chain_precision_stack(env, i);
9772 if (err < 0)
9773 return err;
9774 }
9775 return 0;
9776}
9777
2589726d
AS
9778static bool states_maybe_looping(struct bpf_verifier_state *old,
9779 struct bpf_verifier_state *cur)
9780{
9781 struct bpf_func_state *fold, *fcur;
9782 int i, fr = cur->curframe;
9783
9784 if (old->curframe != fr)
9785 return false;
9786
9787 fold = old->frame[fr];
9788 fcur = cur->frame[fr];
9789 for (i = 0; i < MAX_BPF_REG; i++)
9790 if (memcmp(&fold->regs[i], &fcur->regs[i],
9791 offsetof(struct bpf_reg_state, parent)))
9792 return false;
9793 return true;
9794}
9795
9796
58e2af8b 9797static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 9798{
58e2af8b 9799 struct bpf_verifier_state_list *new_sl;
9f4686c4 9800 struct bpf_verifier_state_list *sl, **pprev;
679c782d 9801 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 9802 int i, j, err, states_cnt = 0;
10d274e8 9803 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 9804
b5dc0163 9805 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 9806 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
9807 /* this 'insn_idx' instruction wasn't marked, so we will not
9808 * be doing state search here
9809 */
9810 return 0;
9811
2589726d
AS
9812 /* bpf progs typically have pruning point every 4 instructions
9813 * http://vger.kernel.org/bpfconf2019.html#session-1
9814 * Do not add new state for future pruning if the verifier hasn't seen
9815 * at least 2 jumps and at least 8 instructions.
9816 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9817 * In tests that amounts to up to 50% reduction into total verifier
9818 * memory consumption and 20% verifier time speedup.
9819 */
9820 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9821 env->insn_processed - env->prev_insn_processed >= 8)
9822 add_new_state = true;
9823
a8f500af
AS
9824 pprev = explored_state(env, insn_idx);
9825 sl = *pprev;
9826
9242b5f5
AS
9827 clean_live_states(env, insn_idx, cur);
9828
a8f500af 9829 while (sl) {
dc2a4ebc
AS
9830 states_cnt++;
9831 if (sl->state.insn_idx != insn_idx)
9832 goto next;
2589726d
AS
9833 if (sl->state.branches) {
9834 if (states_maybe_looping(&sl->state, cur) &&
9835 states_equal(env, &sl->state, cur)) {
9836 verbose_linfo(env, insn_idx, "; ");
9837 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9838 return -EINVAL;
9839 }
9840 /* if the verifier is processing a loop, avoid adding new state
9841 * too often, since different loop iterations have distinct
9842 * states and may not help future pruning.
9843 * This threshold shouldn't be too low to make sure that
9844 * a loop with large bound will be rejected quickly.
9845 * The most abusive loop will be:
9846 * r1 += 1
9847 * if r1 < 1000000 goto pc-2
9848 * 1M insn_procssed limit / 100 == 10k peak states.
9849 * This threshold shouldn't be too high either, since states
9850 * at the end of the loop are likely to be useful in pruning.
9851 */
9852 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9853 env->insn_processed - env->prev_insn_processed < 100)
9854 add_new_state = false;
9855 goto miss;
9856 }
638f5b90 9857 if (states_equal(env, &sl->state, cur)) {
9f4686c4 9858 sl->hit_cnt++;
f1bca824 9859 /* reached equivalent register/stack state,
dc503a8a
EC
9860 * prune the search.
9861 * Registers read by the continuation are read by us.
8e9cd9ce
EC
9862 * If we have any write marks in env->cur_state, they
9863 * will prevent corresponding reads in the continuation
9864 * from reaching our parent (an explored_state). Our
9865 * own state will get the read marks recorded, but
9866 * they'll be immediately forgotten as we're pruning
9867 * this state and will pop a new one.
f1bca824 9868 */
f4d7e40a 9869 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
9870
9871 /* if previous state reached the exit with precision and
9872 * current state is equivalent to it (except precsion marks)
9873 * the precision needs to be propagated back in
9874 * the current state.
9875 */
9876 err = err ? : push_jmp_history(env, cur);
9877 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
9878 if (err)
9879 return err;
f1bca824 9880 return 1;
dc503a8a 9881 }
2589726d
AS
9882miss:
9883 /* when new state is not going to be added do not increase miss count.
9884 * Otherwise several loop iterations will remove the state
9885 * recorded earlier. The goal of these heuristics is to have
9886 * states from some iterations of the loop (some in the beginning
9887 * and some at the end) to help pruning.
9888 */
9889 if (add_new_state)
9890 sl->miss_cnt++;
9f4686c4
AS
9891 /* heuristic to determine whether this state is beneficial
9892 * to keep checking from state equivalence point of view.
9893 * Higher numbers increase max_states_per_insn and verification time,
9894 * but do not meaningfully decrease insn_processed.
9895 */
9896 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9897 /* the state is unlikely to be useful. Remove it to
9898 * speed up verification
9899 */
9900 *pprev = sl->next;
9901 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
9902 u32 br = sl->state.branches;
9903
9904 WARN_ONCE(br,
9905 "BUG live_done but branches_to_explore %d\n",
9906 br);
9f4686c4
AS
9907 free_verifier_state(&sl->state, false);
9908 kfree(sl);
9909 env->peak_states--;
9910 } else {
9911 /* cannot free this state, since parentage chain may
9912 * walk it later. Add it for free_list instead to
9913 * be freed at the end of verification
9914 */
9915 sl->next = env->free_list;
9916 env->free_list = sl;
9917 }
9918 sl = *pprev;
9919 continue;
9920 }
dc2a4ebc 9921next:
9f4686c4
AS
9922 pprev = &sl->next;
9923 sl = *pprev;
f1bca824
AS
9924 }
9925
06ee7115
AS
9926 if (env->max_states_per_insn < states_cnt)
9927 env->max_states_per_insn = states_cnt;
9928
2c78ee89 9929 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 9930 return push_jmp_history(env, cur);
ceefbc96 9931
2589726d 9932 if (!add_new_state)
b5dc0163 9933 return push_jmp_history(env, cur);
ceefbc96 9934
2589726d
AS
9935 /* There were no equivalent states, remember the current one.
9936 * Technically the current state is not proven to be safe yet,
f4d7e40a 9937 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 9938 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 9939 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
9940 * again on the way to bpf_exit.
9941 * When looping the sl->state.branches will be > 0 and this state
9942 * will not be considered for equivalence until branches == 0.
f1bca824 9943 */
638f5b90 9944 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
9945 if (!new_sl)
9946 return -ENOMEM;
06ee7115
AS
9947 env->total_states++;
9948 env->peak_states++;
2589726d
AS
9949 env->prev_jmps_processed = env->jmps_processed;
9950 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
9951
9952 /* add new state to the head of linked list */
679c782d
EC
9953 new = &new_sl->state;
9954 err = copy_verifier_state(new, cur);
1969db47 9955 if (err) {
679c782d 9956 free_verifier_state(new, false);
1969db47
AS
9957 kfree(new_sl);
9958 return err;
9959 }
dc2a4ebc 9960 new->insn_idx = insn_idx;
2589726d
AS
9961 WARN_ONCE(new->branches != 1,
9962 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 9963
2589726d 9964 cur->parent = new;
b5dc0163
AS
9965 cur->first_insn_idx = insn_idx;
9966 clear_jmp_history(cur);
5d839021
AS
9967 new_sl->next = *explored_state(env, insn_idx);
9968 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
9969 /* connect new state to parentage chain. Current frame needs all
9970 * registers connected. Only r6 - r9 of the callers are alive (pushed
9971 * to the stack implicitly by JITs) so in callers' frames connect just
9972 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9973 * the state of the call instruction (with WRITTEN set), and r0 comes
9974 * from callee with its full parentage chain, anyway.
9975 */
8e9cd9ce
EC
9976 /* clear write marks in current state: the writes we did are not writes
9977 * our child did, so they don't screen off its reads from us.
9978 * (There are no read marks in current state, because reads always mark
9979 * their parent and current state never has children yet. Only
9980 * explored_states can get read marks.)
9981 */
eea1c227
AS
9982 for (j = 0; j <= cur->curframe; j++) {
9983 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9984 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9985 for (i = 0; i < BPF_REG_FP; i++)
9986 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9987 }
f4d7e40a
AS
9988
9989 /* all stack frames are accessible from callee, clear them all */
9990 for (j = 0; j <= cur->curframe; j++) {
9991 struct bpf_func_state *frame = cur->frame[j];
679c782d 9992 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 9993
679c782d 9994 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 9995 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
9996 frame->stack[i].spilled_ptr.parent =
9997 &newframe->stack[i].spilled_ptr;
9998 }
f4d7e40a 9999 }
f1bca824
AS
10000 return 0;
10001}
10002
c64b7983
JS
10003/* Return true if it's OK to have the same insn return a different type. */
10004static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10005{
10006 switch (type) {
10007 case PTR_TO_CTX:
10008 case PTR_TO_SOCKET:
10009 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10010 case PTR_TO_SOCK_COMMON:
10011 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10012 case PTR_TO_TCP_SOCK:
10013 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10014 case PTR_TO_XDP_SOCK:
2a02759e 10015 case PTR_TO_BTF_ID:
b121b341 10016 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
10017 return false;
10018 default:
10019 return true;
10020 }
10021}
10022
10023/* If an instruction was previously used with particular pointer types, then we
10024 * need to be careful to avoid cases such as the below, where it may be ok
10025 * for one branch accessing the pointer, but not ok for the other branch:
10026 *
10027 * R1 = sock_ptr
10028 * goto X;
10029 * ...
10030 * R1 = some_other_valid_ptr;
10031 * goto X;
10032 * ...
10033 * R2 = *(u32 *)(R1 + 0);
10034 */
10035static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10036{
10037 return src != prev && (!reg_type_mismatch_ok(src) ||
10038 !reg_type_mismatch_ok(prev));
10039}
10040
58e2af8b 10041static int do_check(struct bpf_verifier_env *env)
17a52670 10042{
6f8a57cc 10043 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 10044 struct bpf_verifier_state *state = env->cur_state;
17a52670 10045 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 10046 struct bpf_reg_state *regs;
06ee7115 10047 int insn_cnt = env->prog->len;
17a52670 10048 bool do_print_state = false;
b5dc0163 10049 int prev_insn_idx = -1;
17a52670 10050
17a52670
AS
10051 for (;;) {
10052 struct bpf_insn *insn;
10053 u8 class;
10054 int err;
10055
b5dc0163 10056 env->prev_insn_idx = prev_insn_idx;
c08435ec 10057 if (env->insn_idx >= insn_cnt) {
61bd5218 10058 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 10059 env->insn_idx, insn_cnt);
17a52670
AS
10060 return -EFAULT;
10061 }
10062
c08435ec 10063 insn = &insns[env->insn_idx];
17a52670
AS
10064 class = BPF_CLASS(insn->code);
10065
06ee7115 10066 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
10067 verbose(env,
10068 "BPF program is too large. Processed %d insn\n",
06ee7115 10069 env->insn_processed);
17a52670
AS
10070 return -E2BIG;
10071 }
10072
c08435ec 10073 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
10074 if (err < 0)
10075 return err;
10076 if (err == 1) {
10077 /* found equivalent state, can prune the search */
06ee7115 10078 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 10079 if (do_print_state)
979d63d5
DB
10080 verbose(env, "\nfrom %d to %d%s: safe\n",
10081 env->prev_insn_idx, env->insn_idx,
10082 env->cur_state->speculative ?
10083 " (speculative execution)" : "");
f1bca824 10084 else
c08435ec 10085 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
10086 }
10087 goto process_bpf_exit;
10088 }
10089
c3494801
AS
10090 if (signal_pending(current))
10091 return -EAGAIN;
10092
3c2ce60b
DB
10093 if (need_resched())
10094 cond_resched();
10095
06ee7115
AS
10096 if (env->log.level & BPF_LOG_LEVEL2 ||
10097 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10098 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 10099 verbose(env, "%d:", env->insn_idx);
c5fc9692 10100 else
979d63d5
DB
10101 verbose(env, "\nfrom %d to %d%s:",
10102 env->prev_insn_idx, env->insn_idx,
10103 env->cur_state->speculative ?
10104 " (speculative execution)" : "");
f4d7e40a 10105 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
10106 do_print_state = false;
10107 }
10108
06ee7115 10109 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
10110 const struct bpf_insn_cbs cbs = {
10111 .cb_print = verbose,
abe08840 10112 .private_data = env,
7105e828
DB
10113 };
10114
c08435ec
DB
10115 verbose_linfo(env, env->insn_idx, "; ");
10116 verbose(env, "%d: ", env->insn_idx);
abe08840 10117 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
10118 }
10119
cae1927c 10120 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
10121 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10122 env->prev_insn_idx);
cae1927c
JK
10123 if (err)
10124 return err;
10125 }
13a27dfc 10126
638f5b90 10127 regs = cur_regs(env);
51c39bb1 10128 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 10129 prev_insn_idx = env->insn_idx;
fd978bf7 10130
17a52670 10131 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 10132 err = check_alu_op(env, insn);
17a52670
AS
10133 if (err)
10134 return err;
10135
10136 } else if (class == BPF_LDX) {
3df126f3 10137 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
10138
10139 /* check for reserved fields is already done */
10140
17a52670 10141 /* check src operand */
dc503a8a 10142 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10143 if (err)
10144 return err;
10145
dc503a8a 10146 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10147 if (err)
10148 return err;
10149
725f9dcd
AS
10150 src_reg_type = regs[insn->src_reg].type;
10151
17a52670
AS
10152 /* check that memory (src_reg + off) is readable,
10153 * the state of dst_reg will be updated by this func
10154 */
c08435ec
DB
10155 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10156 insn->off, BPF_SIZE(insn->code),
10157 BPF_READ, insn->dst_reg, false);
17a52670
AS
10158 if (err)
10159 return err;
10160
c08435ec 10161 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10162
10163 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
10164 /* saw a valid insn
10165 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 10166 * save type to validate intersecting paths
9bac3d6d 10167 */
3df126f3 10168 *prev_src_type = src_reg_type;
9bac3d6d 10169
c64b7983 10170 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
10171 /* ABuser program is trying to use the same insn
10172 * dst_reg = *(u32*) (src_reg + off)
10173 * with different pointer types:
10174 * src_reg == ctx in one branch and
10175 * src_reg == stack|map in some other branch.
10176 * Reject it.
10177 */
61bd5218 10178 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
10179 return -EINVAL;
10180 }
10181
17a52670 10182 } else if (class == BPF_STX) {
3df126f3 10183 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 10184
91c960b0
BJ
10185 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10186 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
10187 if (err)
10188 return err;
c08435ec 10189 env->insn_idx++;
17a52670
AS
10190 continue;
10191 }
10192
5ca419f2
BJ
10193 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10194 verbose(env, "BPF_STX uses reserved fields\n");
10195 return -EINVAL;
10196 }
10197
17a52670 10198 /* check src1 operand */
dc503a8a 10199 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10200 if (err)
10201 return err;
10202 /* check src2 operand */
dc503a8a 10203 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10204 if (err)
10205 return err;
10206
d691f9e8
AS
10207 dst_reg_type = regs[insn->dst_reg].type;
10208
17a52670 10209 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10210 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10211 insn->off, BPF_SIZE(insn->code),
10212 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10213 if (err)
10214 return err;
10215
c08435ec 10216 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10217
10218 if (*prev_dst_type == NOT_INIT) {
10219 *prev_dst_type = dst_reg_type;
c64b7983 10220 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10221 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10222 return -EINVAL;
10223 }
10224
17a52670
AS
10225 } else if (class == BPF_ST) {
10226 if (BPF_MODE(insn->code) != BPF_MEM ||
10227 insn->src_reg != BPF_REG_0) {
61bd5218 10228 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10229 return -EINVAL;
10230 }
10231 /* check src operand */
dc503a8a 10232 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10233 if (err)
10234 return err;
10235
f37a8cb8 10236 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10237 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10238 insn->dst_reg,
10239 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10240 return -EACCES;
10241 }
10242
17a52670 10243 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10244 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10245 insn->off, BPF_SIZE(insn->code),
10246 BPF_WRITE, -1, false);
17a52670
AS
10247 if (err)
10248 return err;
10249
092ed096 10250 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10251 u8 opcode = BPF_OP(insn->code);
10252
2589726d 10253 env->jmps_processed++;
17a52670
AS
10254 if (opcode == BPF_CALL) {
10255 if (BPF_SRC(insn->code) != BPF_K ||
10256 insn->off != 0 ||
f4d7e40a
AS
10257 (insn->src_reg != BPF_REG_0 &&
10258 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
10259 insn->dst_reg != BPF_REG_0 ||
10260 class == BPF_JMP32) {
61bd5218 10261 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10262 return -EINVAL;
10263 }
10264
d83525ca
AS
10265 if (env->cur_state->active_spin_lock &&
10266 (insn->src_reg == BPF_PSEUDO_CALL ||
10267 insn->imm != BPF_FUNC_spin_unlock)) {
10268 verbose(env, "function calls are not allowed while holding a lock\n");
10269 return -EINVAL;
10270 }
f4d7e40a 10271 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10272 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 10273 else
69c087ba 10274 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
10275 if (err)
10276 return err;
17a52670
AS
10277 } else if (opcode == BPF_JA) {
10278 if (BPF_SRC(insn->code) != BPF_K ||
10279 insn->imm != 0 ||
10280 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10281 insn->dst_reg != BPF_REG_0 ||
10282 class == BPF_JMP32) {
61bd5218 10283 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10284 return -EINVAL;
10285 }
10286
c08435ec 10287 env->insn_idx += insn->off + 1;
17a52670
AS
10288 continue;
10289
10290 } else if (opcode == BPF_EXIT) {
10291 if (BPF_SRC(insn->code) != BPF_K ||
10292 insn->imm != 0 ||
10293 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10294 insn->dst_reg != BPF_REG_0 ||
10295 class == BPF_JMP32) {
61bd5218 10296 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10297 return -EINVAL;
10298 }
10299
d83525ca
AS
10300 if (env->cur_state->active_spin_lock) {
10301 verbose(env, "bpf_spin_unlock is missing\n");
10302 return -EINVAL;
10303 }
10304
f4d7e40a
AS
10305 if (state->curframe) {
10306 /* exit from nested function */
c08435ec 10307 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10308 if (err)
10309 return err;
10310 do_print_state = true;
10311 continue;
10312 }
10313
fd978bf7
JS
10314 err = check_reference_leak(env);
10315 if (err)
10316 return err;
10317
390ee7e2
AS
10318 err = check_return_code(env);
10319 if (err)
10320 return err;
f1bca824 10321process_bpf_exit:
2589726d 10322 update_branch_counts(env, env->cur_state);
b5dc0163 10323 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10324 &env->insn_idx, pop_log);
638f5b90
AS
10325 if (err < 0) {
10326 if (err != -ENOENT)
10327 return err;
17a52670
AS
10328 break;
10329 } else {
10330 do_print_state = true;
10331 continue;
10332 }
10333 } else {
c08435ec 10334 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10335 if (err)
10336 return err;
10337 }
10338 } else if (class == BPF_LD) {
10339 u8 mode = BPF_MODE(insn->code);
10340
10341 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10342 err = check_ld_abs(env, insn);
10343 if (err)
10344 return err;
10345
17a52670
AS
10346 } else if (mode == BPF_IMM) {
10347 err = check_ld_imm(env, insn);
10348 if (err)
10349 return err;
10350
c08435ec 10351 env->insn_idx++;
51c39bb1 10352 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 10353 } else {
61bd5218 10354 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10355 return -EINVAL;
10356 }
10357 } else {
61bd5218 10358 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10359 return -EINVAL;
10360 }
10361
c08435ec 10362 env->insn_idx++;
17a52670
AS
10363 }
10364
10365 return 0;
10366}
10367
541c3bad
AN
10368static int find_btf_percpu_datasec(struct btf *btf)
10369{
10370 const struct btf_type *t;
10371 const char *tname;
10372 int i, n;
10373
10374 /*
10375 * Both vmlinux and module each have their own ".data..percpu"
10376 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10377 * types to look at only module's own BTF types.
10378 */
10379 n = btf_nr_types(btf);
10380 if (btf_is_module(btf))
10381 i = btf_nr_types(btf_vmlinux);
10382 else
10383 i = 1;
10384
10385 for(; i < n; i++) {
10386 t = btf_type_by_id(btf, i);
10387 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10388 continue;
10389
10390 tname = btf_name_by_offset(btf, t->name_off);
10391 if (!strcmp(tname, ".data..percpu"))
10392 return i;
10393 }
10394
10395 return -ENOENT;
10396}
10397
4976b718
HL
10398/* replace pseudo btf_id with kernel symbol address */
10399static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10400 struct bpf_insn *insn,
10401 struct bpf_insn_aux_data *aux)
10402{
eaa6bcb7
HL
10403 const struct btf_var_secinfo *vsi;
10404 const struct btf_type *datasec;
541c3bad 10405 struct btf_mod_pair *btf_mod;
4976b718
HL
10406 const struct btf_type *t;
10407 const char *sym_name;
eaa6bcb7 10408 bool percpu = false;
f16e6313 10409 u32 type, id = insn->imm;
541c3bad 10410 struct btf *btf;
f16e6313 10411 s32 datasec_id;
4976b718 10412 u64 addr;
541c3bad 10413 int i, btf_fd, err;
4976b718 10414
541c3bad
AN
10415 btf_fd = insn[1].imm;
10416 if (btf_fd) {
10417 btf = btf_get_by_fd(btf_fd);
10418 if (IS_ERR(btf)) {
10419 verbose(env, "invalid module BTF object FD specified.\n");
10420 return -EINVAL;
10421 }
10422 } else {
10423 if (!btf_vmlinux) {
10424 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10425 return -EINVAL;
10426 }
10427 btf = btf_vmlinux;
10428 btf_get(btf);
4976b718
HL
10429 }
10430
541c3bad 10431 t = btf_type_by_id(btf, id);
4976b718
HL
10432 if (!t) {
10433 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
10434 err = -ENOENT;
10435 goto err_put;
4976b718
HL
10436 }
10437
10438 if (!btf_type_is_var(t)) {
541c3bad
AN
10439 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10440 err = -EINVAL;
10441 goto err_put;
4976b718
HL
10442 }
10443
541c3bad 10444 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10445 addr = kallsyms_lookup_name(sym_name);
10446 if (!addr) {
10447 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10448 sym_name);
541c3bad
AN
10449 err = -ENOENT;
10450 goto err_put;
4976b718
HL
10451 }
10452
541c3bad 10453 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 10454 if (datasec_id > 0) {
541c3bad 10455 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
10456 for_each_vsi(i, datasec, vsi) {
10457 if (vsi->type == id) {
10458 percpu = true;
10459 break;
10460 }
10461 }
10462 }
10463
4976b718
HL
10464 insn[0].imm = (u32)addr;
10465 insn[1].imm = addr >> 32;
10466
10467 type = t->type;
541c3bad 10468 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7
HL
10469 if (percpu) {
10470 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
541c3bad 10471 aux->btf_var.btf = btf;
eaa6bcb7
HL
10472 aux->btf_var.btf_id = type;
10473 } else if (!btf_type_is_struct(t)) {
4976b718
HL
10474 const struct btf_type *ret;
10475 const char *tname;
10476 u32 tsize;
10477
10478 /* resolve the type size of ksym. */
541c3bad 10479 ret = btf_resolve_size(btf, t, &tsize);
4976b718 10480 if (IS_ERR(ret)) {
541c3bad 10481 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
10482 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10483 tname, PTR_ERR(ret));
541c3bad
AN
10484 err = -EINVAL;
10485 goto err_put;
4976b718
HL
10486 }
10487 aux->btf_var.reg_type = PTR_TO_MEM;
10488 aux->btf_var.mem_size = tsize;
10489 } else {
10490 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 10491 aux->btf_var.btf = btf;
4976b718
HL
10492 aux->btf_var.btf_id = type;
10493 }
541c3bad
AN
10494
10495 /* check whether we recorded this BTF (and maybe module) already */
10496 for (i = 0; i < env->used_btf_cnt; i++) {
10497 if (env->used_btfs[i].btf == btf) {
10498 btf_put(btf);
10499 return 0;
10500 }
10501 }
10502
10503 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10504 err = -E2BIG;
10505 goto err_put;
10506 }
10507
10508 btf_mod = &env->used_btfs[env->used_btf_cnt];
10509 btf_mod->btf = btf;
10510 btf_mod->module = NULL;
10511
10512 /* if we reference variables from kernel module, bump its refcount */
10513 if (btf_is_module(btf)) {
10514 btf_mod->module = btf_try_get_module(btf);
10515 if (!btf_mod->module) {
10516 err = -ENXIO;
10517 goto err_put;
10518 }
10519 }
10520
10521 env->used_btf_cnt++;
10522
4976b718 10523 return 0;
541c3bad
AN
10524err_put:
10525 btf_put(btf);
10526 return err;
4976b718
HL
10527}
10528
56f668df
MKL
10529static int check_map_prealloc(struct bpf_map *map)
10530{
10531 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
10532 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10533 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
10534 !(map->map_flags & BPF_F_NO_PREALLOC);
10535}
10536
d83525ca
AS
10537static bool is_tracing_prog_type(enum bpf_prog_type type)
10538{
10539 switch (type) {
10540 case BPF_PROG_TYPE_KPROBE:
10541 case BPF_PROG_TYPE_TRACEPOINT:
10542 case BPF_PROG_TYPE_PERF_EVENT:
10543 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10544 return true;
10545 default:
10546 return false;
10547 }
10548}
10549
94dacdbd
TG
10550static bool is_preallocated_map(struct bpf_map *map)
10551{
10552 if (!check_map_prealloc(map))
10553 return false;
10554 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10555 return false;
10556 return true;
10557}
10558
61bd5218
JK
10559static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10560 struct bpf_map *map,
fdc15d38
AS
10561 struct bpf_prog *prog)
10562
10563{
7e40781c 10564 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
10565 /*
10566 * Validate that trace type programs use preallocated hash maps.
10567 *
10568 * For programs attached to PERF events this is mandatory as the
10569 * perf NMI can hit any arbitrary code sequence.
10570 *
10571 * All other trace types using preallocated hash maps are unsafe as
10572 * well because tracepoint or kprobes can be inside locked regions
10573 * of the memory allocator or at a place where a recursion into the
10574 * memory allocator would see inconsistent state.
10575 *
2ed905c5
TG
10576 * On RT enabled kernels run-time allocation of all trace type
10577 * programs is strictly prohibited due to lock type constraints. On
10578 * !RT kernels it is allowed for backwards compatibility reasons for
10579 * now, but warnings are emitted so developers are made aware of
10580 * the unsafety and can fix their programs before this is enforced.
56f668df 10581 */
7e40781c
UP
10582 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10583 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 10584 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
10585 return -EINVAL;
10586 }
2ed905c5
TG
10587 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10588 verbose(env, "trace type programs can only use preallocated hash map\n");
10589 return -EINVAL;
10590 }
94dacdbd
TG
10591 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10592 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 10593 }
a3884572 10594
9e7a4d98
KS
10595 if (map_value_has_spin_lock(map)) {
10596 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10597 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10598 return -EINVAL;
10599 }
10600
10601 if (is_tracing_prog_type(prog_type)) {
10602 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10603 return -EINVAL;
10604 }
10605
10606 if (prog->aux->sleepable) {
10607 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10608 return -EINVAL;
10609 }
d83525ca
AS
10610 }
10611
a3884572 10612 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 10613 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
10614 verbose(env, "offload device mismatch between prog and map\n");
10615 return -EINVAL;
10616 }
10617
85d33df3
MKL
10618 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10619 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10620 return -EINVAL;
10621 }
10622
1e6c62a8
AS
10623 if (prog->aux->sleepable)
10624 switch (map->map_type) {
10625 case BPF_MAP_TYPE_HASH:
10626 case BPF_MAP_TYPE_LRU_HASH:
10627 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
10628 case BPF_MAP_TYPE_PERCPU_HASH:
10629 case BPF_MAP_TYPE_PERCPU_ARRAY:
10630 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10631 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10632 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
10633 if (!is_preallocated_map(map)) {
10634 verbose(env,
638e4b82 10635 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
10636 return -EINVAL;
10637 }
10638 break;
ba90c2cc
KS
10639 case BPF_MAP_TYPE_RINGBUF:
10640 break;
1e6c62a8
AS
10641 default:
10642 verbose(env,
ba90c2cc 10643 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
10644 return -EINVAL;
10645 }
10646
fdc15d38
AS
10647 return 0;
10648}
10649
b741f163
RG
10650static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10651{
10652 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10653 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10654}
10655
4976b718
HL
10656/* find and rewrite pseudo imm in ld_imm64 instructions:
10657 *
10658 * 1. if it accesses map FD, replace it with actual map pointer.
10659 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10660 *
10661 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 10662 */
4976b718 10663static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
10664{
10665 struct bpf_insn *insn = env->prog->insnsi;
10666 int insn_cnt = env->prog->len;
fdc15d38 10667 int i, j, err;
0246e64d 10668
f1f7714e 10669 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
10670 if (err)
10671 return err;
10672
0246e64d 10673 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 10674 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 10675 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 10676 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
10677 return -EINVAL;
10678 }
10679
0246e64d 10680 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 10681 struct bpf_insn_aux_data *aux;
0246e64d
AS
10682 struct bpf_map *map;
10683 struct fd f;
d8eca5bb 10684 u64 addr;
0246e64d
AS
10685
10686 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10687 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10688 insn[1].off != 0) {
61bd5218 10689 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
10690 return -EINVAL;
10691 }
10692
d8eca5bb 10693 if (insn[0].src_reg == 0)
0246e64d
AS
10694 /* valid generic load 64-bit imm */
10695 goto next_insn;
10696
4976b718
HL
10697 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10698 aux = &env->insn_aux_data[i];
10699 err = check_pseudo_btf_id(env, insn, aux);
10700 if (err)
10701 return err;
10702 goto next_insn;
10703 }
10704
69c087ba
YS
10705 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
10706 aux = &env->insn_aux_data[i];
10707 aux->ptr_type = PTR_TO_FUNC;
10708 goto next_insn;
10709 }
10710
d8eca5bb
DB
10711 /* In final convert_pseudo_ld_imm64() step, this is
10712 * converted into regular 64-bit imm load insn.
10713 */
10714 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10715 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10716 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10717 insn[1].imm != 0)) {
10718 verbose(env,
10719 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
10720 return -EINVAL;
10721 }
10722
20182390 10723 f = fdget(insn[0].imm);
c2101297 10724 map = __bpf_map_get(f);
0246e64d 10725 if (IS_ERR(map)) {
61bd5218 10726 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 10727 insn[0].imm);
0246e64d
AS
10728 return PTR_ERR(map);
10729 }
10730
61bd5218 10731 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
10732 if (err) {
10733 fdput(f);
10734 return err;
10735 }
10736
d8eca5bb
DB
10737 aux = &env->insn_aux_data[i];
10738 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10739 addr = (unsigned long)map;
10740 } else {
10741 u32 off = insn[1].imm;
10742
10743 if (off >= BPF_MAX_VAR_OFF) {
10744 verbose(env, "direct value offset of %u is not allowed\n", off);
10745 fdput(f);
10746 return -EINVAL;
10747 }
10748
10749 if (!map->ops->map_direct_value_addr) {
10750 verbose(env, "no direct value access support for this map type\n");
10751 fdput(f);
10752 return -EINVAL;
10753 }
10754
10755 err = map->ops->map_direct_value_addr(map, &addr, off);
10756 if (err) {
10757 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10758 map->value_size, off);
10759 fdput(f);
10760 return err;
10761 }
10762
10763 aux->map_off = off;
10764 addr += off;
10765 }
10766
10767 insn[0].imm = (u32)addr;
10768 insn[1].imm = addr >> 32;
0246e64d
AS
10769
10770 /* check whether we recorded this map already */
d8eca5bb 10771 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 10772 if (env->used_maps[j] == map) {
d8eca5bb 10773 aux->map_index = j;
0246e64d
AS
10774 fdput(f);
10775 goto next_insn;
10776 }
d8eca5bb 10777 }
0246e64d
AS
10778
10779 if (env->used_map_cnt >= MAX_USED_MAPS) {
10780 fdput(f);
10781 return -E2BIG;
10782 }
10783
0246e64d
AS
10784 /* hold the map. If the program is rejected by verifier,
10785 * the map will be released by release_maps() or it
10786 * will be used by the valid program until it's unloaded
ab7f5bf0 10787 * and all maps are released in free_used_maps()
0246e64d 10788 */
1e0bd5a0 10789 bpf_map_inc(map);
d8eca5bb
DB
10790
10791 aux->map_index = env->used_map_cnt;
92117d84
AS
10792 env->used_maps[env->used_map_cnt++] = map;
10793
b741f163 10794 if (bpf_map_is_cgroup_storage(map) &&
e4730423 10795 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 10796 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
10797 fdput(f);
10798 return -EBUSY;
10799 }
10800
0246e64d
AS
10801 fdput(f);
10802next_insn:
10803 insn++;
10804 i++;
5e581dad
DB
10805 continue;
10806 }
10807
10808 /* Basic sanity check before we invest more work here. */
10809 if (!bpf_opcode_in_insntable(insn->code)) {
10810 verbose(env, "unknown opcode %02x\n", insn->code);
10811 return -EINVAL;
0246e64d
AS
10812 }
10813 }
10814
10815 /* now all pseudo BPF_LD_IMM64 instructions load valid
10816 * 'struct bpf_map *' into a register instead of user map_fd.
10817 * These pointers will be used later by verifier to validate map access.
10818 */
10819 return 0;
10820}
10821
10822/* drop refcnt of maps used by the rejected program */
58e2af8b 10823static void release_maps(struct bpf_verifier_env *env)
0246e64d 10824{
a2ea0746
DB
10825 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10826 env->used_map_cnt);
0246e64d
AS
10827}
10828
541c3bad
AN
10829/* drop refcnt of maps used by the rejected program */
10830static void release_btfs(struct bpf_verifier_env *env)
10831{
10832 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10833 env->used_btf_cnt);
10834}
10835
0246e64d 10836/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 10837static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
10838{
10839 struct bpf_insn *insn = env->prog->insnsi;
10840 int insn_cnt = env->prog->len;
10841 int i;
10842
69c087ba
YS
10843 for (i = 0; i < insn_cnt; i++, insn++) {
10844 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
10845 continue;
10846 if (insn->src_reg == BPF_PSEUDO_FUNC)
10847 continue;
10848 insn->src_reg = 0;
10849 }
0246e64d
AS
10850}
10851
8041902d
AS
10852/* single env->prog->insni[off] instruction was replaced with the range
10853 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10854 * [0, off) and [off, end) to new locations, so the patched range stays zero
10855 */
b325fbca
JW
10856static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10857 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
10858{
10859 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
10860 struct bpf_insn *insn = new_prog->insnsi;
10861 u32 prog_len;
c131187d 10862 int i;
8041902d 10863
b325fbca
JW
10864 /* aux info at OFF always needs adjustment, no matter fast path
10865 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10866 * original insn at old prog.
10867 */
10868 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10869
8041902d
AS
10870 if (cnt == 1)
10871 return 0;
b325fbca 10872 prog_len = new_prog->len;
fad953ce
KC
10873 new_data = vzalloc(array_size(prog_len,
10874 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
10875 if (!new_data)
10876 return -ENOMEM;
10877 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10878 memcpy(new_data + off + cnt - 1, old_data + off,
10879 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 10880 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 10881 new_data[i].seen = env->pass_cnt;
b325fbca
JW
10882 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10883 }
8041902d
AS
10884 env->insn_aux_data = new_data;
10885 vfree(old_data);
10886 return 0;
10887}
10888
cc8b0b92
AS
10889static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10890{
10891 int i;
10892
10893 if (len == 1)
10894 return;
4cb3d99c
JW
10895 /* NOTE: fake 'exit' subprog should be updated as well. */
10896 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 10897 if (env->subprog_info[i].start <= off)
cc8b0b92 10898 continue;
9c8105bd 10899 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
10900 }
10901}
10902
a748c697
MF
10903static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10904{
10905 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10906 int i, sz = prog->aux->size_poke_tab;
10907 struct bpf_jit_poke_descriptor *desc;
10908
10909 for (i = 0; i < sz; i++) {
10910 desc = &tab[i];
10911 desc->insn_idx += len - 1;
10912 }
10913}
10914
8041902d
AS
10915static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10916 const struct bpf_insn *patch, u32 len)
10917{
10918 struct bpf_prog *new_prog;
10919
10920 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
10921 if (IS_ERR(new_prog)) {
10922 if (PTR_ERR(new_prog) == -ERANGE)
10923 verbose(env,
10924 "insn %d cannot be patched due to 16-bit range\n",
10925 env->insn_aux_data[off].orig_idx);
8041902d 10926 return NULL;
4f73379e 10927 }
b325fbca 10928 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 10929 return NULL;
cc8b0b92 10930 adjust_subprog_starts(env, off, len);
a748c697 10931 adjust_poke_descs(new_prog, len);
8041902d
AS
10932 return new_prog;
10933}
10934
52875a04
JK
10935static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10936 u32 off, u32 cnt)
10937{
10938 int i, j;
10939
10940 /* find first prog starting at or after off (first to remove) */
10941 for (i = 0; i < env->subprog_cnt; i++)
10942 if (env->subprog_info[i].start >= off)
10943 break;
10944 /* find first prog starting at or after off + cnt (first to stay) */
10945 for (j = i; j < env->subprog_cnt; j++)
10946 if (env->subprog_info[j].start >= off + cnt)
10947 break;
10948 /* if j doesn't start exactly at off + cnt, we are just removing
10949 * the front of previous prog
10950 */
10951 if (env->subprog_info[j].start != off + cnt)
10952 j--;
10953
10954 if (j > i) {
10955 struct bpf_prog_aux *aux = env->prog->aux;
10956 int move;
10957
10958 /* move fake 'exit' subprog as well */
10959 move = env->subprog_cnt + 1 - j;
10960
10961 memmove(env->subprog_info + i,
10962 env->subprog_info + j,
10963 sizeof(*env->subprog_info) * move);
10964 env->subprog_cnt -= j - i;
10965
10966 /* remove func_info */
10967 if (aux->func_info) {
10968 move = aux->func_info_cnt - j;
10969
10970 memmove(aux->func_info + i,
10971 aux->func_info + j,
10972 sizeof(*aux->func_info) * move);
10973 aux->func_info_cnt -= j - i;
10974 /* func_info->insn_off is set after all code rewrites,
10975 * in adjust_btf_func() - no need to adjust
10976 */
10977 }
10978 } else {
10979 /* convert i from "first prog to remove" to "first to adjust" */
10980 if (env->subprog_info[i].start == off)
10981 i++;
10982 }
10983
10984 /* update fake 'exit' subprog as well */
10985 for (; i <= env->subprog_cnt; i++)
10986 env->subprog_info[i].start -= cnt;
10987
10988 return 0;
10989}
10990
10991static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10992 u32 cnt)
10993{
10994 struct bpf_prog *prog = env->prog;
10995 u32 i, l_off, l_cnt, nr_linfo;
10996 struct bpf_line_info *linfo;
10997
10998 nr_linfo = prog->aux->nr_linfo;
10999 if (!nr_linfo)
11000 return 0;
11001
11002 linfo = prog->aux->linfo;
11003
11004 /* find first line info to remove, count lines to be removed */
11005 for (i = 0; i < nr_linfo; i++)
11006 if (linfo[i].insn_off >= off)
11007 break;
11008
11009 l_off = i;
11010 l_cnt = 0;
11011 for (; i < nr_linfo; i++)
11012 if (linfo[i].insn_off < off + cnt)
11013 l_cnt++;
11014 else
11015 break;
11016
11017 /* First live insn doesn't match first live linfo, it needs to "inherit"
11018 * last removed linfo. prog is already modified, so prog->len == off
11019 * means no live instructions after (tail of the program was removed).
11020 */
11021 if (prog->len != off && l_cnt &&
11022 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11023 l_cnt--;
11024 linfo[--i].insn_off = off + cnt;
11025 }
11026
11027 /* remove the line info which refer to the removed instructions */
11028 if (l_cnt) {
11029 memmove(linfo + l_off, linfo + i,
11030 sizeof(*linfo) * (nr_linfo - i));
11031
11032 prog->aux->nr_linfo -= l_cnt;
11033 nr_linfo = prog->aux->nr_linfo;
11034 }
11035
11036 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11037 for (i = l_off; i < nr_linfo; i++)
11038 linfo[i].insn_off -= cnt;
11039
11040 /* fix up all subprogs (incl. 'exit') which start >= off */
11041 for (i = 0; i <= env->subprog_cnt; i++)
11042 if (env->subprog_info[i].linfo_idx > l_off) {
11043 /* program may have started in the removed region but
11044 * may not be fully removed
11045 */
11046 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11047 env->subprog_info[i].linfo_idx -= l_cnt;
11048 else
11049 env->subprog_info[i].linfo_idx = l_off;
11050 }
11051
11052 return 0;
11053}
11054
11055static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11056{
11057 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11058 unsigned int orig_prog_len = env->prog->len;
11059 int err;
11060
08ca90af
JK
11061 if (bpf_prog_is_dev_bound(env->prog->aux))
11062 bpf_prog_offload_remove_insns(env, off, cnt);
11063
52875a04
JK
11064 err = bpf_remove_insns(env->prog, off, cnt);
11065 if (err)
11066 return err;
11067
11068 err = adjust_subprog_starts_after_remove(env, off, cnt);
11069 if (err)
11070 return err;
11071
11072 err = bpf_adj_linfo_after_remove(env, off, cnt);
11073 if (err)
11074 return err;
11075
11076 memmove(aux_data + off, aux_data + off + cnt,
11077 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11078
11079 return 0;
11080}
11081
2a5418a1
DB
11082/* The verifier does more data flow analysis than llvm and will not
11083 * explore branches that are dead at run time. Malicious programs can
11084 * have dead code too. Therefore replace all dead at-run-time code
11085 * with 'ja -1'.
11086 *
11087 * Just nops are not optimal, e.g. if they would sit at the end of the
11088 * program and through another bug we would manage to jump there, then
11089 * we'd execute beyond program memory otherwise. Returning exception
11090 * code also wouldn't work since we can have subprogs where the dead
11091 * code could be located.
c131187d
AS
11092 */
11093static void sanitize_dead_code(struct bpf_verifier_env *env)
11094{
11095 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 11096 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
11097 struct bpf_insn *insn = env->prog->insnsi;
11098 const int insn_cnt = env->prog->len;
11099 int i;
11100
11101 for (i = 0; i < insn_cnt; i++) {
11102 if (aux_data[i].seen)
11103 continue;
2a5418a1 11104 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
11105 }
11106}
11107
e2ae4ca2
JK
11108static bool insn_is_cond_jump(u8 code)
11109{
11110 u8 op;
11111
092ed096
JW
11112 if (BPF_CLASS(code) == BPF_JMP32)
11113 return true;
11114
e2ae4ca2
JK
11115 if (BPF_CLASS(code) != BPF_JMP)
11116 return false;
11117
11118 op = BPF_OP(code);
11119 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11120}
11121
11122static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11123{
11124 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11125 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11126 struct bpf_insn *insn = env->prog->insnsi;
11127 const int insn_cnt = env->prog->len;
11128 int i;
11129
11130 for (i = 0; i < insn_cnt; i++, insn++) {
11131 if (!insn_is_cond_jump(insn->code))
11132 continue;
11133
11134 if (!aux_data[i + 1].seen)
11135 ja.off = insn->off;
11136 else if (!aux_data[i + 1 + insn->off].seen)
11137 ja.off = 0;
11138 else
11139 continue;
11140
08ca90af
JK
11141 if (bpf_prog_is_dev_bound(env->prog->aux))
11142 bpf_prog_offload_replace_insn(env, i, &ja);
11143
e2ae4ca2
JK
11144 memcpy(insn, &ja, sizeof(ja));
11145 }
11146}
11147
52875a04
JK
11148static int opt_remove_dead_code(struct bpf_verifier_env *env)
11149{
11150 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11151 int insn_cnt = env->prog->len;
11152 int i, err;
11153
11154 for (i = 0; i < insn_cnt; i++) {
11155 int j;
11156
11157 j = 0;
11158 while (i + j < insn_cnt && !aux_data[i + j].seen)
11159 j++;
11160 if (!j)
11161 continue;
11162
11163 err = verifier_remove_insns(env, i, j);
11164 if (err)
11165 return err;
11166 insn_cnt = env->prog->len;
11167 }
11168
11169 return 0;
11170}
11171
a1b14abc
JK
11172static int opt_remove_nops(struct bpf_verifier_env *env)
11173{
11174 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11175 struct bpf_insn *insn = env->prog->insnsi;
11176 int insn_cnt = env->prog->len;
11177 int i, err;
11178
11179 for (i = 0; i < insn_cnt; i++) {
11180 if (memcmp(&insn[i], &ja, sizeof(ja)))
11181 continue;
11182
11183 err = verifier_remove_insns(env, i, 1);
11184 if (err)
11185 return err;
11186 insn_cnt--;
11187 i--;
11188 }
11189
11190 return 0;
11191}
11192
d6c2308c
JW
11193static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11194 const union bpf_attr *attr)
a4b1d3c1 11195{
d6c2308c 11196 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 11197 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 11198 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 11199 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 11200 struct bpf_prog *new_prog;
d6c2308c 11201 bool rnd_hi32;
a4b1d3c1 11202
d6c2308c 11203 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 11204 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
11205 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11206 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11207 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
11208 for (i = 0; i < len; i++) {
11209 int adj_idx = i + delta;
11210 struct bpf_insn insn;
b2e37a71 11211 u8 load_reg;
a4b1d3c1 11212
d6c2308c
JW
11213 insn = insns[adj_idx];
11214 if (!aux[adj_idx].zext_dst) {
11215 u8 code, class;
11216 u32 imm_rnd;
11217
11218 if (!rnd_hi32)
11219 continue;
11220
11221 code = insn.code;
11222 class = BPF_CLASS(code);
11223 if (insn_no_def(&insn))
11224 continue;
11225
11226 /* NOTE: arg "reg" (the fourth one) is only used for
11227 * BPF_STX which has been ruled out in above
11228 * check, it is safe to pass NULL here.
11229 */
11230 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11231 if (class == BPF_LD &&
11232 BPF_MODE(code) == BPF_IMM)
11233 i++;
11234 continue;
11235 }
11236
11237 /* ctx load could be transformed into wider load. */
11238 if (class == BPF_LDX &&
11239 aux[adj_idx].ptr_type == PTR_TO_CTX)
11240 continue;
11241
11242 imm_rnd = get_random_int();
11243 rnd_hi32_patch[0] = insn;
11244 rnd_hi32_patch[1].imm = imm_rnd;
11245 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11246 patch = rnd_hi32_patch;
11247 patch_len = 4;
11248 goto apply_patch_buffer;
11249 }
11250
11251 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
11252 continue;
11253
b2e37a71
IL
11254 /* zext_dst means that we want to zero-extend whatever register
11255 * the insn defines, which is dst_reg most of the time, with
11256 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH.
11257 */
11258 if (BPF_CLASS(insn.code) == BPF_STX &&
11259 BPF_MODE(insn.code) == BPF_ATOMIC) {
11260 /* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not
11261 * define any registers, therefore zext_dst cannot be
11262 * set.
11263 */
11264 if (WARN_ON(!(insn.imm & BPF_FETCH)))
11265 return -EINVAL;
11266 load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0
11267 : insn.src_reg;
11268 } else {
11269 load_reg = insn.dst_reg;
11270 }
11271
a4b1d3c1 11272 zext_patch[0] = insn;
b2e37a71
IL
11273 zext_patch[1].dst_reg = load_reg;
11274 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
11275 patch = zext_patch;
11276 patch_len = 2;
11277apply_patch_buffer:
11278 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
11279 if (!new_prog)
11280 return -ENOMEM;
11281 env->prog = new_prog;
11282 insns = new_prog->insnsi;
11283 aux = env->insn_aux_data;
d6c2308c 11284 delta += patch_len - 1;
a4b1d3c1
JW
11285 }
11286
11287 return 0;
11288}
11289
c64b7983
JS
11290/* convert load instructions that access fields of a context type into a
11291 * sequence of instructions that access fields of the underlying structure:
11292 * struct __sk_buff -> struct sk_buff
11293 * struct bpf_sock_ops -> struct sock
9bac3d6d 11294 */
58e2af8b 11295static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 11296{
00176a34 11297 const struct bpf_verifier_ops *ops = env->ops;
f96da094 11298 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 11299 const int insn_cnt = env->prog->len;
36bbef52 11300 struct bpf_insn insn_buf[16], *insn;
46f53a65 11301 u32 target_size, size_default, off;
9bac3d6d 11302 struct bpf_prog *new_prog;
d691f9e8 11303 enum bpf_access_type type;
f96da094 11304 bool is_narrower_load;
9bac3d6d 11305
b09928b9
DB
11306 if (ops->gen_prologue || env->seen_direct_write) {
11307 if (!ops->gen_prologue) {
11308 verbose(env, "bpf verifier is misconfigured\n");
11309 return -EINVAL;
11310 }
36bbef52
DB
11311 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11312 env->prog);
11313 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11314 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11315 return -EINVAL;
11316 } else if (cnt) {
8041902d 11317 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11318 if (!new_prog)
11319 return -ENOMEM;
8041902d 11320
36bbef52 11321 env->prog = new_prog;
3df126f3 11322 delta += cnt - 1;
36bbef52
DB
11323 }
11324 }
11325
c64b7983 11326 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11327 return 0;
11328
3df126f3 11329 insn = env->prog->insnsi + delta;
36bbef52 11330
9bac3d6d 11331 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11332 bpf_convert_ctx_access_t convert_ctx_access;
11333
62c7989b
DB
11334 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11335 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11336 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11337 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11338 type = BPF_READ;
62c7989b
DB
11339 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11340 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11341 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11342 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11343 type = BPF_WRITE;
11344 else
9bac3d6d
AS
11345 continue;
11346
af86ca4e
AS
11347 if (type == BPF_WRITE &&
11348 env->insn_aux_data[i + delta].sanitize_stack_off) {
11349 struct bpf_insn patch[] = {
11350 /* Sanitize suspicious stack slot with zero.
11351 * There are no memory dependencies for this store,
11352 * since it's only using frame pointer and immediate
11353 * constant of zero
11354 */
11355 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11356 env->insn_aux_data[i + delta].sanitize_stack_off,
11357 0),
11358 /* the original STX instruction will immediately
11359 * overwrite the same stack slot with appropriate value
11360 */
11361 *insn,
11362 };
11363
11364 cnt = ARRAY_SIZE(patch);
11365 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11366 if (!new_prog)
11367 return -ENOMEM;
11368
11369 delta += cnt - 1;
11370 env->prog = new_prog;
11371 insn = new_prog->insnsi + i + delta;
11372 continue;
11373 }
11374
c64b7983
JS
11375 switch (env->insn_aux_data[i + delta].ptr_type) {
11376 case PTR_TO_CTX:
11377 if (!ops->convert_ctx_access)
11378 continue;
11379 convert_ctx_access = ops->convert_ctx_access;
11380 break;
11381 case PTR_TO_SOCKET:
46f8bc92 11382 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11383 convert_ctx_access = bpf_sock_convert_ctx_access;
11384 break;
655a51e5
MKL
11385 case PTR_TO_TCP_SOCK:
11386 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11387 break;
fada7fdc
JL
11388 case PTR_TO_XDP_SOCK:
11389 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11390 break;
2a02759e 11391 case PTR_TO_BTF_ID:
27ae7997
MKL
11392 if (type == BPF_READ) {
11393 insn->code = BPF_LDX | BPF_PROBE_MEM |
11394 BPF_SIZE((insn)->code);
11395 env->prog->aux->num_exentries++;
7e40781c 11396 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11397 verbose(env, "Writes through BTF pointers are not allowed\n");
11398 return -EINVAL;
11399 }
2a02759e 11400 continue;
c64b7983 11401 default:
9bac3d6d 11402 continue;
c64b7983 11403 }
9bac3d6d 11404
31fd8581 11405 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11406 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11407
11408 /* If the read access is a narrower load of the field,
11409 * convert to a 4/8-byte load, to minimum program type specific
11410 * convert_ctx_access changes. If conversion is successful,
11411 * we will apply proper mask to the result.
11412 */
f96da094 11413 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11414 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11415 off = insn->off;
31fd8581 11416 if (is_narrower_load) {
f96da094
DB
11417 u8 size_code;
11418
11419 if (type == BPF_WRITE) {
61bd5218 11420 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
11421 return -EINVAL;
11422 }
31fd8581 11423
f96da094 11424 size_code = BPF_H;
31fd8581
YS
11425 if (ctx_field_size == 4)
11426 size_code = BPF_W;
11427 else if (ctx_field_size == 8)
11428 size_code = BPF_DW;
f96da094 11429
bc23105c 11430 insn->off = off & ~(size_default - 1);
31fd8581
YS
11431 insn->code = BPF_LDX | BPF_MEM | size_code;
11432 }
f96da094
DB
11433
11434 target_size = 0;
c64b7983
JS
11435 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11436 &target_size);
f96da094
DB
11437 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11438 (ctx_field_size && !target_size)) {
61bd5218 11439 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
11440 return -EINVAL;
11441 }
f96da094
DB
11442
11443 if (is_narrower_load && size < target_size) {
d895a0f1
IL
11444 u8 shift = bpf_ctx_narrow_access_offset(
11445 off, size, size_default) * 8;
46f53a65
AI
11446 if (ctx_field_size <= 4) {
11447 if (shift)
11448 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11449 insn->dst_reg,
11450 shift);
31fd8581 11451 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 11452 (1 << size * 8) - 1);
46f53a65
AI
11453 } else {
11454 if (shift)
11455 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11456 insn->dst_reg,
11457 shift);
31fd8581 11458 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 11459 (1ULL << size * 8) - 1);
46f53a65 11460 }
31fd8581 11461 }
9bac3d6d 11462
8041902d 11463 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
11464 if (!new_prog)
11465 return -ENOMEM;
11466
3df126f3 11467 delta += cnt - 1;
9bac3d6d
AS
11468
11469 /* keep walking new program and skip insns we just inserted */
11470 env->prog = new_prog;
3df126f3 11471 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
11472 }
11473
11474 return 0;
11475}
11476
1c2a088a
AS
11477static int jit_subprogs(struct bpf_verifier_env *env)
11478{
11479 struct bpf_prog *prog = env->prog, **func, *tmp;
11480 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 11481 struct bpf_map *map_ptr;
7105e828 11482 struct bpf_insn *insn;
1c2a088a 11483 void *old_bpf_func;
c4c0bdc0 11484 int err, num_exentries;
1c2a088a 11485
f910cefa 11486 if (env->subprog_cnt <= 1)
1c2a088a
AS
11487 return 0;
11488
7105e828 11489 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11490 if (bpf_pseudo_func(insn)) {
11491 env->insn_aux_data[i].call_imm = insn->imm;
11492 /* subprog is encoded in insn[1].imm */
11493 continue;
11494 }
11495
23a2d70c 11496 if (!bpf_pseudo_call(insn))
1c2a088a 11497 continue;
c7a89784
DB
11498 /* Upon error here we cannot fall back to interpreter but
11499 * need a hard reject of the program. Thus -EFAULT is
11500 * propagated in any case.
11501 */
1c2a088a
AS
11502 subprog = find_subprog(env, i + insn->imm + 1);
11503 if (subprog < 0) {
11504 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11505 i + insn->imm + 1);
11506 return -EFAULT;
11507 }
11508 /* temporarily remember subprog id inside insn instead of
11509 * aux_data, since next loop will split up all insns into funcs
11510 */
f910cefa 11511 insn->off = subprog;
1c2a088a
AS
11512 /* remember original imm in case JIT fails and fallback
11513 * to interpreter will be needed
11514 */
11515 env->insn_aux_data[i].call_imm = insn->imm;
11516 /* point imm to __bpf_call_base+1 from JITs point of view */
11517 insn->imm = 1;
11518 }
11519
c454a46b
MKL
11520 err = bpf_prog_alloc_jited_linfo(prog);
11521 if (err)
11522 goto out_undo_insn;
11523
11524 err = -ENOMEM;
6396bb22 11525 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 11526 if (!func)
c7a89784 11527 goto out_undo_insn;
1c2a088a 11528
f910cefa 11529 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 11530 subprog_start = subprog_end;
4cb3d99c 11531 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
11532
11533 len = subprog_end - subprog_start;
492ecee8
AS
11534 /* BPF_PROG_RUN doesn't call subprogs directly,
11535 * hence main prog stats include the runtime of subprogs.
11536 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 11537 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
11538 */
11539 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
11540 if (!func[i])
11541 goto out_free;
11542 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11543 len * sizeof(struct bpf_insn));
4f74d809 11544 func[i]->type = prog->type;
1c2a088a 11545 func[i]->len = len;
4f74d809
DB
11546 if (bpf_prog_calc_tag(func[i]))
11547 goto out_free;
1c2a088a 11548 func[i]->is_func = 1;
ba64e7d8
YS
11549 func[i]->aux->func_idx = i;
11550 /* the btf and func_info will be freed only at prog->aux */
11551 func[i]->aux->btf = prog->aux->btf;
11552 func[i]->aux->func_info = prog->aux->func_info;
11553
a748c697
MF
11554 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11555 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11556 int ret;
11557
11558 if (!(insn_idx >= subprog_start &&
11559 insn_idx <= subprog_end))
11560 continue;
11561
11562 ret = bpf_jit_add_poke_descriptor(func[i],
11563 &prog->aux->poke_tab[j]);
11564 if (ret < 0) {
11565 verbose(env, "adding tail call poke descriptor failed\n");
11566 goto out_free;
11567 }
11568
11569 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11570
11571 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11572 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11573 if (ret < 0) {
11574 verbose(env, "tracking tail call prog failed\n");
11575 goto out_free;
11576 }
11577 }
11578
1c2a088a
AS
11579 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11580 * Long term would need debug info to populate names
11581 */
11582 func[i]->aux->name[0] = 'F';
9c8105bd 11583 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 11584 func[i]->jit_requested = 1;
c454a46b
MKL
11585 func[i]->aux->linfo = prog->aux->linfo;
11586 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11587 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11588 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
11589 num_exentries = 0;
11590 insn = func[i]->insnsi;
11591 for (j = 0; j < func[i]->len; j++, insn++) {
11592 if (BPF_CLASS(insn->code) == BPF_LDX &&
11593 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11594 num_exentries++;
11595 }
11596 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 11597 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
11598 func[i] = bpf_int_jit_compile(func[i]);
11599 if (!func[i]->jited) {
11600 err = -ENOTSUPP;
11601 goto out_free;
11602 }
11603 cond_resched();
11604 }
a748c697
MF
11605
11606 /* Untrack main program's aux structs so that during map_poke_run()
11607 * we will not stumble upon the unfilled poke descriptors; each
11608 * of the main program's poke descs got distributed across subprogs
11609 * and got tracked onto map, so we are sure that none of them will
11610 * be missed after the operation below
11611 */
11612 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11613 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11614
11615 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11616 }
11617
1c2a088a
AS
11618 /* at this point all bpf functions were successfully JITed
11619 * now populate all bpf_calls with correct addresses and
11620 * run last pass of JIT
11621 */
f910cefa 11622 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11623 insn = func[i]->insnsi;
11624 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba
YS
11625 if (bpf_pseudo_func(insn)) {
11626 subprog = insn[1].imm;
11627 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
11628 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
11629 continue;
11630 }
23a2d70c 11631 if (!bpf_pseudo_call(insn))
1c2a088a
AS
11632 continue;
11633 subprog = insn->off;
0d306c31
PB
11634 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11635 __bpf_call_base;
1c2a088a 11636 }
2162fed4
SD
11637
11638 /* we use the aux data to keep a list of the start addresses
11639 * of the JITed images for each function in the program
11640 *
11641 * for some architectures, such as powerpc64, the imm field
11642 * might not be large enough to hold the offset of the start
11643 * address of the callee's JITed image from __bpf_call_base
11644 *
11645 * in such cases, we can lookup the start address of a callee
11646 * by using its subprog id, available from the off field of
11647 * the call instruction, as an index for this list
11648 */
11649 func[i]->aux->func = func;
11650 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 11651 }
f910cefa 11652 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11653 old_bpf_func = func[i]->bpf_func;
11654 tmp = bpf_int_jit_compile(func[i]);
11655 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11656 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 11657 err = -ENOTSUPP;
1c2a088a
AS
11658 goto out_free;
11659 }
11660 cond_resched();
11661 }
11662
11663 /* finally lock prog and jit images for all functions and
11664 * populate kallsysm
11665 */
f910cefa 11666 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
11667 bpf_prog_lock_ro(func[i]);
11668 bpf_prog_kallsyms_add(func[i]);
11669 }
7105e828
DB
11670
11671 /* Last step: make now unused interpreter insns from main
11672 * prog consistent for later dump requests, so they can
11673 * later look the same as if they were interpreted only.
11674 */
11675 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
11676 if (bpf_pseudo_func(insn)) {
11677 insn[0].imm = env->insn_aux_data[i].call_imm;
11678 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
11679 continue;
11680 }
23a2d70c 11681 if (!bpf_pseudo_call(insn))
7105e828
DB
11682 continue;
11683 insn->off = env->insn_aux_data[i].call_imm;
11684 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 11685 insn->imm = subprog;
7105e828
DB
11686 }
11687
1c2a088a
AS
11688 prog->jited = 1;
11689 prog->bpf_func = func[0]->bpf_func;
11690 prog->aux->func = func;
f910cefa 11691 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 11692 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
11693 return 0;
11694out_free:
a748c697
MF
11695 for (i = 0; i < env->subprog_cnt; i++) {
11696 if (!func[i])
11697 continue;
11698
11699 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11700 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11701 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11702 }
11703 bpf_jit_free(func[i]);
11704 }
1c2a088a 11705 kfree(func);
c7a89784 11706out_undo_insn:
1c2a088a
AS
11707 /* cleanup main prog to be interpreted */
11708 prog->jit_requested = 0;
11709 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 11710 if (!bpf_pseudo_call(insn))
1c2a088a
AS
11711 continue;
11712 insn->off = 0;
11713 insn->imm = env->insn_aux_data[i].call_imm;
11714 }
c454a46b 11715 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
11716 return err;
11717}
11718
1ea47e01
AS
11719static int fixup_call_args(struct bpf_verifier_env *env)
11720{
19d28fbd 11721#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
11722 struct bpf_prog *prog = env->prog;
11723 struct bpf_insn *insn = prog->insnsi;
11724 int i, depth;
19d28fbd 11725#endif
e4052d06 11726 int err = 0;
1ea47e01 11727
e4052d06
QM
11728 if (env->prog->jit_requested &&
11729 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
11730 err = jit_subprogs(env);
11731 if (err == 0)
1c2a088a 11732 return 0;
c7a89784
DB
11733 if (err == -EFAULT)
11734 return err;
19d28fbd
DM
11735 }
11736#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
11737 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11738 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11739 * have to be rejected, since interpreter doesn't support them yet.
11740 */
11741 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11742 return -EINVAL;
11743 }
1ea47e01 11744 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
11745 if (bpf_pseudo_func(insn)) {
11746 /* When JIT fails the progs with callback calls
11747 * have to be rejected, since interpreter doesn't support them yet.
11748 */
11749 verbose(env, "callbacks are not allowed in non-JITed programs\n");
11750 return -EINVAL;
11751 }
11752
23a2d70c 11753 if (!bpf_pseudo_call(insn))
1ea47e01
AS
11754 continue;
11755 depth = get_callee_stack_depth(env, insn, i);
11756 if (depth < 0)
11757 return depth;
11758 bpf_patch_call_args(insn, depth);
11759 }
19d28fbd
DM
11760 err = 0;
11761#endif
11762 return err;
1ea47e01
AS
11763}
11764
e6ac5933
BJ
11765/* Do various post-verification rewrites in a single program pass.
11766 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 11767 */
e6ac5933 11768static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 11769{
79741b3b 11770 struct bpf_prog *prog = env->prog;
d2e4c1e6 11771 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 11772 struct bpf_insn *insn = prog->insnsi;
e245c5c6 11773 const struct bpf_func_proto *fn;
79741b3b 11774 const int insn_cnt = prog->len;
09772d92 11775 const struct bpf_map_ops *ops;
c93552c4 11776 struct bpf_insn_aux_data *aux;
81ed18ab
AS
11777 struct bpf_insn insn_buf[16];
11778 struct bpf_prog *new_prog;
11779 struct bpf_map *map_ptr;
d2e4c1e6 11780 int i, ret, cnt, delta = 0;
e245c5c6 11781
79741b3b 11782 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 11783 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
11784 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11785 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11786 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 11787 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 11788 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
11789 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11790 struct bpf_insn *patchlet;
11791 struct bpf_insn chk_and_div[] = {
9b00f1b7 11792 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
11793 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11794 BPF_JNE | BPF_K, insn->src_reg,
11795 0, 2, 0),
f6b1b3bf
DB
11796 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11797 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11798 *insn,
11799 };
e88b2c6e 11800 struct bpf_insn chk_and_mod[] = {
9b00f1b7 11801 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
11802 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11803 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 11804 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 11805 *insn,
9b00f1b7
DB
11806 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11807 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 11808 };
f6b1b3bf 11809
e88b2c6e
DB
11810 patchlet = isdiv ? chk_and_div : chk_and_mod;
11811 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 11812 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
11813
11814 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
11815 if (!new_prog)
11816 return -ENOMEM;
11817
11818 delta += cnt - 1;
11819 env->prog = prog = new_prog;
11820 insn = new_prog->insnsi + i + delta;
11821 continue;
11822 }
11823
e6ac5933 11824 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
11825 if (BPF_CLASS(insn->code) == BPF_LD &&
11826 (BPF_MODE(insn->code) == BPF_ABS ||
11827 BPF_MODE(insn->code) == BPF_IND)) {
11828 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11829 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11830 verbose(env, "bpf verifier is misconfigured\n");
11831 return -EINVAL;
11832 }
11833
11834 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11835 if (!new_prog)
11836 return -ENOMEM;
11837
11838 delta += cnt - 1;
11839 env->prog = prog = new_prog;
11840 insn = new_prog->insnsi + i + delta;
11841 continue;
11842 }
11843
e6ac5933 11844 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
11845 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11846 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11847 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11848 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11849 struct bpf_insn insn_buf[16];
11850 struct bpf_insn *patch = &insn_buf[0];
11851 bool issrc, isneg;
11852 u32 off_reg;
11853
11854 aux = &env->insn_aux_data[i + delta];
3612af78
DB
11855 if (!aux->alu_state ||
11856 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
11857 continue;
11858
11859 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11860 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11861 BPF_ALU_SANITIZE_SRC;
11862
11863 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11864 if (isneg)
11865 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11866 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11867 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11868 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11869 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11870 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11871 if (issrc) {
11872 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11873 off_reg);
11874 insn->src_reg = BPF_REG_AX;
11875 } else {
11876 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11877 BPF_REG_AX);
11878 }
11879 if (isneg)
11880 insn->code = insn->code == code_add ?
11881 code_sub : code_add;
11882 *patch++ = *insn;
11883 if (issrc && isneg)
11884 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11885 cnt = patch - insn_buf;
11886
11887 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11888 if (!new_prog)
11889 return -ENOMEM;
11890
11891 delta += cnt - 1;
11892 env->prog = prog = new_prog;
11893 insn = new_prog->insnsi + i + delta;
11894 continue;
11895 }
11896
79741b3b
AS
11897 if (insn->code != (BPF_JMP | BPF_CALL))
11898 continue;
cc8b0b92
AS
11899 if (insn->src_reg == BPF_PSEUDO_CALL)
11900 continue;
e245c5c6 11901
79741b3b
AS
11902 if (insn->imm == BPF_FUNC_get_route_realm)
11903 prog->dst_needed = 1;
11904 if (insn->imm == BPF_FUNC_get_prandom_u32)
11905 bpf_user_rnd_init_once();
9802d865
JB
11906 if (insn->imm == BPF_FUNC_override_return)
11907 prog->kprobe_override = 1;
79741b3b 11908 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
11909 /* If we tail call into other programs, we
11910 * cannot make any assumptions since they can
11911 * be replaced dynamically during runtime in
11912 * the program array.
11913 */
11914 prog->cb_access = 1;
e411901c
MF
11915 if (!allow_tail_call_in_subprogs(env))
11916 prog->aux->stack_depth = MAX_BPF_STACK;
11917 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 11918
79741b3b
AS
11919 /* mark bpf_tail_call as different opcode to avoid
11920 * conditional branch in the interpeter for every normal
11921 * call and to prevent accidental JITing by JIT compiler
11922 * that doesn't support bpf_tail_call yet
e245c5c6 11923 */
79741b3b 11924 insn->imm = 0;
71189fa9 11925 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 11926
c93552c4 11927 aux = &env->insn_aux_data[i + delta];
2c78ee89 11928 if (env->bpf_capable && !expect_blinding &&
cc52d914 11929 prog->jit_requested &&
d2e4c1e6
DB
11930 !bpf_map_key_poisoned(aux) &&
11931 !bpf_map_ptr_poisoned(aux) &&
11932 !bpf_map_ptr_unpriv(aux)) {
11933 struct bpf_jit_poke_descriptor desc = {
11934 .reason = BPF_POKE_REASON_TAIL_CALL,
11935 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11936 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 11937 .insn_idx = i + delta,
d2e4c1e6
DB
11938 };
11939
11940 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11941 if (ret < 0) {
11942 verbose(env, "adding tail call poke descriptor failed\n");
11943 return ret;
11944 }
11945
11946 insn->imm = ret + 1;
11947 continue;
11948 }
11949
c93552c4
DB
11950 if (!bpf_map_ptr_unpriv(aux))
11951 continue;
11952
b2157399
AS
11953 /* instead of changing every JIT dealing with tail_call
11954 * emit two extra insns:
11955 * if (index >= max_entries) goto out;
11956 * index &= array->index_mask;
11957 * to avoid out-of-bounds cpu speculation
11958 */
c93552c4 11959 if (bpf_map_ptr_poisoned(aux)) {
40950343 11960 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
11961 return -EINVAL;
11962 }
c93552c4 11963
d2e4c1e6 11964 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
11965 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11966 map_ptr->max_entries, 2);
11967 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11968 container_of(map_ptr,
11969 struct bpf_array,
11970 map)->index_mask);
11971 insn_buf[2] = *insn;
11972 cnt = 3;
11973 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11974 if (!new_prog)
11975 return -ENOMEM;
11976
11977 delta += cnt - 1;
11978 env->prog = prog = new_prog;
11979 insn = new_prog->insnsi + i + delta;
79741b3b
AS
11980 continue;
11981 }
e245c5c6 11982
89c63074 11983 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
11984 * and other inlining handlers are currently limited to 64 bit
11985 * only.
89c63074 11986 */
60b58afc 11987 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
11988 (insn->imm == BPF_FUNC_map_lookup_elem ||
11989 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
11990 insn->imm == BPF_FUNC_map_delete_elem ||
11991 insn->imm == BPF_FUNC_map_push_elem ||
11992 insn->imm == BPF_FUNC_map_pop_elem ||
11993 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
11994 aux = &env->insn_aux_data[i + delta];
11995 if (bpf_map_ptr_poisoned(aux))
11996 goto patch_call_imm;
11997
d2e4c1e6 11998 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
11999 ops = map_ptr->ops;
12000 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12001 ops->map_gen_lookup) {
12002 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
12003 if (cnt == -EOPNOTSUPP)
12004 goto patch_map_ops_generic;
12005 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
12006 verbose(env, "bpf verifier is misconfigured\n");
12007 return -EINVAL;
12008 }
81ed18ab 12009
09772d92
DB
12010 new_prog = bpf_patch_insn_data(env, i + delta,
12011 insn_buf, cnt);
12012 if (!new_prog)
12013 return -ENOMEM;
81ed18ab 12014
09772d92
DB
12015 delta += cnt - 1;
12016 env->prog = prog = new_prog;
12017 insn = new_prog->insnsi + i + delta;
12018 continue;
12019 }
81ed18ab 12020
09772d92
DB
12021 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12022 (void *(*)(struct bpf_map *map, void *key))NULL));
12023 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12024 (int (*)(struct bpf_map *map, void *key))NULL));
12025 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12026 (int (*)(struct bpf_map *map, void *key, void *value,
12027 u64 flags))NULL));
84430d42
DB
12028 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12029 (int (*)(struct bpf_map *map, void *value,
12030 u64 flags))NULL));
12031 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12032 (int (*)(struct bpf_map *map, void *value))NULL));
12033 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12034 (int (*)(struct bpf_map *map, void *value))NULL));
4a8f87e6 12035patch_map_ops_generic:
09772d92
DB
12036 switch (insn->imm) {
12037 case BPF_FUNC_map_lookup_elem:
12038 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12039 __bpf_call_base;
12040 continue;
12041 case BPF_FUNC_map_update_elem:
12042 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12043 __bpf_call_base;
12044 continue;
12045 case BPF_FUNC_map_delete_elem:
12046 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12047 __bpf_call_base;
12048 continue;
84430d42
DB
12049 case BPF_FUNC_map_push_elem:
12050 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12051 __bpf_call_base;
12052 continue;
12053 case BPF_FUNC_map_pop_elem:
12054 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12055 __bpf_call_base;
12056 continue;
12057 case BPF_FUNC_map_peek_elem:
12058 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12059 __bpf_call_base;
12060 continue;
09772d92 12061 }
81ed18ab 12062
09772d92 12063 goto patch_call_imm;
81ed18ab
AS
12064 }
12065
e6ac5933 12066 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
12067 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12068 insn->imm == BPF_FUNC_jiffies64) {
12069 struct bpf_insn ld_jiffies_addr[2] = {
12070 BPF_LD_IMM64(BPF_REG_0,
12071 (unsigned long)&jiffies),
12072 };
12073
12074 insn_buf[0] = ld_jiffies_addr[0];
12075 insn_buf[1] = ld_jiffies_addr[1];
12076 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12077 BPF_REG_0, 0);
12078 cnt = 3;
12079
12080 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12081 cnt);
12082 if (!new_prog)
12083 return -ENOMEM;
12084
12085 delta += cnt - 1;
12086 env->prog = prog = new_prog;
12087 insn = new_prog->insnsi + i + delta;
12088 continue;
12089 }
12090
81ed18ab 12091patch_call_imm:
5e43f899 12092 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
12093 /* all functions that have prototype and verifier allowed
12094 * programs to call them, must be real in-kernel functions
12095 */
12096 if (!fn->func) {
61bd5218
JK
12097 verbose(env,
12098 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
12099 func_id_name(insn->imm), insn->imm);
12100 return -EFAULT;
e245c5c6 12101 }
79741b3b 12102 insn->imm = fn->func - __bpf_call_base;
e245c5c6 12103 }
e245c5c6 12104
d2e4c1e6
DB
12105 /* Since poke tab is now finalized, publish aux to tracker. */
12106 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12107 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12108 if (!map_ptr->ops->map_poke_track ||
12109 !map_ptr->ops->map_poke_untrack ||
12110 !map_ptr->ops->map_poke_run) {
12111 verbose(env, "bpf verifier is misconfigured\n");
12112 return -EINVAL;
12113 }
12114
12115 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12116 if (ret < 0) {
12117 verbose(env, "tracking tail call prog failed\n");
12118 return ret;
12119 }
12120 }
12121
79741b3b
AS
12122 return 0;
12123}
e245c5c6 12124
58e2af8b 12125static void free_states(struct bpf_verifier_env *env)
f1bca824 12126{
58e2af8b 12127 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
12128 int i;
12129
9f4686c4
AS
12130 sl = env->free_list;
12131 while (sl) {
12132 sln = sl->next;
12133 free_verifier_state(&sl->state, false);
12134 kfree(sl);
12135 sl = sln;
12136 }
51c39bb1 12137 env->free_list = NULL;
9f4686c4 12138
f1bca824
AS
12139 if (!env->explored_states)
12140 return;
12141
dc2a4ebc 12142 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
12143 sl = env->explored_states[i];
12144
a8f500af
AS
12145 while (sl) {
12146 sln = sl->next;
12147 free_verifier_state(&sl->state, false);
12148 kfree(sl);
12149 sl = sln;
12150 }
51c39bb1 12151 env->explored_states[i] = NULL;
f1bca824 12152 }
51c39bb1 12153}
f1bca824 12154
51c39bb1
AS
12155/* The verifier is using insn_aux_data[] to store temporary data during
12156 * verification and to store information for passes that run after the
12157 * verification like dead code sanitization. do_check_common() for subprogram N
12158 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12159 * temporary data after do_check_common() finds that subprogram N cannot be
12160 * verified independently. pass_cnt counts the number of times
12161 * do_check_common() was run and insn->aux->seen tells the pass number
12162 * insn_aux_data was touched. These variables are compared to clear temporary
12163 * data from failed pass. For testing and experiments do_check_common() can be
12164 * run multiple times even when prior attempt to verify is unsuccessful.
12165 */
12166static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12167{
12168 struct bpf_insn *insn = env->prog->insnsi;
12169 struct bpf_insn_aux_data *aux;
12170 int i, class;
12171
12172 for (i = 0; i < env->prog->len; i++) {
12173 class = BPF_CLASS(insn[i].code);
12174 if (class != BPF_LDX && class != BPF_STX)
12175 continue;
12176 aux = &env->insn_aux_data[i];
12177 if (aux->seen != env->pass_cnt)
12178 continue;
12179 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12180 }
f1bca824
AS
12181}
12182
51c39bb1
AS
12183static int do_check_common(struct bpf_verifier_env *env, int subprog)
12184{
6f8a57cc 12185 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
12186 struct bpf_verifier_state *state;
12187 struct bpf_reg_state *regs;
12188 int ret, i;
12189
12190 env->prev_linfo = NULL;
12191 env->pass_cnt++;
12192
12193 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12194 if (!state)
12195 return -ENOMEM;
12196 state->curframe = 0;
12197 state->speculative = false;
12198 state->branches = 1;
12199 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12200 if (!state->frame[0]) {
12201 kfree(state);
12202 return -ENOMEM;
12203 }
12204 env->cur_state = state;
12205 init_func_state(env, state->frame[0],
12206 BPF_MAIN_FUNC /* callsite */,
12207 0 /* frameno */,
12208 subprog);
12209
12210 regs = state->frame[state->curframe]->regs;
be8704ff 12211 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
12212 ret = btf_prepare_func_args(env, subprog, regs);
12213 if (ret)
12214 goto out;
12215 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12216 if (regs[i].type == PTR_TO_CTX)
12217 mark_reg_known_zero(env, regs, i);
12218 else if (regs[i].type == SCALAR_VALUE)
12219 mark_reg_unknown(env, regs, i);
e5069b9c
DB
12220 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12221 const u32 mem_size = regs[i].mem_size;
12222
12223 mark_reg_known_zero(env, regs, i);
12224 regs[i].mem_size = mem_size;
12225 regs[i].id = ++env->id_gen;
12226 }
51c39bb1
AS
12227 }
12228 } else {
12229 /* 1st arg to a function */
12230 regs[BPF_REG_1].type = PTR_TO_CTX;
12231 mark_reg_known_zero(env, regs, BPF_REG_1);
12232 ret = btf_check_func_arg_match(env, subprog, regs);
12233 if (ret == -EFAULT)
12234 /* unlikely verifier bug. abort.
12235 * ret == 0 and ret < 0 are sadly acceptable for
12236 * main() function due to backward compatibility.
12237 * Like socket filter program may be written as:
12238 * int bpf_prog(struct pt_regs *ctx)
12239 * and never dereference that ctx in the program.
12240 * 'struct pt_regs' is a type mismatch for socket
12241 * filter that should be using 'struct __sk_buff'.
12242 */
12243 goto out;
12244 }
12245
12246 ret = do_check(env);
12247out:
f59bbfc2
AS
12248 /* check for NULL is necessary, since cur_state can be freed inside
12249 * do_check() under memory pressure.
12250 */
12251 if (env->cur_state) {
12252 free_verifier_state(env->cur_state, true);
12253 env->cur_state = NULL;
12254 }
6f8a57cc
AN
12255 while (!pop_stack(env, NULL, NULL, false));
12256 if (!ret && pop_log)
12257 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
12258 free_states(env);
12259 if (ret)
12260 /* clean aux data in case subprog was rejected */
12261 sanitize_insn_aux_data(env);
12262 return ret;
12263}
12264
12265/* Verify all global functions in a BPF program one by one based on their BTF.
12266 * All global functions must pass verification. Otherwise the whole program is rejected.
12267 * Consider:
12268 * int bar(int);
12269 * int foo(int f)
12270 * {
12271 * return bar(f);
12272 * }
12273 * int bar(int b)
12274 * {
12275 * ...
12276 * }
12277 * foo() will be verified first for R1=any_scalar_value. During verification it
12278 * will be assumed that bar() already verified successfully and call to bar()
12279 * from foo() will be checked for type match only. Later bar() will be verified
12280 * independently to check that it's safe for R1=any_scalar_value.
12281 */
12282static int do_check_subprogs(struct bpf_verifier_env *env)
12283{
12284 struct bpf_prog_aux *aux = env->prog->aux;
12285 int i, ret;
12286
12287 if (!aux->func_info)
12288 return 0;
12289
12290 for (i = 1; i < env->subprog_cnt; i++) {
12291 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12292 continue;
12293 env->insn_idx = env->subprog_info[i].start;
12294 WARN_ON_ONCE(env->insn_idx == 0);
12295 ret = do_check_common(env, i);
12296 if (ret) {
12297 return ret;
12298 } else if (env->log.level & BPF_LOG_LEVEL) {
12299 verbose(env,
12300 "Func#%d is safe for any args that match its prototype\n",
12301 i);
12302 }
12303 }
12304 return 0;
12305}
12306
12307static int do_check_main(struct bpf_verifier_env *env)
12308{
12309 int ret;
12310
12311 env->insn_idx = 0;
12312 ret = do_check_common(env, 0);
12313 if (!ret)
12314 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12315 return ret;
12316}
12317
12318
06ee7115
AS
12319static void print_verification_stats(struct bpf_verifier_env *env)
12320{
12321 int i;
12322
12323 if (env->log.level & BPF_LOG_STATS) {
12324 verbose(env, "verification time %lld usec\n",
12325 div_u64(env->verification_time, 1000));
12326 verbose(env, "stack depth ");
12327 for (i = 0; i < env->subprog_cnt; i++) {
12328 u32 depth = env->subprog_info[i].stack_depth;
12329
12330 verbose(env, "%d", depth);
12331 if (i + 1 < env->subprog_cnt)
12332 verbose(env, "+");
12333 }
12334 verbose(env, "\n");
12335 }
12336 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12337 "total_states %d peak_states %d mark_read %d\n",
12338 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12339 env->max_states_per_insn, env->total_states,
12340 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12341}
12342
27ae7997
MKL
12343static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12344{
12345 const struct btf_type *t, *func_proto;
12346 const struct bpf_struct_ops *st_ops;
12347 const struct btf_member *member;
12348 struct bpf_prog *prog = env->prog;
12349 u32 btf_id, member_idx;
12350 const char *mname;
12351
12352 btf_id = prog->aux->attach_btf_id;
12353 st_ops = bpf_struct_ops_find(btf_id);
12354 if (!st_ops) {
12355 verbose(env, "attach_btf_id %u is not a supported struct\n",
12356 btf_id);
12357 return -ENOTSUPP;
12358 }
12359
12360 t = st_ops->type;
12361 member_idx = prog->expected_attach_type;
12362 if (member_idx >= btf_type_vlen(t)) {
12363 verbose(env, "attach to invalid member idx %u of struct %s\n",
12364 member_idx, st_ops->name);
12365 return -EINVAL;
12366 }
12367
12368 member = &btf_type_member(t)[member_idx];
12369 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12370 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12371 NULL);
12372 if (!func_proto) {
12373 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12374 mname, member_idx, st_ops->name);
12375 return -EINVAL;
12376 }
12377
12378 if (st_ops->check_member) {
12379 int err = st_ops->check_member(t, member);
12380
12381 if (err) {
12382 verbose(env, "attach to unsupported member %s of struct %s\n",
12383 mname, st_ops->name);
12384 return err;
12385 }
12386 }
12387
12388 prog->aux->attach_func_proto = func_proto;
12389 prog->aux->attach_func_name = mname;
12390 env->ops = st_ops->verifier_ops;
12391
12392 return 0;
12393}
6ba43b76
KS
12394#define SECURITY_PREFIX "security_"
12395
f7b12b6f 12396static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12397{
69191754 12398 if (within_error_injection_list(addr) ||
f7b12b6f 12399 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12400 return 0;
6ba43b76 12401
6ba43b76
KS
12402 return -EINVAL;
12403}
27ae7997 12404
1e6c62a8
AS
12405/* list of non-sleepable functions that are otherwise on
12406 * ALLOW_ERROR_INJECTION list
12407 */
12408BTF_SET_START(btf_non_sleepable_error_inject)
12409/* Three functions below can be called from sleepable and non-sleepable context.
12410 * Assume non-sleepable from bpf safety point of view.
12411 */
12412BTF_ID(func, __add_to_page_cache_locked)
12413BTF_ID(func, should_fail_alloc_page)
12414BTF_ID(func, should_failslab)
12415BTF_SET_END(btf_non_sleepable_error_inject)
12416
12417static int check_non_sleepable_error_inject(u32 btf_id)
12418{
12419 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12420}
12421
f7b12b6f
THJ
12422int bpf_check_attach_target(struct bpf_verifier_log *log,
12423 const struct bpf_prog *prog,
12424 const struct bpf_prog *tgt_prog,
12425 u32 btf_id,
12426 struct bpf_attach_target_info *tgt_info)
38207291 12427{
be8704ff 12428 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 12429 const char prefix[] = "btf_trace_";
5b92a28a 12430 int ret = 0, subprog = -1, i;
38207291 12431 const struct btf_type *t;
5b92a28a 12432 bool conservative = true;
38207291 12433 const char *tname;
5b92a28a 12434 struct btf *btf;
f7b12b6f 12435 long addr = 0;
38207291 12436
f1b9509c 12437 if (!btf_id) {
efc68158 12438 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
12439 return -EINVAL;
12440 }
22dc4a0f 12441 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 12442 if (!btf) {
efc68158 12443 bpf_log(log,
5b92a28a
AS
12444 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12445 return -EINVAL;
12446 }
12447 t = btf_type_by_id(btf, btf_id);
f1b9509c 12448 if (!t) {
efc68158 12449 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
12450 return -EINVAL;
12451 }
5b92a28a 12452 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 12453 if (!tname) {
efc68158 12454 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
12455 return -EINVAL;
12456 }
5b92a28a
AS
12457 if (tgt_prog) {
12458 struct bpf_prog_aux *aux = tgt_prog->aux;
12459
12460 for (i = 0; i < aux->func_info_cnt; i++)
12461 if (aux->func_info[i].type_id == btf_id) {
12462 subprog = i;
12463 break;
12464 }
12465 if (subprog == -1) {
efc68158 12466 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
12467 return -EINVAL;
12468 }
12469 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
12470 if (prog_extension) {
12471 if (conservative) {
efc68158 12472 bpf_log(log,
be8704ff
AS
12473 "Cannot replace static functions\n");
12474 return -EINVAL;
12475 }
12476 if (!prog->jit_requested) {
efc68158 12477 bpf_log(log,
be8704ff
AS
12478 "Extension programs should be JITed\n");
12479 return -EINVAL;
12480 }
be8704ff
AS
12481 }
12482 if (!tgt_prog->jited) {
efc68158 12483 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
12484 return -EINVAL;
12485 }
12486 if (tgt_prog->type == prog->type) {
12487 /* Cannot fentry/fexit another fentry/fexit program.
12488 * Cannot attach program extension to another extension.
12489 * It's ok to attach fentry/fexit to extension program.
12490 */
efc68158 12491 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
12492 return -EINVAL;
12493 }
12494 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12495 prog_extension &&
12496 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12497 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12498 /* Program extensions can extend all program types
12499 * except fentry/fexit. The reason is the following.
12500 * The fentry/fexit programs are used for performance
12501 * analysis, stats and can be attached to any program
12502 * type except themselves. When extension program is
12503 * replacing XDP function it is necessary to allow
12504 * performance analysis of all functions. Both original
12505 * XDP program and its program extension. Hence
12506 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12507 * allowed. If extending of fentry/fexit was allowed it
12508 * would be possible to create long call chain
12509 * fentry->extension->fentry->extension beyond
12510 * reasonable stack size. Hence extending fentry is not
12511 * allowed.
12512 */
efc68158 12513 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
12514 return -EINVAL;
12515 }
5b92a28a 12516 } else {
be8704ff 12517 if (prog_extension) {
efc68158 12518 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
12519 return -EINVAL;
12520 }
5b92a28a 12521 }
f1b9509c
AS
12522
12523 switch (prog->expected_attach_type) {
12524 case BPF_TRACE_RAW_TP:
5b92a28a 12525 if (tgt_prog) {
efc68158 12526 bpf_log(log,
5b92a28a
AS
12527 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12528 return -EINVAL;
12529 }
38207291 12530 if (!btf_type_is_typedef(t)) {
efc68158 12531 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
12532 btf_id);
12533 return -EINVAL;
12534 }
f1b9509c 12535 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 12536 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
12537 btf_id, tname);
12538 return -EINVAL;
12539 }
12540 tname += sizeof(prefix) - 1;
5b92a28a 12541 t = btf_type_by_id(btf, t->type);
38207291
MKL
12542 if (!btf_type_is_ptr(t))
12543 /* should never happen in valid vmlinux build */
12544 return -EINVAL;
5b92a28a 12545 t = btf_type_by_id(btf, t->type);
38207291
MKL
12546 if (!btf_type_is_func_proto(t))
12547 /* should never happen in valid vmlinux build */
12548 return -EINVAL;
12549
f7b12b6f 12550 break;
15d83c4d
YS
12551 case BPF_TRACE_ITER:
12552 if (!btf_type_is_func(t)) {
efc68158 12553 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
12554 btf_id);
12555 return -EINVAL;
12556 }
12557 t = btf_type_by_id(btf, t->type);
12558 if (!btf_type_is_func_proto(t))
12559 return -EINVAL;
f7b12b6f
THJ
12560 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12561 if (ret)
12562 return ret;
12563 break;
be8704ff
AS
12564 default:
12565 if (!prog_extension)
12566 return -EINVAL;
df561f66 12567 fallthrough;
ae240823 12568 case BPF_MODIFY_RETURN:
9e4e01df 12569 case BPF_LSM_MAC:
fec56f58
AS
12570 case BPF_TRACE_FENTRY:
12571 case BPF_TRACE_FEXIT:
12572 if (!btf_type_is_func(t)) {
efc68158 12573 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
12574 btf_id);
12575 return -EINVAL;
12576 }
be8704ff 12577 if (prog_extension &&
efc68158 12578 btf_check_type_match(log, prog, btf, t))
be8704ff 12579 return -EINVAL;
5b92a28a 12580 t = btf_type_by_id(btf, t->type);
fec56f58
AS
12581 if (!btf_type_is_func_proto(t))
12582 return -EINVAL;
f7b12b6f 12583
4a1e7c0c
THJ
12584 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12585 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12586 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12587 return -EINVAL;
12588
f7b12b6f 12589 if (tgt_prog && conservative)
5b92a28a 12590 t = NULL;
f7b12b6f
THJ
12591
12592 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 12593 if (ret < 0)
f7b12b6f
THJ
12594 return ret;
12595
5b92a28a 12596 if (tgt_prog) {
e9eeec58
YS
12597 if (subprog == 0)
12598 addr = (long) tgt_prog->bpf_func;
12599 else
12600 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
12601 } else {
12602 addr = kallsyms_lookup_name(tname);
12603 if (!addr) {
efc68158 12604 bpf_log(log,
5b92a28a
AS
12605 "The address of function %s cannot be found\n",
12606 tname);
f7b12b6f 12607 return -ENOENT;
5b92a28a 12608 }
fec56f58 12609 }
18644cec 12610
1e6c62a8
AS
12611 if (prog->aux->sleepable) {
12612 ret = -EINVAL;
12613 switch (prog->type) {
12614 case BPF_PROG_TYPE_TRACING:
12615 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12616 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12617 */
12618 if (!check_non_sleepable_error_inject(btf_id) &&
12619 within_error_injection_list(addr))
12620 ret = 0;
12621 break;
12622 case BPF_PROG_TYPE_LSM:
12623 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12624 * Only some of them are sleepable.
12625 */
423f1610 12626 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
12627 ret = 0;
12628 break;
12629 default:
12630 break;
12631 }
f7b12b6f
THJ
12632 if (ret) {
12633 bpf_log(log, "%s is not sleepable\n", tname);
12634 return ret;
12635 }
1e6c62a8 12636 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 12637 if (tgt_prog) {
efc68158 12638 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
12639 return -EINVAL;
12640 }
12641 ret = check_attach_modify_return(addr, tname);
12642 if (ret) {
12643 bpf_log(log, "%s() is not modifiable\n", tname);
12644 return ret;
1af9270e 12645 }
18644cec 12646 }
f7b12b6f
THJ
12647
12648 break;
12649 }
12650 tgt_info->tgt_addr = addr;
12651 tgt_info->tgt_name = tname;
12652 tgt_info->tgt_type = t;
12653 return 0;
12654}
12655
12656static int check_attach_btf_id(struct bpf_verifier_env *env)
12657{
12658 struct bpf_prog *prog = env->prog;
3aac1ead 12659 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
12660 struct bpf_attach_target_info tgt_info = {};
12661 u32 btf_id = prog->aux->attach_btf_id;
12662 struct bpf_trampoline *tr;
12663 int ret;
12664 u64 key;
12665
12666 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12667 prog->type != BPF_PROG_TYPE_LSM) {
12668 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12669 return -EINVAL;
12670 }
12671
12672 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12673 return check_struct_ops_btf_id(env);
12674
12675 if (prog->type != BPF_PROG_TYPE_TRACING &&
12676 prog->type != BPF_PROG_TYPE_LSM &&
12677 prog->type != BPF_PROG_TYPE_EXT)
12678 return 0;
12679
12680 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12681 if (ret)
fec56f58 12682 return ret;
f7b12b6f
THJ
12683
12684 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
12685 /* to make freplace equivalent to their targets, they need to
12686 * inherit env->ops and expected_attach_type for the rest of the
12687 * verification
12688 */
f7b12b6f
THJ
12689 env->ops = bpf_verifier_ops[tgt_prog->type];
12690 prog->expected_attach_type = tgt_prog->expected_attach_type;
12691 }
12692
12693 /* store info about the attachment target that will be used later */
12694 prog->aux->attach_func_proto = tgt_info.tgt_type;
12695 prog->aux->attach_func_name = tgt_info.tgt_name;
12696
4a1e7c0c
THJ
12697 if (tgt_prog) {
12698 prog->aux->saved_dst_prog_type = tgt_prog->type;
12699 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12700 }
12701
f7b12b6f
THJ
12702 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12703 prog->aux->attach_btf_trace = true;
12704 return 0;
12705 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12706 if (!bpf_iter_prog_supported(prog))
12707 return -EINVAL;
12708 return 0;
12709 }
12710
12711 if (prog->type == BPF_PROG_TYPE_LSM) {
12712 ret = bpf_lsm_verify_prog(&env->log, prog);
12713 if (ret < 0)
12714 return ret;
38207291 12715 }
f7b12b6f 12716
22dc4a0f 12717 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
12718 tr = bpf_trampoline_get(key, &tgt_info);
12719 if (!tr)
12720 return -ENOMEM;
12721
3aac1ead 12722 prog->aux->dst_trampoline = tr;
f7b12b6f 12723 return 0;
38207291
MKL
12724}
12725
76654e67
AM
12726struct btf *bpf_get_btf_vmlinux(void)
12727{
12728 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12729 mutex_lock(&bpf_verifier_lock);
12730 if (!btf_vmlinux)
12731 btf_vmlinux = btf_parse_vmlinux();
12732 mutex_unlock(&bpf_verifier_lock);
12733 }
12734 return btf_vmlinux;
12735}
12736
838e9690
YS
12737int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12738 union bpf_attr __user *uattr)
51580e79 12739{
06ee7115 12740 u64 start_time = ktime_get_ns();
58e2af8b 12741 struct bpf_verifier_env *env;
b9193c1b 12742 struct bpf_verifier_log *log;
9e4c24e7 12743 int i, len, ret = -EINVAL;
e2ae4ca2 12744 bool is_priv;
51580e79 12745
eba0c929
AB
12746 /* no program is valid */
12747 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12748 return -EINVAL;
12749
58e2af8b 12750 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
12751 * allocate/free it every time bpf_check() is called
12752 */
58e2af8b 12753 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
12754 if (!env)
12755 return -ENOMEM;
61bd5218 12756 log = &env->log;
cbd35700 12757
9e4c24e7 12758 len = (*prog)->len;
fad953ce 12759 env->insn_aux_data =
9e4c24e7 12760 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
12761 ret = -ENOMEM;
12762 if (!env->insn_aux_data)
12763 goto err_free_env;
9e4c24e7
JK
12764 for (i = 0; i < len; i++)
12765 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 12766 env->prog = *prog;
00176a34 12767 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 12768 is_priv = bpf_capable();
0246e64d 12769
76654e67 12770 bpf_get_btf_vmlinux();
8580ac94 12771
cbd35700 12772 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
12773 if (!is_priv)
12774 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
12775
12776 if (attr->log_level || attr->log_buf || attr->log_size) {
12777 /* user requested verbose verifier output
12778 * and supplied buffer to store the verification trace
12779 */
e7bf8249
JK
12780 log->level = attr->log_level;
12781 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12782 log->len_total = attr->log_size;
cbd35700
AS
12783
12784 ret = -EINVAL;
e7bf8249 12785 /* log attributes have to be sane */
7a9f5c65 12786 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 12787 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 12788 goto err_unlock;
cbd35700 12789 }
1ad2f583 12790
8580ac94
AS
12791 if (IS_ERR(btf_vmlinux)) {
12792 /* Either gcc or pahole or kernel are broken. */
12793 verbose(env, "in-kernel BTF is malformed\n");
12794 ret = PTR_ERR(btf_vmlinux);
38207291 12795 goto skip_full_check;
8580ac94
AS
12796 }
12797
1ad2f583
DB
12798 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12799 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 12800 env->strict_alignment = true;
e9ee9efc
DM
12801 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12802 env->strict_alignment = false;
cbd35700 12803
2c78ee89 12804 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 12805 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 12806 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
12807 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12808 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12809 env->bpf_capable = bpf_capable();
e2ae4ca2 12810
10d274e8
AS
12811 if (is_priv)
12812 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12813
cae1927c 12814 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 12815 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 12816 if (ret)
f4e3ec0d 12817 goto skip_full_check;
ab3f0063
JK
12818 }
12819
dc2a4ebc 12820 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 12821 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
12822 GFP_USER);
12823 ret = -ENOMEM;
12824 if (!env->explored_states)
12825 goto skip_full_check;
12826
d9762e84 12827 ret = check_subprogs(env);
475fb78f
AS
12828 if (ret < 0)
12829 goto skip_full_check;
12830
c454a46b 12831 ret = check_btf_info(env, attr, uattr);
838e9690
YS
12832 if (ret < 0)
12833 goto skip_full_check;
12834
be8704ff
AS
12835 ret = check_attach_btf_id(env);
12836 if (ret)
12837 goto skip_full_check;
12838
4976b718
HL
12839 ret = resolve_pseudo_ldimm64(env);
12840 if (ret < 0)
12841 goto skip_full_check;
12842
d9762e84
MKL
12843 ret = check_cfg(env);
12844 if (ret < 0)
12845 goto skip_full_check;
12846
51c39bb1
AS
12847 ret = do_check_subprogs(env);
12848 ret = ret ?: do_check_main(env);
cbd35700 12849
c941ce9c
QM
12850 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12851 ret = bpf_prog_offload_finalize(env);
12852
0246e64d 12853skip_full_check:
51c39bb1 12854 kvfree(env->explored_states);
0246e64d 12855
c131187d 12856 if (ret == 0)
9b38c405 12857 ret = check_max_stack_depth(env);
c131187d 12858
9b38c405 12859 /* instruction rewrites happen after this point */
e2ae4ca2
JK
12860 if (is_priv) {
12861 if (ret == 0)
12862 opt_hard_wire_dead_code_branches(env);
52875a04
JK
12863 if (ret == 0)
12864 ret = opt_remove_dead_code(env);
a1b14abc
JK
12865 if (ret == 0)
12866 ret = opt_remove_nops(env);
52875a04
JK
12867 } else {
12868 if (ret == 0)
12869 sanitize_dead_code(env);
e2ae4ca2
JK
12870 }
12871
9bac3d6d
AS
12872 if (ret == 0)
12873 /* program is valid, convert *(u32*)(ctx + off) accesses */
12874 ret = convert_ctx_accesses(env);
12875
e245c5c6 12876 if (ret == 0)
e6ac5933 12877 ret = do_misc_fixups(env);
e245c5c6 12878
a4b1d3c1
JW
12879 /* do 32-bit optimization after insn patching has done so those patched
12880 * insns could be handled correctly.
12881 */
d6c2308c
JW
12882 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12883 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12884 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12885 : false;
a4b1d3c1
JW
12886 }
12887
1ea47e01
AS
12888 if (ret == 0)
12889 ret = fixup_call_args(env);
12890
06ee7115
AS
12891 env->verification_time = ktime_get_ns() - start_time;
12892 print_verification_stats(env);
12893
a2a7d570 12894 if (log->level && bpf_verifier_log_full(log))
cbd35700 12895 ret = -ENOSPC;
a2a7d570 12896 if (log->level && !log->ubuf) {
cbd35700 12897 ret = -EFAULT;
a2a7d570 12898 goto err_release_maps;
cbd35700
AS
12899 }
12900
541c3bad
AN
12901 if (ret)
12902 goto err_release_maps;
12903
12904 if (env->used_map_cnt) {
0246e64d 12905 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
12906 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12907 sizeof(env->used_maps[0]),
12908 GFP_KERNEL);
0246e64d 12909
9bac3d6d 12910 if (!env->prog->aux->used_maps) {
0246e64d 12911 ret = -ENOMEM;
a2a7d570 12912 goto err_release_maps;
0246e64d
AS
12913 }
12914
9bac3d6d 12915 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 12916 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 12917 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
12918 }
12919 if (env->used_btf_cnt) {
12920 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12921 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12922 sizeof(env->used_btfs[0]),
12923 GFP_KERNEL);
12924 if (!env->prog->aux->used_btfs) {
12925 ret = -ENOMEM;
12926 goto err_release_maps;
12927 }
0246e64d 12928
541c3bad
AN
12929 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12930 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12931 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12932 }
12933 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
12934 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12935 * bpf_ld_imm64 instructions
12936 */
12937 convert_pseudo_ld_imm64(env);
12938 }
cbd35700 12939
541c3bad 12940 adjust_btf_func(env);
ba64e7d8 12941
a2a7d570 12942err_release_maps:
9bac3d6d 12943 if (!env->prog->aux->used_maps)
0246e64d 12944 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 12945 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
12946 */
12947 release_maps(env);
541c3bad
AN
12948 if (!env->prog->aux->used_btfs)
12949 release_btfs(env);
03f87c0b
THJ
12950
12951 /* extension progs temporarily inherit the attach_type of their targets
12952 for verification purposes, so set it back to zero before returning
12953 */
12954 if (env->prog->type == BPF_PROG_TYPE_EXT)
12955 env->prog->expected_attach_type = 0;
12956
9bac3d6d 12957 *prog = env->prog;
3df126f3 12958err_unlock:
45a73c17
AS
12959 if (!is_priv)
12960 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
12961 vfree(env->insn_aux_data);
12962err_free_env:
12963 kfree(env);
51580e79
AS
12964 return ret;
12965}