]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - kernel/bpf/verifier.c
Merge branch 'rtt-speedup.2020.09.16a' of git://git.kernel.org/pub/scm/linux/kernel...
[mirror_ubuntu-jammy-kernel.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
33ff9823
DB
231struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
435faee1 233 bool raw_mode;
36bbef52 234 bool pkt_access;
435faee1
DB
235 int regno;
236 int access_size;
457f4436 237 int mem_size;
10060503 238 u64 msize_max_value;
1b986589 239 int ref_obj_id;
d83525ca 240 int func_id;
33ff9823
DB
241};
242
8580ac94
AS
243struct btf *btf_vmlinux;
244
cbd35700
AS
245static DEFINE_MUTEX(bpf_verifier_lock);
246
d9762e84
MKL
247static const struct bpf_line_info *
248find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
249{
250 const struct bpf_line_info *linfo;
251 const struct bpf_prog *prog;
252 u32 i, nr_linfo;
253
254 prog = env->prog;
255 nr_linfo = prog->aux->nr_linfo;
256
257 if (!nr_linfo || insn_off >= prog->len)
258 return NULL;
259
260 linfo = prog->aux->linfo;
261 for (i = 1; i < nr_linfo; i++)
262 if (insn_off < linfo[i].insn_off)
263 break;
264
265 return &linfo[i - 1];
266}
267
77d2e05a
MKL
268void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
269 va_list args)
cbd35700 270{
a2a7d570 271 unsigned int n;
cbd35700 272
a2a7d570 273 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
274
275 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
276 "verifier log line truncated - local buffer too short\n");
277
278 n = min(log->len_total - log->len_used - 1, n);
279 log->kbuf[n] = '\0';
280
8580ac94
AS
281 if (log->level == BPF_LOG_KERNEL) {
282 pr_err("BPF:%s\n", log->kbuf);
283 return;
284 }
a2a7d570
JK
285 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
286 log->len_used += n;
287 else
288 log->ubuf = NULL;
cbd35700 289}
abe08840 290
6f8a57cc
AN
291static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
292{
293 char zero = 0;
294
295 if (!bpf_verifier_log_needed(log))
296 return;
297
298 log->len_used = new_pos;
299 if (put_user(zero, log->ubuf + new_pos))
300 log->ubuf = NULL;
301}
302
abe08840
JO
303/* log_level controls verbosity level of eBPF verifier.
304 * bpf_verifier_log_write() is used to dump the verification trace to the log,
305 * so the user can figure out what's wrong with the program
430e68d1 306 */
abe08840
JO
307__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
308 const char *fmt, ...)
309{
310 va_list args;
311
77d2e05a
MKL
312 if (!bpf_verifier_log_needed(&env->log))
313 return;
314
abe08840 315 va_start(args, fmt);
77d2e05a 316 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
317 va_end(args);
318}
319EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
320
321__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
322{
77d2e05a 323 struct bpf_verifier_env *env = private_data;
abe08840
JO
324 va_list args;
325
77d2e05a
MKL
326 if (!bpf_verifier_log_needed(&env->log))
327 return;
328
abe08840 329 va_start(args, fmt);
77d2e05a 330 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
331 va_end(args);
332}
cbd35700 333
9e15db66
AS
334__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
335 const char *fmt, ...)
336{
337 va_list args;
338
339 if (!bpf_verifier_log_needed(log))
340 return;
341
342 va_start(args, fmt);
343 bpf_verifier_vlog(log, fmt, args);
344 va_end(args);
345}
346
d9762e84
MKL
347static const char *ltrim(const char *s)
348{
349 while (isspace(*s))
350 s++;
351
352 return s;
353}
354
355__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
356 u32 insn_off,
357 const char *prefix_fmt, ...)
358{
359 const struct bpf_line_info *linfo;
360
361 if (!bpf_verifier_log_needed(&env->log))
362 return;
363
364 linfo = find_linfo(env, insn_off);
365 if (!linfo || linfo == env->prev_linfo)
366 return;
367
368 if (prefix_fmt) {
369 va_list args;
370
371 va_start(args, prefix_fmt);
372 bpf_verifier_vlog(&env->log, prefix_fmt, args);
373 va_end(args);
374 }
375
376 verbose(env, "%s\n",
377 ltrim(btf_name_by_offset(env->prog->aux->btf,
378 linfo->line_off)));
379
380 env->prev_linfo = linfo;
381}
382
de8f3a83
DB
383static bool type_is_pkt_pointer(enum bpf_reg_type type)
384{
385 return type == PTR_TO_PACKET ||
386 type == PTR_TO_PACKET_META;
387}
388
46f8bc92
MKL
389static bool type_is_sk_pointer(enum bpf_reg_type type)
390{
391 return type == PTR_TO_SOCKET ||
655a51e5 392 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
393 type == PTR_TO_TCP_SOCK ||
394 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
395}
396
cac616db
JF
397static bool reg_type_not_null(enum bpf_reg_type type)
398{
399 return type == PTR_TO_SOCKET ||
400 type == PTR_TO_TCP_SOCK ||
401 type == PTR_TO_MAP_VALUE ||
01c66c48 402 type == PTR_TO_SOCK_COMMON;
cac616db
JF
403}
404
840b9615
JS
405static bool reg_type_may_be_null(enum bpf_reg_type type)
406{
fd978bf7 407 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 408 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 409 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 410 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 411 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
412 type == PTR_TO_MEM_OR_NULL ||
413 type == PTR_TO_RDONLY_BUF_OR_NULL ||
414 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
415}
416
d83525ca
AS
417static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
418{
419 return reg->type == PTR_TO_MAP_VALUE &&
420 map_value_has_spin_lock(reg->map_ptr);
421}
422
cba368c1
MKL
423static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
424{
425 return type == PTR_TO_SOCKET ||
426 type == PTR_TO_SOCKET_OR_NULL ||
427 type == PTR_TO_TCP_SOCK ||
457f4436
AN
428 type == PTR_TO_TCP_SOCK_OR_NULL ||
429 type == PTR_TO_MEM ||
430 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
431}
432
1b986589 433static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 434{
1b986589 435 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
436}
437
fd1b0d60
LB
438static bool arg_type_may_be_null(enum bpf_arg_type type)
439{
440 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
441 type == ARG_PTR_TO_MEM_OR_NULL ||
442 type == ARG_PTR_TO_CTX_OR_NULL ||
443 type == ARG_PTR_TO_SOCKET_OR_NULL ||
444 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
445}
446
fd978bf7
JS
447/* Determine whether the function releases some resources allocated by another
448 * function call. The first reference type argument will be assumed to be
449 * released by release_reference().
450 */
451static bool is_release_function(enum bpf_func_id func_id)
452{
457f4436
AN
453 return func_id == BPF_FUNC_sk_release ||
454 func_id == BPF_FUNC_ringbuf_submit ||
455 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
456}
457
64d85290 458static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
459{
460 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 461 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 462 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
463 func_id == BPF_FUNC_map_lookup_elem ||
464 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
465}
466
467static bool is_acquire_function(enum bpf_func_id func_id,
468 const struct bpf_map *map)
469{
470 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
471
472 if (func_id == BPF_FUNC_sk_lookup_tcp ||
473 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
474 func_id == BPF_FUNC_skc_lookup_tcp ||
475 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
476 return true;
477
478 if (func_id == BPF_FUNC_map_lookup_elem &&
479 (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 map_type == BPF_MAP_TYPE_SOCKHASH))
481 return true;
482
483 return false;
46f8bc92
MKL
484}
485
1b986589
MKL
486static bool is_ptr_cast_function(enum bpf_func_id func_id)
487{
488 return func_id == BPF_FUNC_tcp_sock ||
489 func_id == BPF_FUNC_sk_fullsock;
490}
491
17a52670
AS
492/* string representation of 'enum bpf_reg_type' */
493static const char * const reg_type_str[] = {
494 [NOT_INIT] = "?",
f1174f77 495 [SCALAR_VALUE] = "inv",
17a52670
AS
496 [PTR_TO_CTX] = "ctx",
497 [CONST_PTR_TO_MAP] = "map_ptr",
498 [PTR_TO_MAP_VALUE] = "map_value",
499 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 500 [PTR_TO_STACK] = "fp",
969bf05e 501 [PTR_TO_PACKET] = "pkt",
de8f3a83 502 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 503 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 504 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
505 [PTR_TO_SOCKET] = "sock",
506 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
507 [PTR_TO_SOCK_COMMON] = "sock_common",
508 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
509 [PTR_TO_TCP_SOCK] = "tcp_sock",
510 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 511 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 512 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 513 [PTR_TO_BTF_ID] = "ptr_",
b121b341 514 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
457f4436
AN
515 [PTR_TO_MEM] = "mem",
516 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
517 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
518 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
519 [PTR_TO_RDWR_BUF] = "rdwr_buf",
520 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
17a52670
AS
521};
522
8efea21d
EC
523static char slot_type_char[] = {
524 [STACK_INVALID] = '?',
525 [STACK_SPILL] = 'r',
526 [STACK_MISC] = 'm',
527 [STACK_ZERO] = '0',
528};
529
4e92024a
AS
530static void print_liveness(struct bpf_verifier_env *env,
531 enum bpf_reg_liveness live)
532{
9242b5f5 533 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
534 verbose(env, "_");
535 if (live & REG_LIVE_READ)
536 verbose(env, "r");
537 if (live & REG_LIVE_WRITTEN)
538 verbose(env, "w");
9242b5f5
AS
539 if (live & REG_LIVE_DONE)
540 verbose(env, "D");
4e92024a
AS
541}
542
f4d7e40a
AS
543static struct bpf_func_state *func(struct bpf_verifier_env *env,
544 const struct bpf_reg_state *reg)
545{
546 struct bpf_verifier_state *cur = env->cur_state;
547
548 return cur->frame[reg->frameno];
549}
550
9e15db66
AS
551const char *kernel_type_name(u32 id)
552{
553 return btf_name_by_offset(btf_vmlinux,
554 btf_type_by_id(btf_vmlinux, id)->name_off);
555}
556
61bd5218 557static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 558 const struct bpf_func_state *state)
17a52670 559{
f4d7e40a 560 const struct bpf_reg_state *reg;
17a52670
AS
561 enum bpf_reg_type t;
562 int i;
563
f4d7e40a
AS
564 if (state->frameno)
565 verbose(env, " frame%d:", state->frameno);
17a52670 566 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
567 reg = &state->regs[i];
568 t = reg->type;
17a52670
AS
569 if (t == NOT_INIT)
570 continue;
4e92024a
AS
571 verbose(env, " R%d", i);
572 print_liveness(env, reg->live);
573 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
574 if (t == SCALAR_VALUE && reg->precise)
575 verbose(env, "P");
f1174f77
EC
576 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
577 tnum_is_const(reg->var_off)) {
578 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 579 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 580 } else {
b121b341 581 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
9e15db66 582 verbose(env, "%s", kernel_type_name(reg->btf_id));
cba368c1
MKL
583 verbose(env, "(id=%d", reg->id);
584 if (reg_type_may_be_refcounted_or_null(t))
585 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 586 if (t != SCALAR_VALUE)
61bd5218 587 verbose(env, ",off=%d", reg->off);
de8f3a83 588 if (type_is_pkt_pointer(t))
61bd5218 589 verbose(env, ",r=%d", reg->range);
f1174f77
EC
590 else if (t == CONST_PTR_TO_MAP ||
591 t == PTR_TO_MAP_VALUE ||
592 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 593 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
594 reg->map_ptr->key_size,
595 reg->map_ptr->value_size);
7d1238f2
EC
596 if (tnum_is_const(reg->var_off)) {
597 /* Typically an immediate SCALAR_VALUE, but
598 * could be a pointer whose offset is too big
599 * for reg->off
600 */
61bd5218 601 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
602 } else {
603 if (reg->smin_value != reg->umin_value &&
604 reg->smin_value != S64_MIN)
61bd5218 605 verbose(env, ",smin_value=%lld",
7d1238f2
EC
606 (long long)reg->smin_value);
607 if (reg->smax_value != reg->umax_value &&
608 reg->smax_value != S64_MAX)
61bd5218 609 verbose(env, ",smax_value=%lld",
7d1238f2
EC
610 (long long)reg->smax_value);
611 if (reg->umin_value != 0)
61bd5218 612 verbose(env, ",umin_value=%llu",
7d1238f2
EC
613 (unsigned long long)reg->umin_value);
614 if (reg->umax_value != U64_MAX)
61bd5218 615 verbose(env, ",umax_value=%llu",
7d1238f2
EC
616 (unsigned long long)reg->umax_value);
617 if (!tnum_is_unknown(reg->var_off)) {
618 char tn_buf[48];
f1174f77 619
7d1238f2 620 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 621 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 622 }
3f50f132
JF
623 if (reg->s32_min_value != reg->smin_value &&
624 reg->s32_min_value != S32_MIN)
625 verbose(env, ",s32_min_value=%d",
626 (int)(reg->s32_min_value));
627 if (reg->s32_max_value != reg->smax_value &&
628 reg->s32_max_value != S32_MAX)
629 verbose(env, ",s32_max_value=%d",
630 (int)(reg->s32_max_value));
631 if (reg->u32_min_value != reg->umin_value &&
632 reg->u32_min_value != U32_MIN)
633 verbose(env, ",u32_min_value=%d",
634 (int)(reg->u32_min_value));
635 if (reg->u32_max_value != reg->umax_value &&
636 reg->u32_max_value != U32_MAX)
637 verbose(env, ",u32_max_value=%d",
638 (int)(reg->u32_max_value));
f1174f77 639 }
61bd5218 640 verbose(env, ")");
f1174f77 641 }
17a52670 642 }
638f5b90 643 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
644 char types_buf[BPF_REG_SIZE + 1];
645 bool valid = false;
646 int j;
647
648 for (j = 0; j < BPF_REG_SIZE; j++) {
649 if (state->stack[i].slot_type[j] != STACK_INVALID)
650 valid = true;
651 types_buf[j] = slot_type_char[
652 state->stack[i].slot_type[j]];
653 }
654 types_buf[BPF_REG_SIZE] = 0;
655 if (!valid)
656 continue;
657 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
658 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
659 if (state->stack[i].slot_type[0] == STACK_SPILL) {
660 reg = &state->stack[i].spilled_ptr;
661 t = reg->type;
662 verbose(env, "=%s", reg_type_str[t]);
663 if (t == SCALAR_VALUE && reg->precise)
664 verbose(env, "P");
665 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
666 verbose(env, "%lld", reg->var_off.value + reg->off);
667 } else {
8efea21d 668 verbose(env, "=%s", types_buf);
b5dc0163 669 }
17a52670 670 }
fd978bf7
JS
671 if (state->acquired_refs && state->refs[0].id) {
672 verbose(env, " refs=%d", state->refs[0].id);
673 for (i = 1; i < state->acquired_refs; i++)
674 if (state->refs[i].id)
675 verbose(env, ",%d", state->refs[i].id);
676 }
61bd5218 677 verbose(env, "\n");
17a52670
AS
678}
679
84dbf350
JS
680#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
681static int copy_##NAME##_state(struct bpf_func_state *dst, \
682 const struct bpf_func_state *src) \
683{ \
684 if (!src->FIELD) \
685 return 0; \
686 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
687 /* internal bug, make state invalid to reject the program */ \
688 memset(dst, 0, sizeof(*dst)); \
689 return -EFAULT; \
690 } \
691 memcpy(dst->FIELD, src->FIELD, \
692 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
693 return 0; \
638f5b90 694}
fd978bf7
JS
695/* copy_reference_state() */
696COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
697/* copy_stack_state() */
698COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
699#undef COPY_STATE_FN
700
701#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
702static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
703 bool copy_old) \
704{ \
705 u32 old_size = state->COUNT; \
706 struct bpf_##NAME##_state *new_##FIELD; \
707 int slot = size / SIZE; \
708 \
709 if (size <= old_size || !size) { \
710 if (copy_old) \
711 return 0; \
712 state->COUNT = slot * SIZE; \
713 if (!size && old_size) { \
714 kfree(state->FIELD); \
715 state->FIELD = NULL; \
716 } \
717 return 0; \
718 } \
719 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
720 GFP_KERNEL); \
721 if (!new_##FIELD) \
722 return -ENOMEM; \
723 if (copy_old) { \
724 if (state->FIELD) \
725 memcpy(new_##FIELD, state->FIELD, \
726 sizeof(*new_##FIELD) * (old_size / SIZE)); \
727 memset(new_##FIELD + old_size / SIZE, 0, \
728 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
729 } \
730 state->COUNT = slot * SIZE; \
731 kfree(state->FIELD); \
732 state->FIELD = new_##FIELD; \
733 return 0; \
734}
fd978bf7
JS
735/* realloc_reference_state() */
736REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
737/* realloc_stack_state() */
738REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
739#undef REALLOC_STATE_FN
638f5b90
AS
740
741/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
742 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 743 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
744 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
745 * which realloc_stack_state() copies over. It points to previous
746 * bpf_verifier_state which is never reallocated.
638f5b90 747 */
fd978bf7
JS
748static int realloc_func_state(struct bpf_func_state *state, int stack_size,
749 int refs_size, bool copy_old)
638f5b90 750{
fd978bf7
JS
751 int err = realloc_reference_state(state, refs_size, copy_old);
752 if (err)
753 return err;
754 return realloc_stack_state(state, stack_size, copy_old);
755}
756
757/* Acquire a pointer id from the env and update the state->refs to include
758 * this new pointer reference.
759 * On success, returns a valid pointer id to associate with the register
760 * On failure, returns a negative errno.
638f5b90 761 */
fd978bf7 762static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 763{
fd978bf7
JS
764 struct bpf_func_state *state = cur_func(env);
765 int new_ofs = state->acquired_refs;
766 int id, err;
767
768 err = realloc_reference_state(state, state->acquired_refs + 1, true);
769 if (err)
770 return err;
771 id = ++env->id_gen;
772 state->refs[new_ofs].id = id;
773 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 774
fd978bf7
JS
775 return id;
776}
777
778/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 779static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
780{
781 int i, last_idx;
782
fd978bf7
JS
783 last_idx = state->acquired_refs - 1;
784 for (i = 0; i < state->acquired_refs; i++) {
785 if (state->refs[i].id == ptr_id) {
786 if (last_idx && i != last_idx)
787 memcpy(&state->refs[i], &state->refs[last_idx],
788 sizeof(*state->refs));
789 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
790 state->acquired_refs--;
638f5b90 791 return 0;
638f5b90 792 }
638f5b90 793 }
46f8bc92 794 return -EINVAL;
fd978bf7
JS
795}
796
797static int transfer_reference_state(struct bpf_func_state *dst,
798 struct bpf_func_state *src)
799{
800 int err = realloc_reference_state(dst, src->acquired_refs, false);
801 if (err)
802 return err;
803 err = copy_reference_state(dst, src);
804 if (err)
805 return err;
638f5b90
AS
806 return 0;
807}
808
f4d7e40a
AS
809static void free_func_state(struct bpf_func_state *state)
810{
5896351e
AS
811 if (!state)
812 return;
fd978bf7 813 kfree(state->refs);
f4d7e40a
AS
814 kfree(state->stack);
815 kfree(state);
816}
817
b5dc0163
AS
818static void clear_jmp_history(struct bpf_verifier_state *state)
819{
820 kfree(state->jmp_history);
821 state->jmp_history = NULL;
822 state->jmp_history_cnt = 0;
823}
824
1969db47
AS
825static void free_verifier_state(struct bpf_verifier_state *state,
826 bool free_self)
638f5b90 827{
f4d7e40a
AS
828 int i;
829
830 for (i = 0; i <= state->curframe; i++) {
831 free_func_state(state->frame[i]);
832 state->frame[i] = NULL;
833 }
b5dc0163 834 clear_jmp_history(state);
1969db47
AS
835 if (free_self)
836 kfree(state);
638f5b90
AS
837}
838
839/* copy verifier state from src to dst growing dst stack space
840 * when necessary to accommodate larger src stack
841 */
f4d7e40a
AS
842static int copy_func_state(struct bpf_func_state *dst,
843 const struct bpf_func_state *src)
638f5b90
AS
844{
845 int err;
846
fd978bf7
JS
847 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
848 false);
849 if (err)
850 return err;
851 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
852 err = copy_reference_state(dst, src);
638f5b90
AS
853 if (err)
854 return err;
638f5b90
AS
855 return copy_stack_state(dst, src);
856}
857
f4d7e40a
AS
858static int copy_verifier_state(struct bpf_verifier_state *dst_state,
859 const struct bpf_verifier_state *src)
860{
861 struct bpf_func_state *dst;
b5dc0163 862 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
863 int i, err;
864
b5dc0163
AS
865 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
866 kfree(dst_state->jmp_history);
867 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
868 if (!dst_state->jmp_history)
869 return -ENOMEM;
870 }
871 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
872 dst_state->jmp_history_cnt = src->jmp_history_cnt;
873
f4d7e40a
AS
874 /* if dst has more stack frames then src frame, free them */
875 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
876 free_func_state(dst_state->frame[i]);
877 dst_state->frame[i] = NULL;
878 }
979d63d5 879 dst_state->speculative = src->speculative;
f4d7e40a 880 dst_state->curframe = src->curframe;
d83525ca 881 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
882 dst_state->branches = src->branches;
883 dst_state->parent = src->parent;
b5dc0163
AS
884 dst_state->first_insn_idx = src->first_insn_idx;
885 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
886 for (i = 0; i <= src->curframe; i++) {
887 dst = dst_state->frame[i];
888 if (!dst) {
889 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
890 if (!dst)
891 return -ENOMEM;
892 dst_state->frame[i] = dst;
893 }
894 err = copy_func_state(dst, src->frame[i]);
895 if (err)
896 return err;
897 }
898 return 0;
899}
900
2589726d
AS
901static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
902{
903 while (st) {
904 u32 br = --st->branches;
905
906 /* WARN_ON(br > 1) technically makes sense here,
907 * but see comment in push_stack(), hence:
908 */
909 WARN_ONCE((int)br < 0,
910 "BUG update_branch_counts:branches_to_explore=%d\n",
911 br);
912 if (br)
913 break;
914 st = st->parent;
915 }
916}
917
638f5b90 918static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 919 int *insn_idx, bool pop_log)
638f5b90
AS
920{
921 struct bpf_verifier_state *cur = env->cur_state;
922 struct bpf_verifier_stack_elem *elem, *head = env->head;
923 int err;
17a52670
AS
924
925 if (env->head == NULL)
638f5b90 926 return -ENOENT;
17a52670 927
638f5b90
AS
928 if (cur) {
929 err = copy_verifier_state(cur, &head->st);
930 if (err)
931 return err;
932 }
6f8a57cc
AN
933 if (pop_log)
934 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
935 if (insn_idx)
936 *insn_idx = head->insn_idx;
17a52670 937 if (prev_insn_idx)
638f5b90
AS
938 *prev_insn_idx = head->prev_insn_idx;
939 elem = head->next;
1969db47 940 free_verifier_state(&head->st, false);
638f5b90 941 kfree(head);
17a52670
AS
942 env->head = elem;
943 env->stack_size--;
638f5b90 944 return 0;
17a52670
AS
945}
946
58e2af8b 947static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
948 int insn_idx, int prev_insn_idx,
949 bool speculative)
17a52670 950{
638f5b90 951 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 952 struct bpf_verifier_stack_elem *elem;
638f5b90 953 int err;
17a52670 954
638f5b90 955 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
956 if (!elem)
957 goto err;
958
17a52670
AS
959 elem->insn_idx = insn_idx;
960 elem->prev_insn_idx = prev_insn_idx;
961 elem->next = env->head;
6f8a57cc 962 elem->log_pos = env->log.len_used;
17a52670
AS
963 env->head = elem;
964 env->stack_size++;
1969db47
AS
965 err = copy_verifier_state(&elem->st, cur);
966 if (err)
967 goto err;
979d63d5 968 elem->st.speculative |= speculative;
b285fcb7
AS
969 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
970 verbose(env, "The sequence of %d jumps is too complex.\n",
971 env->stack_size);
17a52670
AS
972 goto err;
973 }
2589726d
AS
974 if (elem->st.parent) {
975 ++elem->st.parent->branches;
976 /* WARN_ON(branches > 2) technically makes sense here,
977 * but
978 * 1. speculative states will bump 'branches' for non-branch
979 * instructions
980 * 2. is_state_visited() heuristics may decide not to create
981 * a new state for a sequence of branches and all such current
982 * and cloned states will be pointing to a single parent state
983 * which might have large 'branches' count.
984 */
985 }
17a52670
AS
986 return &elem->st;
987err:
5896351e
AS
988 free_verifier_state(env->cur_state, true);
989 env->cur_state = NULL;
17a52670 990 /* pop all elements and return */
6f8a57cc 991 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
992 return NULL;
993}
994
995#define CALLER_SAVED_REGS 6
996static const int caller_saved[CALLER_SAVED_REGS] = {
997 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
998};
999
f54c7898
DB
1000static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1001 struct bpf_reg_state *reg);
f1174f77 1002
b03c9f9f
EC
1003/* Mark the unknown part of a register (variable offset or scalar value) as
1004 * known to have the value @imm.
1005 */
1006static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1007{
a9c676bc
AS
1008 /* Clear id, off, and union(map_ptr, range) */
1009 memset(((u8 *)reg) + sizeof(reg->type), 0,
1010 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
b03c9f9f
EC
1011 reg->var_off = tnum_const(imm);
1012 reg->smin_value = (s64)imm;
1013 reg->smax_value = (s64)imm;
1014 reg->umin_value = imm;
1015 reg->umax_value = imm;
3f50f132
JF
1016
1017 reg->s32_min_value = (s32)imm;
1018 reg->s32_max_value = (s32)imm;
1019 reg->u32_min_value = (u32)imm;
1020 reg->u32_max_value = (u32)imm;
1021}
1022
1023static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1024{
1025 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1026 reg->s32_min_value = (s32)imm;
1027 reg->s32_max_value = (s32)imm;
1028 reg->u32_min_value = (u32)imm;
1029 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1030}
1031
f1174f77
EC
1032/* Mark the 'variable offset' part of a register as zero. This should be
1033 * used only on registers holding a pointer type.
1034 */
1035static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1036{
b03c9f9f 1037 __mark_reg_known(reg, 0);
f1174f77 1038}
a9789ef9 1039
cc2b14d5
AS
1040static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1041{
1042 __mark_reg_known(reg, 0);
cc2b14d5
AS
1043 reg->type = SCALAR_VALUE;
1044}
1045
61bd5218
JK
1046static void mark_reg_known_zero(struct bpf_verifier_env *env,
1047 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1048{
1049 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1050 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1051 /* Something bad happened, let's kill all regs */
1052 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1053 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1054 return;
1055 }
1056 __mark_reg_known_zero(regs + regno);
1057}
1058
de8f3a83
DB
1059static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1060{
1061 return type_is_pkt_pointer(reg->type);
1062}
1063
1064static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1065{
1066 return reg_is_pkt_pointer(reg) ||
1067 reg->type == PTR_TO_PACKET_END;
1068}
1069
1070/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1071static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1072 enum bpf_reg_type which)
1073{
1074 /* The register can already have a range from prior markings.
1075 * This is fine as long as it hasn't been advanced from its
1076 * origin.
1077 */
1078 return reg->type == which &&
1079 reg->id == 0 &&
1080 reg->off == 0 &&
1081 tnum_equals_const(reg->var_off, 0);
1082}
1083
3f50f132
JF
1084/* Reset the min/max bounds of a register */
1085static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1086{
1087 reg->smin_value = S64_MIN;
1088 reg->smax_value = S64_MAX;
1089 reg->umin_value = 0;
1090 reg->umax_value = U64_MAX;
1091
1092 reg->s32_min_value = S32_MIN;
1093 reg->s32_max_value = S32_MAX;
1094 reg->u32_min_value = 0;
1095 reg->u32_max_value = U32_MAX;
1096}
1097
1098static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1099{
1100 reg->smin_value = S64_MIN;
1101 reg->smax_value = S64_MAX;
1102 reg->umin_value = 0;
1103 reg->umax_value = U64_MAX;
1104}
1105
1106static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1107{
1108 reg->s32_min_value = S32_MIN;
1109 reg->s32_max_value = S32_MAX;
1110 reg->u32_min_value = 0;
1111 reg->u32_max_value = U32_MAX;
1112}
1113
1114static void __update_reg32_bounds(struct bpf_reg_state *reg)
1115{
1116 struct tnum var32_off = tnum_subreg(reg->var_off);
1117
1118 /* min signed is max(sign bit) | min(other bits) */
1119 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1120 var32_off.value | (var32_off.mask & S32_MIN));
1121 /* max signed is min(sign bit) | max(other bits) */
1122 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1123 var32_off.value | (var32_off.mask & S32_MAX));
1124 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1125 reg->u32_max_value = min(reg->u32_max_value,
1126 (u32)(var32_off.value | var32_off.mask));
1127}
1128
1129static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1130{
1131 /* min signed is max(sign bit) | min(other bits) */
1132 reg->smin_value = max_t(s64, reg->smin_value,
1133 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1134 /* max signed is min(sign bit) | max(other bits) */
1135 reg->smax_value = min_t(s64, reg->smax_value,
1136 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1137 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1138 reg->umax_value = min(reg->umax_value,
1139 reg->var_off.value | reg->var_off.mask);
1140}
1141
3f50f132
JF
1142static void __update_reg_bounds(struct bpf_reg_state *reg)
1143{
1144 __update_reg32_bounds(reg);
1145 __update_reg64_bounds(reg);
1146}
1147
b03c9f9f 1148/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1149static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1150{
1151 /* Learn sign from signed bounds.
1152 * If we cannot cross the sign boundary, then signed and unsigned bounds
1153 * are the same, so combine. This works even in the negative case, e.g.
1154 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1155 */
1156 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1157 reg->s32_min_value = reg->u32_min_value =
1158 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1159 reg->s32_max_value = reg->u32_max_value =
1160 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1161 return;
1162 }
1163 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1164 * boundary, so we must be careful.
1165 */
1166 if ((s32)reg->u32_max_value >= 0) {
1167 /* Positive. We can't learn anything from the smin, but smax
1168 * is positive, hence safe.
1169 */
1170 reg->s32_min_value = reg->u32_min_value;
1171 reg->s32_max_value = reg->u32_max_value =
1172 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1173 } else if ((s32)reg->u32_min_value < 0) {
1174 /* Negative. We can't learn anything from the smax, but smin
1175 * is negative, hence safe.
1176 */
1177 reg->s32_min_value = reg->u32_min_value =
1178 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1179 reg->s32_max_value = reg->u32_max_value;
1180 }
1181}
1182
1183static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1184{
1185 /* Learn sign from signed bounds.
1186 * If we cannot cross the sign boundary, then signed and unsigned bounds
1187 * are the same, so combine. This works even in the negative case, e.g.
1188 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1189 */
1190 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1191 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1192 reg->umin_value);
1193 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1194 reg->umax_value);
1195 return;
1196 }
1197 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1198 * boundary, so we must be careful.
1199 */
1200 if ((s64)reg->umax_value >= 0) {
1201 /* Positive. We can't learn anything from the smin, but smax
1202 * is positive, hence safe.
1203 */
1204 reg->smin_value = reg->umin_value;
1205 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1206 reg->umax_value);
1207 } else if ((s64)reg->umin_value < 0) {
1208 /* Negative. We can't learn anything from the smax, but smin
1209 * is negative, hence safe.
1210 */
1211 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1212 reg->umin_value);
1213 reg->smax_value = reg->umax_value;
1214 }
1215}
1216
3f50f132
JF
1217static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1218{
1219 __reg32_deduce_bounds(reg);
1220 __reg64_deduce_bounds(reg);
1221}
1222
b03c9f9f
EC
1223/* Attempts to improve var_off based on unsigned min/max information */
1224static void __reg_bound_offset(struct bpf_reg_state *reg)
1225{
3f50f132
JF
1226 struct tnum var64_off = tnum_intersect(reg->var_off,
1227 tnum_range(reg->umin_value,
1228 reg->umax_value));
1229 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1230 tnum_range(reg->u32_min_value,
1231 reg->u32_max_value));
1232
1233 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1234}
1235
3f50f132 1236static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1237{
3f50f132
JF
1238 reg->umin_value = reg->u32_min_value;
1239 reg->umax_value = reg->u32_max_value;
1240 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1241 * but must be positive otherwise set to worse case bounds
1242 * and refine later from tnum.
1243 */
3a71dc36 1244 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1245 reg->smax_value = reg->s32_max_value;
1246 else
1247 reg->smax_value = U32_MAX;
3a71dc36
JF
1248 if (reg->s32_min_value >= 0)
1249 reg->smin_value = reg->s32_min_value;
1250 else
1251 reg->smin_value = 0;
3f50f132
JF
1252}
1253
1254static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1255{
1256 /* special case when 64-bit register has upper 32-bit register
1257 * zeroed. Typically happens after zext or <<32, >>32 sequence
1258 * allowing us to use 32-bit bounds directly,
1259 */
1260 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1261 __reg_assign_32_into_64(reg);
1262 } else {
1263 /* Otherwise the best we can do is push lower 32bit known and
1264 * unknown bits into register (var_off set from jmp logic)
1265 * then learn as much as possible from the 64-bit tnum
1266 * known and unknown bits. The previous smin/smax bounds are
1267 * invalid here because of jmp32 compare so mark them unknown
1268 * so they do not impact tnum bounds calculation.
1269 */
1270 __mark_reg64_unbounded(reg);
1271 __update_reg_bounds(reg);
1272 }
1273
1274 /* Intersecting with the old var_off might have improved our bounds
1275 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1276 * then new var_off is (0; 0x7f...fc) which improves our umax.
1277 */
1278 __reg_deduce_bounds(reg);
1279 __reg_bound_offset(reg);
1280 __update_reg_bounds(reg);
1281}
1282
1283static bool __reg64_bound_s32(s64 a)
1284{
1285 if (a > S32_MIN && a < S32_MAX)
1286 return true;
1287 return false;
1288}
1289
1290static bool __reg64_bound_u32(u64 a)
1291{
1292 if (a > U32_MIN && a < U32_MAX)
1293 return true;
1294 return false;
1295}
1296
1297static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1298{
1299 __mark_reg32_unbounded(reg);
1300
1301 if (__reg64_bound_s32(reg->smin_value))
1302 reg->s32_min_value = (s32)reg->smin_value;
1303 if (__reg64_bound_s32(reg->smax_value))
1304 reg->s32_max_value = (s32)reg->smax_value;
1305 if (__reg64_bound_u32(reg->umin_value))
1306 reg->u32_min_value = (u32)reg->umin_value;
1307 if (__reg64_bound_u32(reg->umax_value))
1308 reg->u32_max_value = (u32)reg->umax_value;
1309
1310 /* Intersecting with the old var_off might have improved our bounds
1311 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1312 * then new var_off is (0; 0x7f...fc) which improves our umax.
1313 */
1314 __reg_deduce_bounds(reg);
1315 __reg_bound_offset(reg);
1316 __update_reg_bounds(reg);
b03c9f9f
EC
1317}
1318
f1174f77 1319/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1320static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1321 struct bpf_reg_state *reg)
f1174f77 1322{
a9c676bc
AS
1323 /*
1324 * Clear type, id, off, and union(map_ptr, range) and
1325 * padding between 'type' and union
1326 */
1327 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1328 reg->type = SCALAR_VALUE;
f1174f77 1329 reg->var_off = tnum_unknown;
f4d7e40a 1330 reg->frameno = 0;
2c78ee89 1331 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1332 __mark_reg_unbounded(reg);
f1174f77
EC
1333}
1334
61bd5218
JK
1335static void mark_reg_unknown(struct bpf_verifier_env *env,
1336 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1337{
1338 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1339 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1340 /* Something bad happened, let's kill all regs except FP */
1341 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1342 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1343 return;
1344 }
f54c7898 1345 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1346}
1347
f54c7898
DB
1348static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1349 struct bpf_reg_state *reg)
f1174f77 1350{
f54c7898 1351 __mark_reg_unknown(env, reg);
f1174f77
EC
1352 reg->type = NOT_INIT;
1353}
1354
61bd5218
JK
1355static void mark_reg_not_init(struct bpf_verifier_env *env,
1356 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1357{
1358 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1359 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1360 /* Something bad happened, let's kill all regs except FP */
1361 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1362 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1363 return;
1364 }
f54c7898 1365 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1366}
1367
41c48f3a
AI
1368static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1369 struct bpf_reg_state *regs, u32 regno,
1370 enum bpf_reg_type reg_type, u32 btf_id)
1371{
1372 if (reg_type == SCALAR_VALUE) {
1373 mark_reg_unknown(env, regs, regno);
1374 return;
1375 }
1376 mark_reg_known_zero(env, regs, regno);
1377 regs[regno].type = PTR_TO_BTF_ID;
1378 regs[regno].btf_id = btf_id;
1379}
1380
5327ed3d 1381#define DEF_NOT_SUBREG (0)
61bd5218 1382static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1383 struct bpf_func_state *state)
17a52670 1384{
f4d7e40a 1385 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1386 int i;
1387
dc503a8a 1388 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1389 mark_reg_not_init(env, regs, i);
dc503a8a 1390 regs[i].live = REG_LIVE_NONE;
679c782d 1391 regs[i].parent = NULL;
5327ed3d 1392 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1393 }
17a52670
AS
1394
1395 /* frame pointer */
f1174f77 1396 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1397 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1398 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1399}
1400
f4d7e40a
AS
1401#define BPF_MAIN_FUNC (-1)
1402static void init_func_state(struct bpf_verifier_env *env,
1403 struct bpf_func_state *state,
1404 int callsite, int frameno, int subprogno)
1405{
1406 state->callsite = callsite;
1407 state->frameno = frameno;
1408 state->subprogno = subprogno;
1409 init_reg_state(env, state);
1410}
1411
17a52670
AS
1412enum reg_arg_type {
1413 SRC_OP, /* register is used as source operand */
1414 DST_OP, /* register is used as destination operand */
1415 DST_OP_NO_MARK /* same as above, check only, don't mark */
1416};
1417
cc8b0b92
AS
1418static int cmp_subprogs(const void *a, const void *b)
1419{
9c8105bd
JW
1420 return ((struct bpf_subprog_info *)a)->start -
1421 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1422}
1423
1424static int find_subprog(struct bpf_verifier_env *env, int off)
1425{
9c8105bd 1426 struct bpf_subprog_info *p;
cc8b0b92 1427
9c8105bd
JW
1428 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1429 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1430 if (!p)
1431 return -ENOENT;
9c8105bd 1432 return p - env->subprog_info;
cc8b0b92
AS
1433
1434}
1435
1436static int add_subprog(struct bpf_verifier_env *env, int off)
1437{
1438 int insn_cnt = env->prog->len;
1439 int ret;
1440
1441 if (off >= insn_cnt || off < 0) {
1442 verbose(env, "call to invalid destination\n");
1443 return -EINVAL;
1444 }
1445 ret = find_subprog(env, off);
1446 if (ret >= 0)
1447 return 0;
4cb3d99c 1448 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1449 verbose(env, "too many subprograms\n");
1450 return -E2BIG;
1451 }
9c8105bd
JW
1452 env->subprog_info[env->subprog_cnt++].start = off;
1453 sort(env->subprog_info, env->subprog_cnt,
1454 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
cc8b0b92
AS
1455 return 0;
1456}
1457
1458static int check_subprogs(struct bpf_verifier_env *env)
1459{
1460 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1461 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1462 struct bpf_insn *insn = env->prog->insnsi;
1463 int insn_cnt = env->prog->len;
1464
f910cefa
JW
1465 /* Add entry function. */
1466 ret = add_subprog(env, 0);
1467 if (ret < 0)
1468 return ret;
1469
cc8b0b92
AS
1470 /* determine subprog starts. The end is one before the next starts */
1471 for (i = 0; i < insn_cnt; i++) {
1472 if (insn[i].code != (BPF_JMP | BPF_CALL))
1473 continue;
1474 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1475 continue;
2c78ee89
AS
1476 if (!env->bpf_capable) {
1477 verbose(env,
1478 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1479 return -EPERM;
1480 }
cc8b0b92
AS
1481 ret = add_subprog(env, i + insn[i].imm + 1);
1482 if (ret < 0)
1483 return ret;
1484 }
1485
4cb3d99c
JW
1486 /* Add a fake 'exit' subprog which could simplify subprog iteration
1487 * logic. 'subprog_cnt' should not be increased.
1488 */
1489 subprog[env->subprog_cnt].start = insn_cnt;
1490
06ee7115 1491 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1492 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1493 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1494
1495 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1496 subprog_start = subprog[cur_subprog].start;
1497 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1498 for (i = 0; i < insn_cnt; i++) {
1499 u8 code = insn[i].code;
1500
7f6e4312
MF
1501 if (code == (BPF_JMP | BPF_CALL) &&
1502 insn[i].imm == BPF_FUNC_tail_call &&
1503 insn[i].src_reg != BPF_PSEUDO_CALL)
1504 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1505 if (BPF_CLASS(code) == BPF_LD &&
1506 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1507 subprog[cur_subprog].has_ld_abs = true;
092ed096 1508 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1509 goto next;
1510 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1511 goto next;
1512 off = i + insn[i].off + 1;
1513 if (off < subprog_start || off >= subprog_end) {
1514 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1515 return -EINVAL;
1516 }
1517next:
1518 if (i == subprog_end - 1) {
1519 /* to avoid fall-through from one subprog into another
1520 * the last insn of the subprog should be either exit
1521 * or unconditional jump back
1522 */
1523 if (code != (BPF_JMP | BPF_EXIT) &&
1524 code != (BPF_JMP | BPF_JA)) {
1525 verbose(env, "last insn is not an exit or jmp\n");
1526 return -EINVAL;
1527 }
1528 subprog_start = subprog_end;
4cb3d99c
JW
1529 cur_subprog++;
1530 if (cur_subprog < env->subprog_cnt)
9c8105bd 1531 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1532 }
1533 }
1534 return 0;
1535}
1536
679c782d
EC
1537/* Parentage chain of this register (or stack slot) should take care of all
1538 * issues like callee-saved registers, stack slot allocation time, etc.
1539 */
f4d7e40a 1540static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1541 const struct bpf_reg_state *state,
5327ed3d 1542 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1543{
1544 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1545 int cnt = 0;
dc503a8a
EC
1546
1547 while (parent) {
1548 /* if read wasn't screened by an earlier write ... */
679c782d 1549 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1550 break;
9242b5f5
AS
1551 if (parent->live & REG_LIVE_DONE) {
1552 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1553 reg_type_str[parent->type],
1554 parent->var_off.value, parent->off);
1555 return -EFAULT;
1556 }
5327ed3d
JW
1557 /* The first condition is more likely to be true than the
1558 * second, checked it first.
1559 */
1560 if ((parent->live & REG_LIVE_READ) == flag ||
1561 parent->live & REG_LIVE_READ64)
25af32da
AS
1562 /* The parentage chain never changes and
1563 * this parent was already marked as LIVE_READ.
1564 * There is no need to keep walking the chain again and
1565 * keep re-marking all parents as LIVE_READ.
1566 * This case happens when the same register is read
1567 * multiple times without writes into it in-between.
5327ed3d
JW
1568 * Also, if parent has the stronger REG_LIVE_READ64 set,
1569 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1570 */
1571 break;
dc503a8a 1572 /* ... then we depend on parent's value */
5327ed3d
JW
1573 parent->live |= flag;
1574 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1575 if (flag == REG_LIVE_READ64)
1576 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1577 state = parent;
1578 parent = state->parent;
f4d7e40a 1579 writes = true;
06ee7115 1580 cnt++;
dc503a8a 1581 }
06ee7115
AS
1582
1583 if (env->longest_mark_read_walk < cnt)
1584 env->longest_mark_read_walk = cnt;
f4d7e40a 1585 return 0;
dc503a8a
EC
1586}
1587
5327ed3d
JW
1588/* This function is supposed to be used by the following 32-bit optimization
1589 * code only. It returns TRUE if the source or destination register operates
1590 * on 64-bit, otherwise return FALSE.
1591 */
1592static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1593 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1594{
1595 u8 code, class, op;
1596
1597 code = insn->code;
1598 class = BPF_CLASS(code);
1599 op = BPF_OP(code);
1600 if (class == BPF_JMP) {
1601 /* BPF_EXIT for "main" will reach here. Return TRUE
1602 * conservatively.
1603 */
1604 if (op == BPF_EXIT)
1605 return true;
1606 if (op == BPF_CALL) {
1607 /* BPF to BPF call will reach here because of marking
1608 * caller saved clobber with DST_OP_NO_MARK for which we
1609 * don't care the register def because they are anyway
1610 * marked as NOT_INIT already.
1611 */
1612 if (insn->src_reg == BPF_PSEUDO_CALL)
1613 return false;
1614 /* Helper call will reach here because of arg type
1615 * check, conservatively return TRUE.
1616 */
1617 if (t == SRC_OP)
1618 return true;
1619
1620 return false;
1621 }
1622 }
1623
1624 if (class == BPF_ALU64 || class == BPF_JMP ||
1625 /* BPF_END always use BPF_ALU class. */
1626 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1627 return true;
1628
1629 if (class == BPF_ALU || class == BPF_JMP32)
1630 return false;
1631
1632 if (class == BPF_LDX) {
1633 if (t != SRC_OP)
1634 return BPF_SIZE(code) == BPF_DW;
1635 /* LDX source must be ptr. */
1636 return true;
1637 }
1638
1639 if (class == BPF_STX) {
1640 if (reg->type != SCALAR_VALUE)
1641 return true;
1642 return BPF_SIZE(code) == BPF_DW;
1643 }
1644
1645 if (class == BPF_LD) {
1646 u8 mode = BPF_MODE(code);
1647
1648 /* LD_IMM64 */
1649 if (mode == BPF_IMM)
1650 return true;
1651
1652 /* Both LD_IND and LD_ABS return 32-bit data. */
1653 if (t != SRC_OP)
1654 return false;
1655
1656 /* Implicit ctx ptr. */
1657 if (regno == BPF_REG_6)
1658 return true;
1659
1660 /* Explicit source could be any width. */
1661 return true;
1662 }
1663
1664 if (class == BPF_ST)
1665 /* The only source register for BPF_ST is a ptr. */
1666 return true;
1667
1668 /* Conservatively return true at default. */
1669 return true;
1670}
1671
b325fbca
JW
1672/* Return TRUE if INSN doesn't have explicit value define. */
1673static bool insn_no_def(struct bpf_insn *insn)
1674{
1675 u8 class = BPF_CLASS(insn->code);
1676
1677 return (class == BPF_JMP || class == BPF_JMP32 ||
1678 class == BPF_STX || class == BPF_ST);
1679}
1680
1681/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1682static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1683{
1684 if (insn_no_def(insn))
1685 return false;
1686
1687 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1688}
1689
5327ed3d
JW
1690static void mark_insn_zext(struct bpf_verifier_env *env,
1691 struct bpf_reg_state *reg)
1692{
1693 s32 def_idx = reg->subreg_def;
1694
1695 if (def_idx == DEF_NOT_SUBREG)
1696 return;
1697
1698 env->insn_aux_data[def_idx - 1].zext_dst = true;
1699 /* The dst will be zero extended, so won't be sub-register anymore. */
1700 reg->subreg_def = DEF_NOT_SUBREG;
1701}
1702
dc503a8a 1703static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1704 enum reg_arg_type t)
1705{
f4d7e40a
AS
1706 struct bpf_verifier_state *vstate = env->cur_state;
1707 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1708 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1709 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1710 bool rw64;
dc503a8a 1711
17a52670 1712 if (regno >= MAX_BPF_REG) {
61bd5218 1713 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1714 return -EINVAL;
1715 }
1716
c342dc10 1717 reg = &regs[regno];
5327ed3d 1718 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1719 if (t == SRC_OP) {
1720 /* check whether register used as source operand can be read */
c342dc10 1721 if (reg->type == NOT_INIT) {
61bd5218 1722 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1723 return -EACCES;
1724 }
679c782d 1725 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1726 if (regno == BPF_REG_FP)
1727 return 0;
1728
5327ed3d
JW
1729 if (rw64)
1730 mark_insn_zext(env, reg);
1731
1732 return mark_reg_read(env, reg, reg->parent,
1733 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1734 } else {
1735 /* check whether register used as dest operand can be written to */
1736 if (regno == BPF_REG_FP) {
61bd5218 1737 verbose(env, "frame pointer is read only\n");
17a52670
AS
1738 return -EACCES;
1739 }
c342dc10 1740 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1741 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1742 if (t == DST_OP)
61bd5218 1743 mark_reg_unknown(env, regs, regno);
17a52670
AS
1744 }
1745 return 0;
1746}
1747
b5dc0163
AS
1748/* for any branch, call, exit record the history of jmps in the given state */
1749static int push_jmp_history(struct bpf_verifier_env *env,
1750 struct bpf_verifier_state *cur)
1751{
1752 u32 cnt = cur->jmp_history_cnt;
1753 struct bpf_idx_pair *p;
1754
1755 cnt++;
1756 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1757 if (!p)
1758 return -ENOMEM;
1759 p[cnt - 1].idx = env->insn_idx;
1760 p[cnt - 1].prev_idx = env->prev_insn_idx;
1761 cur->jmp_history = p;
1762 cur->jmp_history_cnt = cnt;
1763 return 0;
1764}
1765
1766/* Backtrack one insn at a time. If idx is not at the top of recorded
1767 * history then previous instruction came from straight line execution.
1768 */
1769static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1770 u32 *history)
1771{
1772 u32 cnt = *history;
1773
1774 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1775 i = st->jmp_history[cnt - 1].prev_idx;
1776 (*history)--;
1777 } else {
1778 i--;
1779 }
1780 return i;
1781}
1782
1783/* For given verifier state backtrack_insn() is called from the last insn to
1784 * the first insn. Its purpose is to compute a bitmask of registers and
1785 * stack slots that needs precision in the parent verifier state.
1786 */
1787static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1788 u32 *reg_mask, u64 *stack_mask)
1789{
1790 const struct bpf_insn_cbs cbs = {
1791 .cb_print = verbose,
1792 .private_data = env,
1793 };
1794 struct bpf_insn *insn = env->prog->insnsi + idx;
1795 u8 class = BPF_CLASS(insn->code);
1796 u8 opcode = BPF_OP(insn->code);
1797 u8 mode = BPF_MODE(insn->code);
1798 u32 dreg = 1u << insn->dst_reg;
1799 u32 sreg = 1u << insn->src_reg;
1800 u32 spi;
1801
1802 if (insn->code == 0)
1803 return 0;
1804 if (env->log.level & BPF_LOG_LEVEL) {
1805 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1806 verbose(env, "%d: ", idx);
1807 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1808 }
1809
1810 if (class == BPF_ALU || class == BPF_ALU64) {
1811 if (!(*reg_mask & dreg))
1812 return 0;
1813 if (opcode == BPF_MOV) {
1814 if (BPF_SRC(insn->code) == BPF_X) {
1815 /* dreg = sreg
1816 * dreg needs precision after this insn
1817 * sreg needs precision before this insn
1818 */
1819 *reg_mask &= ~dreg;
1820 *reg_mask |= sreg;
1821 } else {
1822 /* dreg = K
1823 * dreg needs precision after this insn.
1824 * Corresponding register is already marked
1825 * as precise=true in this verifier state.
1826 * No further markings in parent are necessary
1827 */
1828 *reg_mask &= ~dreg;
1829 }
1830 } else {
1831 if (BPF_SRC(insn->code) == BPF_X) {
1832 /* dreg += sreg
1833 * both dreg and sreg need precision
1834 * before this insn
1835 */
1836 *reg_mask |= sreg;
1837 } /* else dreg += K
1838 * dreg still needs precision before this insn
1839 */
1840 }
1841 } else if (class == BPF_LDX) {
1842 if (!(*reg_mask & dreg))
1843 return 0;
1844 *reg_mask &= ~dreg;
1845
1846 /* scalars can only be spilled into stack w/o losing precision.
1847 * Load from any other memory can be zero extended.
1848 * The desire to keep that precision is already indicated
1849 * by 'precise' mark in corresponding register of this state.
1850 * No further tracking necessary.
1851 */
1852 if (insn->src_reg != BPF_REG_FP)
1853 return 0;
1854 if (BPF_SIZE(insn->code) != BPF_DW)
1855 return 0;
1856
1857 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1858 * that [fp - off] slot contains scalar that needs to be
1859 * tracked with precision
1860 */
1861 spi = (-insn->off - 1) / BPF_REG_SIZE;
1862 if (spi >= 64) {
1863 verbose(env, "BUG spi %d\n", spi);
1864 WARN_ONCE(1, "verifier backtracking bug");
1865 return -EFAULT;
1866 }
1867 *stack_mask |= 1ull << spi;
b3b50f05 1868 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 1869 if (*reg_mask & dreg)
b3b50f05 1870 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
1871 * to access memory. It means backtracking
1872 * encountered a case of pointer subtraction.
1873 */
1874 return -ENOTSUPP;
1875 /* scalars can only be spilled into stack */
1876 if (insn->dst_reg != BPF_REG_FP)
1877 return 0;
1878 if (BPF_SIZE(insn->code) != BPF_DW)
1879 return 0;
1880 spi = (-insn->off - 1) / BPF_REG_SIZE;
1881 if (spi >= 64) {
1882 verbose(env, "BUG spi %d\n", spi);
1883 WARN_ONCE(1, "verifier backtracking bug");
1884 return -EFAULT;
1885 }
1886 if (!(*stack_mask & (1ull << spi)))
1887 return 0;
1888 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
1889 if (class == BPF_STX)
1890 *reg_mask |= sreg;
b5dc0163
AS
1891 } else if (class == BPF_JMP || class == BPF_JMP32) {
1892 if (opcode == BPF_CALL) {
1893 if (insn->src_reg == BPF_PSEUDO_CALL)
1894 return -ENOTSUPP;
1895 /* regular helper call sets R0 */
1896 *reg_mask &= ~1;
1897 if (*reg_mask & 0x3f) {
1898 /* if backtracing was looking for registers R1-R5
1899 * they should have been found already.
1900 */
1901 verbose(env, "BUG regs %x\n", *reg_mask);
1902 WARN_ONCE(1, "verifier backtracking bug");
1903 return -EFAULT;
1904 }
1905 } else if (opcode == BPF_EXIT) {
1906 return -ENOTSUPP;
1907 }
1908 } else if (class == BPF_LD) {
1909 if (!(*reg_mask & dreg))
1910 return 0;
1911 *reg_mask &= ~dreg;
1912 /* It's ld_imm64 or ld_abs or ld_ind.
1913 * For ld_imm64 no further tracking of precision
1914 * into parent is necessary
1915 */
1916 if (mode == BPF_IND || mode == BPF_ABS)
1917 /* to be analyzed */
1918 return -ENOTSUPP;
b5dc0163
AS
1919 }
1920 return 0;
1921}
1922
1923/* the scalar precision tracking algorithm:
1924 * . at the start all registers have precise=false.
1925 * . scalar ranges are tracked as normal through alu and jmp insns.
1926 * . once precise value of the scalar register is used in:
1927 * . ptr + scalar alu
1928 * . if (scalar cond K|scalar)
1929 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1930 * backtrack through the verifier states and mark all registers and
1931 * stack slots with spilled constants that these scalar regisers
1932 * should be precise.
1933 * . during state pruning two registers (or spilled stack slots)
1934 * are equivalent if both are not precise.
1935 *
1936 * Note the verifier cannot simply walk register parentage chain,
1937 * since many different registers and stack slots could have been
1938 * used to compute single precise scalar.
1939 *
1940 * The approach of starting with precise=true for all registers and then
1941 * backtrack to mark a register as not precise when the verifier detects
1942 * that program doesn't care about specific value (e.g., when helper
1943 * takes register as ARG_ANYTHING parameter) is not safe.
1944 *
1945 * It's ok to walk single parentage chain of the verifier states.
1946 * It's possible that this backtracking will go all the way till 1st insn.
1947 * All other branches will be explored for needing precision later.
1948 *
1949 * The backtracking needs to deal with cases like:
1950 * 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)
1951 * r9 -= r8
1952 * r5 = r9
1953 * if r5 > 0x79f goto pc+7
1954 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1955 * r5 += 1
1956 * ...
1957 * call bpf_perf_event_output#25
1958 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1959 *
1960 * and this case:
1961 * r6 = 1
1962 * call foo // uses callee's r6 inside to compute r0
1963 * r0 += r6
1964 * if r0 == 0 goto
1965 *
1966 * to track above reg_mask/stack_mask needs to be independent for each frame.
1967 *
1968 * Also if parent's curframe > frame where backtracking started,
1969 * the verifier need to mark registers in both frames, otherwise callees
1970 * may incorrectly prune callers. This is similar to
1971 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1972 *
1973 * For now backtracking falls back into conservative marking.
1974 */
1975static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1976 struct bpf_verifier_state *st)
1977{
1978 struct bpf_func_state *func;
1979 struct bpf_reg_state *reg;
1980 int i, j;
1981
1982 /* big hammer: mark all scalars precise in this path.
1983 * pop_stack may still get !precise scalars.
1984 */
1985 for (; st; st = st->parent)
1986 for (i = 0; i <= st->curframe; i++) {
1987 func = st->frame[i];
1988 for (j = 0; j < BPF_REG_FP; j++) {
1989 reg = &func->regs[j];
1990 if (reg->type != SCALAR_VALUE)
1991 continue;
1992 reg->precise = true;
1993 }
1994 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1995 if (func->stack[j].slot_type[0] != STACK_SPILL)
1996 continue;
1997 reg = &func->stack[j].spilled_ptr;
1998 if (reg->type != SCALAR_VALUE)
1999 continue;
2000 reg->precise = true;
2001 }
2002 }
2003}
2004
a3ce685d
AS
2005static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2006 int spi)
b5dc0163
AS
2007{
2008 struct bpf_verifier_state *st = env->cur_state;
2009 int first_idx = st->first_insn_idx;
2010 int last_idx = env->insn_idx;
2011 struct bpf_func_state *func;
2012 struct bpf_reg_state *reg;
a3ce685d
AS
2013 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2014 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2015 bool skip_first = true;
a3ce685d 2016 bool new_marks = false;
b5dc0163
AS
2017 int i, err;
2018
2c78ee89 2019 if (!env->bpf_capable)
b5dc0163
AS
2020 return 0;
2021
2022 func = st->frame[st->curframe];
a3ce685d
AS
2023 if (regno >= 0) {
2024 reg = &func->regs[regno];
2025 if (reg->type != SCALAR_VALUE) {
2026 WARN_ONCE(1, "backtracing misuse");
2027 return -EFAULT;
2028 }
2029 if (!reg->precise)
2030 new_marks = true;
2031 else
2032 reg_mask = 0;
2033 reg->precise = true;
b5dc0163 2034 }
b5dc0163 2035
a3ce685d
AS
2036 while (spi >= 0) {
2037 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2038 stack_mask = 0;
2039 break;
2040 }
2041 reg = &func->stack[spi].spilled_ptr;
2042 if (reg->type != SCALAR_VALUE) {
2043 stack_mask = 0;
2044 break;
2045 }
2046 if (!reg->precise)
2047 new_marks = true;
2048 else
2049 stack_mask = 0;
2050 reg->precise = true;
2051 break;
2052 }
2053
2054 if (!new_marks)
2055 return 0;
2056 if (!reg_mask && !stack_mask)
2057 return 0;
b5dc0163
AS
2058 for (;;) {
2059 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2060 u32 history = st->jmp_history_cnt;
2061
2062 if (env->log.level & BPF_LOG_LEVEL)
2063 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2064 for (i = last_idx;;) {
2065 if (skip_first) {
2066 err = 0;
2067 skip_first = false;
2068 } else {
2069 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2070 }
2071 if (err == -ENOTSUPP) {
2072 mark_all_scalars_precise(env, st);
2073 return 0;
2074 } else if (err) {
2075 return err;
2076 }
2077 if (!reg_mask && !stack_mask)
2078 /* Found assignment(s) into tracked register in this state.
2079 * Since this state is already marked, just return.
2080 * Nothing to be tracked further in the parent state.
2081 */
2082 return 0;
2083 if (i == first_idx)
2084 break;
2085 i = get_prev_insn_idx(st, i, &history);
2086 if (i >= env->prog->len) {
2087 /* This can happen if backtracking reached insn 0
2088 * and there are still reg_mask or stack_mask
2089 * to backtrack.
2090 * It means the backtracking missed the spot where
2091 * particular register was initialized with a constant.
2092 */
2093 verbose(env, "BUG backtracking idx %d\n", i);
2094 WARN_ONCE(1, "verifier backtracking bug");
2095 return -EFAULT;
2096 }
2097 }
2098 st = st->parent;
2099 if (!st)
2100 break;
2101
a3ce685d 2102 new_marks = false;
b5dc0163
AS
2103 func = st->frame[st->curframe];
2104 bitmap_from_u64(mask, reg_mask);
2105 for_each_set_bit(i, mask, 32) {
2106 reg = &func->regs[i];
a3ce685d
AS
2107 if (reg->type != SCALAR_VALUE) {
2108 reg_mask &= ~(1u << i);
b5dc0163 2109 continue;
a3ce685d 2110 }
b5dc0163
AS
2111 if (!reg->precise)
2112 new_marks = true;
2113 reg->precise = true;
2114 }
2115
2116 bitmap_from_u64(mask, stack_mask);
2117 for_each_set_bit(i, mask, 64) {
2118 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2119 /* the sequence of instructions:
2120 * 2: (bf) r3 = r10
2121 * 3: (7b) *(u64 *)(r3 -8) = r0
2122 * 4: (79) r4 = *(u64 *)(r10 -8)
2123 * doesn't contain jmps. It's backtracked
2124 * as a single block.
2125 * During backtracking insn 3 is not recognized as
2126 * stack access, so at the end of backtracking
2127 * stack slot fp-8 is still marked in stack_mask.
2128 * However the parent state may not have accessed
2129 * fp-8 and it's "unallocated" stack space.
2130 * In such case fallback to conservative.
b5dc0163 2131 */
2339cd6c
AS
2132 mark_all_scalars_precise(env, st);
2133 return 0;
b5dc0163
AS
2134 }
2135
a3ce685d
AS
2136 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2137 stack_mask &= ~(1ull << i);
b5dc0163 2138 continue;
a3ce685d 2139 }
b5dc0163 2140 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2141 if (reg->type != SCALAR_VALUE) {
2142 stack_mask &= ~(1ull << i);
b5dc0163 2143 continue;
a3ce685d 2144 }
b5dc0163
AS
2145 if (!reg->precise)
2146 new_marks = true;
2147 reg->precise = true;
2148 }
2149 if (env->log.level & BPF_LOG_LEVEL) {
2150 print_verifier_state(env, func);
2151 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2152 new_marks ? "didn't have" : "already had",
2153 reg_mask, stack_mask);
2154 }
2155
a3ce685d
AS
2156 if (!reg_mask && !stack_mask)
2157 break;
b5dc0163
AS
2158 if (!new_marks)
2159 break;
2160
2161 last_idx = st->last_insn_idx;
2162 first_idx = st->first_insn_idx;
2163 }
2164 return 0;
2165}
2166
a3ce685d
AS
2167static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2168{
2169 return __mark_chain_precision(env, regno, -1);
2170}
2171
2172static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2173{
2174 return __mark_chain_precision(env, -1, spi);
2175}
b5dc0163 2176
1be7f75d
AS
2177static bool is_spillable_regtype(enum bpf_reg_type type)
2178{
2179 switch (type) {
2180 case PTR_TO_MAP_VALUE:
2181 case PTR_TO_MAP_VALUE_OR_NULL:
2182 case PTR_TO_STACK:
2183 case PTR_TO_CTX:
969bf05e 2184 case PTR_TO_PACKET:
de8f3a83 2185 case PTR_TO_PACKET_META:
969bf05e 2186 case PTR_TO_PACKET_END:
d58e468b 2187 case PTR_TO_FLOW_KEYS:
1be7f75d 2188 case CONST_PTR_TO_MAP:
c64b7983
JS
2189 case PTR_TO_SOCKET:
2190 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2191 case PTR_TO_SOCK_COMMON:
2192 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2193 case PTR_TO_TCP_SOCK:
2194 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2195 case PTR_TO_XDP_SOCK:
65726b5b 2196 case PTR_TO_BTF_ID:
b121b341 2197 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2198 case PTR_TO_RDONLY_BUF:
2199 case PTR_TO_RDONLY_BUF_OR_NULL:
2200 case PTR_TO_RDWR_BUF:
2201 case PTR_TO_RDWR_BUF_OR_NULL:
1be7f75d
AS
2202 return true;
2203 default:
2204 return false;
2205 }
2206}
2207
cc2b14d5
AS
2208/* Does this register contain a constant zero? */
2209static bool register_is_null(struct bpf_reg_state *reg)
2210{
2211 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2212}
2213
f7cf25b2
AS
2214static bool register_is_const(struct bpf_reg_state *reg)
2215{
2216 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2217}
2218
6e7e63cb
JH
2219static bool __is_pointer_value(bool allow_ptr_leaks,
2220 const struct bpf_reg_state *reg)
2221{
2222 if (allow_ptr_leaks)
2223 return false;
2224
2225 return reg->type != SCALAR_VALUE;
2226}
2227
f7cf25b2
AS
2228static void save_register_state(struct bpf_func_state *state,
2229 int spi, struct bpf_reg_state *reg)
2230{
2231 int i;
2232
2233 state->stack[spi].spilled_ptr = *reg;
2234 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2235
2236 for (i = 0; i < BPF_REG_SIZE; i++)
2237 state->stack[spi].slot_type[i] = STACK_SPILL;
2238}
2239
17a52670
AS
2240/* check_stack_read/write functions track spill/fill of registers,
2241 * stack boundary and alignment are checked in check_mem_access()
2242 */
61bd5218 2243static int check_stack_write(struct bpf_verifier_env *env,
f4d7e40a 2244 struct bpf_func_state *state, /* func where register points to */
af86ca4e 2245 int off, int size, int value_regno, int insn_idx)
17a52670 2246{
f4d7e40a 2247 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2248 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2249 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2250 struct bpf_reg_state *reg = NULL;
638f5b90 2251
f4d7e40a 2252 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2253 state->acquired_refs, true);
638f5b90
AS
2254 if (err)
2255 return err;
9c399760
AS
2256 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2257 * so it's aligned access and [off, off + size) are within stack limits
2258 */
638f5b90
AS
2259 if (!env->allow_ptr_leaks &&
2260 state->stack[spi].slot_type[0] == STACK_SPILL &&
2261 size != BPF_REG_SIZE) {
2262 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2263 return -EACCES;
2264 }
17a52670 2265
f4d7e40a 2266 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2267 if (value_regno >= 0)
2268 reg = &cur->regs[value_regno];
17a52670 2269
f7cf25b2 2270 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
2c78ee89 2271 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2272 if (dst_reg != BPF_REG_FP) {
2273 /* The backtracking logic can only recognize explicit
2274 * stack slot address like [fp - 8]. Other spill of
2275 * scalar via different register has to be conervative.
2276 * Backtrack from here and mark all registers as precise
2277 * that contributed into 'reg' being a constant.
2278 */
2279 err = mark_chain_precision(env, value_regno);
2280 if (err)
2281 return err;
2282 }
f7cf25b2
AS
2283 save_register_state(state, spi, reg);
2284 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2285 /* register containing pointer is being spilled into stack */
9c399760 2286 if (size != BPF_REG_SIZE) {
f7cf25b2 2287 verbose_linfo(env, insn_idx, "; ");
61bd5218 2288 verbose(env, "invalid size of register spill\n");
17a52670
AS
2289 return -EACCES;
2290 }
2291
f7cf25b2 2292 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2293 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2294 return -EINVAL;
2295 }
2296
2c78ee89 2297 if (!env->bypass_spec_v4) {
f7cf25b2 2298 bool sanitize = false;
17a52670 2299
f7cf25b2
AS
2300 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2301 register_is_const(&state->stack[spi].spilled_ptr))
2302 sanitize = true;
2303 for (i = 0; i < BPF_REG_SIZE; i++)
2304 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2305 sanitize = true;
2306 break;
2307 }
2308 if (sanitize) {
af86ca4e
AS
2309 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2310 int soff = (-spi - 1) * BPF_REG_SIZE;
2311
2312 /* detected reuse of integer stack slot with a pointer
2313 * which means either llvm is reusing stack slot or
2314 * an attacker is trying to exploit CVE-2018-3639
2315 * (speculative store bypass)
2316 * Have to sanitize that slot with preemptive
2317 * store of zero.
2318 */
2319 if (*poff && *poff != soff) {
2320 /* disallow programs where single insn stores
2321 * into two different stack slots, since verifier
2322 * cannot sanitize them
2323 */
2324 verbose(env,
2325 "insn %d cannot access two stack slots fp%d and fp%d",
2326 insn_idx, *poff, soff);
2327 return -EINVAL;
2328 }
2329 *poff = soff;
2330 }
af86ca4e 2331 }
f7cf25b2 2332 save_register_state(state, spi, reg);
9c399760 2333 } else {
cc2b14d5
AS
2334 u8 type = STACK_MISC;
2335
679c782d
EC
2336 /* regular write of data into stack destroys any spilled ptr */
2337 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2338 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2339 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2340 for (i = 0; i < BPF_REG_SIZE; i++)
2341 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2342
cc2b14d5
AS
2343 /* only mark the slot as written if all 8 bytes were written
2344 * otherwise read propagation may incorrectly stop too soon
2345 * when stack slots are partially written.
2346 * This heuristic means that read propagation will be
2347 * conservative, since it will add reg_live_read marks
2348 * to stack slots all the way to first state when programs
2349 * writes+reads less than 8 bytes
2350 */
2351 if (size == BPF_REG_SIZE)
2352 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2353
2354 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2355 if (reg && register_is_null(reg)) {
2356 /* backtracking doesn't work for STACK_ZERO yet. */
2357 err = mark_chain_precision(env, value_regno);
2358 if (err)
2359 return err;
cc2b14d5 2360 type = STACK_ZERO;
b5dc0163 2361 }
cc2b14d5 2362
0bae2d4d 2363 /* Mark slots affected by this stack write. */
9c399760 2364 for (i = 0; i < size; i++)
638f5b90 2365 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2366 type;
17a52670
AS
2367 }
2368 return 0;
2369}
2370
61bd5218 2371static int check_stack_read(struct bpf_verifier_env *env,
f4d7e40a
AS
2372 struct bpf_func_state *reg_state /* func where register points to */,
2373 int off, int size, int value_regno)
17a52670 2374{
f4d7e40a
AS
2375 struct bpf_verifier_state *vstate = env->cur_state;
2376 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2377 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2378 struct bpf_reg_state *reg;
638f5b90 2379 u8 *stype;
17a52670 2380
f4d7e40a 2381 if (reg_state->allocated_stack <= slot) {
638f5b90
AS
2382 verbose(env, "invalid read from stack off %d+0 size %d\n",
2383 off, size);
2384 return -EACCES;
2385 }
f4d7e40a 2386 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2387 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2388
638f5b90 2389 if (stype[0] == STACK_SPILL) {
9c399760 2390 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2391 if (reg->type != SCALAR_VALUE) {
2392 verbose_linfo(env, env->insn_idx, "; ");
2393 verbose(env, "invalid size of register fill\n");
2394 return -EACCES;
2395 }
2396 if (value_regno >= 0) {
2397 mark_reg_unknown(env, state->regs, value_regno);
2398 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2399 }
2400 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2401 return 0;
17a52670 2402 }
9c399760 2403 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2404 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2405 verbose(env, "corrupted spill memory\n");
17a52670
AS
2406 return -EACCES;
2407 }
2408 }
2409
dc503a8a 2410 if (value_regno >= 0) {
17a52670 2411 /* restore register state from stack */
f7cf25b2 2412 state->regs[value_regno] = *reg;
2f18f62e
AS
2413 /* mark reg as written since spilled pointer state likely
2414 * has its liveness marks cleared by is_state_visited()
2415 * which resets stack/reg liveness for state transitions
2416 */
2417 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb
JH
2418 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2419 /* If value_regno==-1, the caller is asking us whether
2420 * it is acceptable to use this value as a SCALAR_VALUE
2421 * (e.g. for XADD).
2422 * We must not allow unprivileged callers to do that
2423 * with spilled pointers.
2424 */
2425 verbose(env, "leaking pointer from stack off %d\n",
2426 off);
2427 return -EACCES;
dc503a8a 2428 }
f7cf25b2 2429 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2430 } else {
cc2b14d5
AS
2431 int zeros = 0;
2432
17a52670 2433 for (i = 0; i < size; i++) {
cc2b14d5
AS
2434 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2435 continue;
2436 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2437 zeros++;
2438 continue;
17a52670 2439 }
cc2b14d5
AS
2440 verbose(env, "invalid read from stack off %d+%d size %d\n",
2441 off, i, size);
2442 return -EACCES;
2443 }
f7cf25b2 2444 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
cc2b14d5
AS
2445 if (value_regno >= 0) {
2446 if (zeros == size) {
2447 /* any size read into register is zero extended,
2448 * so the whole register == const_zero
2449 */
2450 __mark_reg_const_zero(&state->regs[value_regno]);
b5dc0163
AS
2451 /* backtracking doesn't support STACK_ZERO yet,
2452 * so mark it precise here, so that later
2453 * backtracking can stop here.
2454 * Backtracking may not need this if this register
2455 * doesn't participate in pointer adjustment.
2456 * Forward propagation of precise flag is not
2457 * necessary either. This mark is only to stop
2458 * backtracking. Any register that contributed
2459 * to const 0 was marked precise before spill.
2460 */
2461 state->regs[value_regno].precise = true;
cc2b14d5
AS
2462 } else {
2463 /* have read misc data from the stack */
2464 mark_reg_unknown(env, state->regs, value_regno);
2465 }
2466 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
17a52670 2467 }
17a52670 2468 }
f7cf25b2 2469 return 0;
17a52670
AS
2470}
2471
e4298d25
DB
2472static int check_stack_access(struct bpf_verifier_env *env,
2473 const struct bpf_reg_state *reg,
2474 int off, int size)
2475{
2476 /* Stack accesses must be at a fixed offset, so that we
2477 * can determine what type of data were returned. See
2478 * check_stack_read().
2479 */
2480 if (!tnum_is_const(reg->var_off)) {
2481 char tn_buf[48];
2482
2483 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1fbd20f8 2484 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
e4298d25
DB
2485 tn_buf, off, size);
2486 return -EACCES;
2487 }
2488
2489 if (off >= 0 || off < -MAX_BPF_STACK) {
2490 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2491 return -EACCES;
2492 }
2493
2494 return 0;
2495}
2496
591fe988
DB
2497static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2498 int off, int size, enum bpf_access_type type)
2499{
2500 struct bpf_reg_state *regs = cur_regs(env);
2501 struct bpf_map *map = regs[regno].map_ptr;
2502 u32 cap = bpf_map_flags_to_cap(map);
2503
2504 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2505 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2506 map->value_size, off, size);
2507 return -EACCES;
2508 }
2509
2510 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2511 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2512 map->value_size, off, size);
2513 return -EACCES;
2514 }
2515
2516 return 0;
2517}
2518
457f4436
AN
2519/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2520static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2521 int off, int size, u32 mem_size,
2522 bool zero_size_allowed)
17a52670 2523{
457f4436
AN
2524 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2525 struct bpf_reg_state *reg;
2526
2527 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2528 return 0;
17a52670 2529
457f4436
AN
2530 reg = &cur_regs(env)[regno];
2531 switch (reg->type) {
2532 case PTR_TO_MAP_VALUE:
61bd5218 2533 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2534 mem_size, off, size);
2535 break;
2536 case PTR_TO_PACKET:
2537 case PTR_TO_PACKET_META:
2538 case PTR_TO_PACKET_END:
2539 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2540 off, size, regno, reg->id, off, mem_size);
2541 break;
2542 case PTR_TO_MEM:
2543 default:
2544 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2545 mem_size, off, size);
17a52670 2546 }
457f4436
AN
2547
2548 return -EACCES;
17a52670
AS
2549}
2550
457f4436
AN
2551/* check read/write into a memory region with possible variable offset */
2552static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2553 int off, int size, u32 mem_size,
2554 bool zero_size_allowed)
dbcfe5f7 2555{
f4d7e40a
AS
2556 struct bpf_verifier_state *vstate = env->cur_state;
2557 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2558 struct bpf_reg_state *reg = &state->regs[regno];
2559 int err;
2560
457f4436 2561 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2562 * need to try adding each of min_value and max_value to off
2563 * to make sure our theoretical access will be safe.
dbcfe5f7 2564 */
06ee7115 2565 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2566 print_verifier_state(env, state);
b7137c4e 2567
dbcfe5f7
GB
2568 /* The minimum value is only important with signed
2569 * comparisons where we can't assume the floor of a
2570 * value is 0. If we are using signed variables for our
2571 * index'es we need to make sure that whatever we use
2572 * will have a set floor within our range.
2573 */
b7137c4e
DB
2574 if (reg->smin_value < 0 &&
2575 (reg->smin_value == S64_MIN ||
2576 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2577 reg->smin_value + off < 0)) {
61bd5218 2578 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2579 regno);
2580 return -EACCES;
2581 }
457f4436
AN
2582 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2583 mem_size, zero_size_allowed);
dbcfe5f7 2584 if (err) {
457f4436 2585 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 2586 regno);
dbcfe5f7
GB
2587 return err;
2588 }
2589
b03c9f9f
EC
2590 /* If we haven't set a max value then we need to bail since we can't be
2591 * sure we won't do bad things.
2592 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 2593 */
b03c9f9f 2594 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 2595 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
2596 regno);
2597 return -EACCES;
2598 }
457f4436
AN
2599 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2600 mem_size, zero_size_allowed);
2601 if (err) {
2602 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 2603 regno);
457f4436
AN
2604 return err;
2605 }
2606
2607 return 0;
2608}
d83525ca 2609
457f4436
AN
2610/* check read/write into a map element with possible variable offset */
2611static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2612 int off, int size, bool zero_size_allowed)
2613{
2614 struct bpf_verifier_state *vstate = env->cur_state;
2615 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2616 struct bpf_reg_state *reg = &state->regs[regno];
2617 struct bpf_map *map = reg->map_ptr;
2618 int err;
2619
2620 err = check_mem_region_access(env, regno, off, size, map->value_size,
2621 zero_size_allowed);
2622 if (err)
2623 return err;
2624
2625 if (map_value_has_spin_lock(map)) {
2626 u32 lock = map->spin_lock_off;
d83525ca
AS
2627
2628 /* if any part of struct bpf_spin_lock can be touched by
2629 * load/store reject this program.
2630 * To check that [x1, x2) overlaps with [y1, y2)
2631 * it is sufficient to check x1 < y2 && y1 < x2.
2632 */
2633 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2634 lock < reg->umax_value + off + size) {
2635 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2636 return -EACCES;
2637 }
2638 }
f1174f77 2639 return err;
dbcfe5f7
GB
2640}
2641
969bf05e
AS
2642#define MAX_PACKET_OFF 0xffff
2643
7e40781c
UP
2644static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2645{
2646 return prog->aux->linked_prog ? prog->aux->linked_prog->type
2647 : prog->type;
2648}
2649
58e2af8b 2650static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
2651 const struct bpf_call_arg_meta *meta,
2652 enum bpf_access_type t)
4acf6c0b 2653{
7e40781c
UP
2654 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2655
2656 switch (prog_type) {
5d66fa7d 2657 /* Program types only with direct read access go here! */
3a0af8fd
TG
2658 case BPF_PROG_TYPE_LWT_IN:
2659 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 2660 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 2661 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 2662 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 2663 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
2664 if (t == BPF_WRITE)
2665 return false;
7e57fbb2 2666 /* fallthrough */
5d66fa7d
DB
2667
2668 /* Program types with direct read + write access go here! */
36bbef52
DB
2669 case BPF_PROG_TYPE_SCHED_CLS:
2670 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 2671 case BPF_PROG_TYPE_XDP:
3a0af8fd 2672 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 2673 case BPF_PROG_TYPE_SK_SKB:
4f738adb 2674 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
2675 if (meta)
2676 return meta->pkt_access;
2677
2678 env->seen_direct_write = true;
4acf6c0b 2679 return true;
0d01da6a
SF
2680
2681 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2682 if (t == BPF_WRITE)
2683 env->seen_direct_write = true;
2684
2685 return true;
2686
4acf6c0b
BB
2687 default:
2688 return false;
2689 }
2690}
2691
f1174f77 2692static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 2693 int size, bool zero_size_allowed)
f1174f77 2694{
638f5b90 2695 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
2696 struct bpf_reg_state *reg = &regs[regno];
2697 int err;
2698
2699 /* We may have added a variable offset to the packet pointer; but any
2700 * reg->range we have comes after that. We are only checking the fixed
2701 * offset.
2702 */
2703
2704 /* We don't allow negative numbers, because we aren't tracking enough
2705 * detail to prove they're safe.
2706 */
b03c9f9f 2707 if (reg->smin_value < 0) {
61bd5218 2708 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
2709 regno);
2710 return -EACCES;
2711 }
457f4436
AN
2712 err = __check_mem_access(env, regno, off, size, reg->range,
2713 zero_size_allowed);
f1174f77 2714 if (err) {
61bd5218 2715 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
2716 return err;
2717 }
e647815a 2718
457f4436 2719 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
2720 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2721 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 2722 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
2723 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2724 */
2725 env->prog->aux->max_pkt_offset =
2726 max_t(u32, env->prog->aux->max_pkt_offset,
2727 off + reg->umax_value + size - 1);
2728
f1174f77
EC
2729 return err;
2730}
2731
2732/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 2733static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66
AS
2734 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2735 u32 *btf_id)
17a52670 2736{
f96da094
DB
2737 struct bpf_insn_access_aux info = {
2738 .reg_type = *reg_type,
9e15db66 2739 .log = &env->log,
f96da094 2740 };
31fd8581 2741
4f9218aa 2742 if (env->ops->is_valid_access &&
5e43f899 2743 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
2744 /* A non zero info.ctx_field_size indicates that this field is a
2745 * candidate for later verifier transformation to load the whole
2746 * field and then apply a mask when accessed with a narrower
2747 * access than actual ctx access size. A zero info.ctx_field_size
2748 * will only allow for whole field access and rejects any other
2749 * type of narrower access.
31fd8581 2750 */
23994631 2751 *reg_type = info.reg_type;
31fd8581 2752
b121b341 2753 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66
AS
2754 *btf_id = info.btf_id;
2755 else
2756 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
32bbe007
AS
2757 /* remember the offset of last byte accessed in ctx */
2758 if (env->prog->aux->max_ctx_offset < off + size)
2759 env->prog->aux->max_ctx_offset = off + size;
17a52670 2760 return 0;
32bbe007 2761 }
17a52670 2762
61bd5218 2763 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
2764 return -EACCES;
2765}
2766
d58e468b
PP
2767static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2768 int size)
2769{
2770 if (size < 0 || off < 0 ||
2771 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2772 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2773 off, size);
2774 return -EACCES;
2775 }
2776 return 0;
2777}
2778
5f456649
MKL
2779static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2780 u32 regno, int off, int size,
2781 enum bpf_access_type t)
c64b7983
JS
2782{
2783 struct bpf_reg_state *regs = cur_regs(env);
2784 struct bpf_reg_state *reg = &regs[regno];
5f456649 2785 struct bpf_insn_access_aux info = {};
46f8bc92 2786 bool valid;
c64b7983
JS
2787
2788 if (reg->smin_value < 0) {
2789 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2790 regno);
2791 return -EACCES;
2792 }
2793
46f8bc92
MKL
2794 switch (reg->type) {
2795 case PTR_TO_SOCK_COMMON:
2796 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2797 break;
2798 case PTR_TO_SOCKET:
2799 valid = bpf_sock_is_valid_access(off, size, t, &info);
2800 break;
655a51e5
MKL
2801 case PTR_TO_TCP_SOCK:
2802 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2803 break;
fada7fdc
JL
2804 case PTR_TO_XDP_SOCK:
2805 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2806 break;
46f8bc92
MKL
2807 default:
2808 valid = false;
c64b7983
JS
2809 }
2810
5f456649 2811
46f8bc92
MKL
2812 if (valid) {
2813 env->insn_aux_data[insn_idx].ctx_field_size =
2814 info.ctx_field_size;
2815 return 0;
2816 }
2817
2818 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2819 regno, reg_type_str[reg->type], off, size);
2820
2821 return -EACCES;
c64b7983
JS
2822}
2823
2a159c6f
DB
2824static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2825{
2826 return cur_regs(env) + regno;
2827}
2828
4cabc5b1
DB
2829static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2830{
2a159c6f 2831 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
2832}
2833
f37a8cb8
DB
2834static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2835{
2a159c6f 2836 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 2837
46f8bc92
MKL
2838 return reg->type == PTR_TO_CTX;
2839}
2840
2841static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2842{
2843 const struct bpf_reg_state *reg = reg_state(env, regno);
2844
2845 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
2846}
2847
ca369602
DB
2848static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2849{
2a159c6f 2850 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
2851
2852 return type_is_pkt_pointer(reg->type);
2853}
2854
4b5defde
DB
2855static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2856{
2857 const struct bpf_reg_state *reg = reg_state(env, regno);
2858
2859 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2860 return reg->type == PTR_TO_FLOW_KEYS;
2861}
2862
61bd5218
JK
2863static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2864 const struct bpf_reg_state *reg,
d1174416 2865 int off, int size, bool strict)
969bf05e 2866{
f1174f77 2867 struct tnum reg_off;
e07b98d9 2868 int ip_align;
d1174416
DM
2869
2870 /* Byte size accesses are always allowed. */
2871 if (!strict || size == 1)
2872 return 0;
2873
e4eda884
DM
2874 /* For platforms that do not have a Kconfig enabling
2875 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2876 * NET_IP_ALIGN is universally set to '2'. And on platforms
2877 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2878 * to this code only in strict mode where we want to emulate
2879 * the NET_IP_ALIGN==2 checking. Therefore use an
2880 * unconditional IP align value of '2'.
e07b98d9 2881 */
e4eda884 2882 ip_align = 2;
f1174f77
EC
2883
2884 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2885 if (!tnum_is_aligned(reg_off, size)) {
2886 char tn_buf[48];
2887
2888 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
2889 verbose(env,
2890 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 2891 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
2892 return -EACCES;
2893 }
79adffcd 2894
969bf05e
AS
2895 return 0;
2896}
2897
61bd5218
JK
2898static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2899 const struct bpf_reg_state *reg,
f1174f77
EC
2900 const char *pointer_desc,
2901 int off, int size, bool strict)
79adffcd 2902{
f1174f77
EC
2903 struct tnum reg_off;
2904
2905 /* Byte size accesses are always allowed. */
2906 if (!strict || size == 1)
2907 return 0;
2908
2909 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2910 if (!tnum_is_aligned(reg_off, size)) {
2911 char tn_buf[48];
2912
2913 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 2914 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 2915 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
2916 return -EACCES;
2917 }
2918
969bf05e
AS
2919 return 0;
2920}
2921
e07b98d9 2922static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
2923 const struct bpf_reg_state *reg, int off,
2924 int size, bool strict_alignment_once)
79adffcd 2925{
ca369602 2926 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 2927 const char *pointer_desc = "";
d1174416 2928
79adffcd
DB
2929 switch (reg->type) {
2930 case PTR_TO_PACKET:
de8f3a83
DB
2931 case PTR_TO_PACKET_META:
2932 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2933 * right in front, treat it the very same way.
2934 */
61bd5218 2935 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
2936 case PTR_TO_FLOW_KEYS:
2937 pointer_desc = "flow keys ";
2938 break;
f1174f77
EC
2939 case PTR_TO_MAP_VALUE:
2940 pointer_desc = "value ";
2941 break;
2942 case PTR_TO_CTX:
2943 pointer_desc = "context ";
2944 break;
2945 case PTR_TO_STACK:
2946 pointer_desc = "stack ";
a5ec6ae1
JH
2947 /* The stack spill tracking logic in check_stack_write()
2948 * and check_stack_read() relies on stack accesses being
2949 * aligned.
2950 */
2951 strict = true;
f1174f77 2952 break;
c64b7983
JS
2953 case PTR_TO_SOCKET:
2954 pointer_desc = "sock ";
2955 break;
46f8bc92
MKL
2956 case PTR_TO_SOCK_COMMON:
2957 pointer_desc = "sock_common ";
2958 break;
655a51e5
MKL
2959 case PTR_TO_TCP_SOCK:
2960 pointer_desc = "tcp_sock ";
2961 break;
fada7fdc
JL
2962 case PTR_TO_XDP_SOCK:
2963 pointer_desc = "xdp_sock ";
2964 break;
79adffcd 2965 default:
f1174f77 2966 break;
79adffcd 2967 }
61bd5218
JK
2968 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2969 strict);
79adffcd
DB
2970}
2971
f4d7e40a
AS
2972static int update_stack_depth(struct bpf_verifier_env *env,
2973 const struct bpf_func_state *func,
2974 int off)
2975{
9c8105bd 2976 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
2977
2978 if (stack >= -off)
2979 return 0;
2980
2981 /* update known max for given subprogram */
9c8105bd 2982 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
2983 return 0;
2984}
f4d7e40a 2985
70a87ffe
AS
2986/* starting from main bpf function walk all instructions of the function
2987 * and recursively walk all callees that given function can call.
2988 * Ignore jump and exit insns.
2989 * Since recursion is prevented by check_cfg() this algorithm
2990 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2991 */
2992static int check_max_stack_depth(struct bpf_verifier_env *env)
2993{
9c8105bd
JW
2994 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2995 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 2996 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 2997 bool tail_call_reachable = false;
70a87ffe
AS
2998 int ret_insn[MAX_CALL_FRAMES];
2999 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3000 int j;
f4d7e40a 3001
70a87ffe 3002process_func:
7f6e4312
MF
3003 /* protect against potential stack overflow that might happen when
3004 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3005 * depth for such case down to 256 so that the worst case scenario
3006 * would result in 8k stack size (32 which is tailcall limit * 256 =
3007 * 8k).
3008 *
3009 * To get the idea what might happen, see an example:
3010 * func1 -> sub rsp, 128
3011 * subfunc1 -> sub rsp, 256
3012 * tailcall1 -> add rsp, 256
3013 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3014 * subfunc2 -> sub rsp, 64
3015 * subfunc22 -> sub rsp, 128
3016 * tailcall2 -> add rsp, 128
3017 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3018 *
3019 * tailcall will unwind the current stack frame but it will not get rid
3020 * of caller's stack as shown on the example above.
3021 */
3022 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3023 verbose(env,
3024 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3025 depth);
3026 return -EACCES;
3027 }
70a87ffe
AS
3028 /* round up to 32-bytes, since this is granularity
3029 * of interpreter stack size
3030 */
9c8105bd 3031 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3032 if (depth > MAX_BPF_STACK) {
f4d7e40a 3033 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3034 frame + 1, depth);
f4d7e40a
AS
3035 return -EACCES;
3036 }
70a87ffe 3037continue_func:
4cb3d99c 3038 subprog_end = subprog[idx + 1].start;
70a87ffe
AS
3039 for (; i < subprog_end; i++) {
3040 if (insn[i].code != (BPF_JMP | BPF_CALL))
3041 continue;
3042 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3043 continue;
3044 /* remember insn and function to return to */
3045 ret_insn[frame] = i + 1;
9c8105bd 3046 ret_prog[frame] = idx;
70a87ffe
AS
3047
3048 /* find the callee */
3049 i = i + insn[i].imm + 1;
9c8105bd
JW
3050 idx = find_subprog(env, i);
3051 if (idx < 0) {
70a87ffe
AS
3052 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3053 i);
3054 return -EFAULT;
3055 }
ebf7d1f5
MF
3056
3057 if (subprog[idx].has_tail_call)
3058 tail_call_reachable = true;
3059
70a87ffe
AS
3060 frame++;
3061 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3062 verbose(env, "the call stack of %d frames is too deep !\n",
3063 frame);
3064 return -E2BIG;
70a87ffe
AS
3065 }
3066 goto process_func;
3067 }
ebf7d1f5
MF
3068 /* if tail call got detected across bpf2bpf calls then mark each of the
3069 * currently present subprog frames as tail call reachable subprogs;
3070 * this info will be utilized by JIT so that we will be preserving the
3071 * tail call counter throughout bpf2bpf calls combined with tailcalls
3072 */
3073 if (tail_call_reachable)
3074 for (j = 0; j < frame; j++)
3075 subprog[ret_prog[j]].tail_call_reachable = true;
3076
70a87ffe
AS
3077 /* end of for() loop means the last insn of the 'subprog'
3078 * was reached. Doesn't matter whether it was JA or EXIT
3079 */
3080 if (frame == 0)
3081 return 0;
9c8105bd 3082 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3083 frame--;
3084 i = ret_insn[frame];
9c8105bd 3085 idx = ret_prog[frame];
70a87ffe 3086 goto continue_func;
f4d7e40a
AS
3087}
3088
19d28fbd 3089#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3090static int get_callee_stack_depth(struct bpf_verifier_env *env,
3091 const struct bpf_insn *insn, int idx)
3092{
3093 int start = idx + insn->imm + 1, subprog;
3094
3095 subprog = find_subprog(env, start);
3096 if (subprog < 0) {
3097 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3098 start);
3099 return -EFAULT;
3100 }
9c8105bd 3101 return env->subprog_info[subprog].stack_depth;
1ea47e01 3102}
19d28fbd 3103#endif
1ea47e01 3104
51c39bb1
AS
3105int check_ctx_reg(struct bpf_verifier_env *env,
3106 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3107{
3108 /* Access to ctx or passing it to a helper is only allowed in
3109 * its original, unmodified form.
3110 */
3111
3112 if (reg->off) {
3113 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3114 regno, reg->off);
3115 return -EACCES;
3116 }
3117
3118 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3119 char tn_buf[48];
3120
3121 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3122 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3123 return -EACCES;
3124 }
3125
3126 return 0;
3127}
3128
afbf21dc
YS
3129static int __check_buffer_access(struct bpf_verifier_env *env,
3130 const char *buf_info,
3131 const struct bpf_reg_state *reg,
3132 int regno, int off, int size)
9df1c28b
MM
3133{
3134 if (off < 0) {
3135 verbose(env,
4fc00b79 3136 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3137 regno, buf_info, off, size);
9df1c28b
MM
3138 return -EACCES;
3139 }
3140 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3141 char tn_buf[48];
3142
3143 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3144 verbose(env,
4fc00b79 3145 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3146 regno, off, tn_buf);
3147 return -EACCES;
3148 }
afbf21dc
YS
3149
3150 return 0;
3151}
3152
3153static int check_tp_buffer_access(struct bpf_verifier_env *env,
3154 const struct bpf_reg_state *reg,
3155 int regno, int off, int size)
3156{
3157 int err;
3158
3159 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3160 if (err)
3161 return err;
3162
9df1c28b
MM
3163 if (off + size > env->prog->aux->max_tp_access)
3164 env->prog->aux->max_tp_access = off + size;
3165
3166 return 0;
3167}
3168
afbf21dc
YS
3169static int check_buffer_access(struct bpf_verifier_env *env,
3170 const struct bpf_reg_state *reg,
3171 int regno, int off, int size,
3172 bool zero_size_allowed,
3173 const char *buf_info,
3174 u32 *max_access)
3175{
3176 int err;
3177
3178 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3179 if (err)
3180 return err;
3181
3182 if (off + size > *max_access)
3183 *max_access = off + size;
3184
3185 return 0;
3186}
3187
3f50f132
JF
3188/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3189static void zext_32_to_64(struct bpf_reg_state *reg)
3190{
3191 reg->var_off = tnum_subreg(reg->var_off);
3192 __reg_assign_32_into_64(reg);
3193}
9df1c28b 3194
0c17d1d2
JH
3195/* truncate register to smaller size (in bytes)
3196 * must be called with size < BPF_REG_SIZE
3197 */
3198static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3199{
3200 u64 mask;
3201
3202 /* clear high bits in bit representation */
3203 reg->var_off = tnum_cast(reg->var_off, size);
3204
3205 /* fix arithmetic bounds */
3206 mask = ((u64)1 << (size * 8)) - 1;
3207 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3208 reg->umin_value &= mask;
3209 reg->umax_value &= mask;
3210 } else {
3211 reg->umin_value = 0;
3212 reg->umax_value = mask;
3213 }
3214 reg->smin_value = reg->umin_value;
3215 reg->smax_value = reg->umax_value;
3f50f132
JF
3216
3217 /* If size is smaller than 32bit register the 32bit register
3218 * values are also truncated so we push 64-bit bounds into
3219 * 32-bit bounds. Above were truncated < 32-bits already.
3220 */
3221 if (size >= 4)
3222 return;
3223 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3224}
3225
a23740ec
AN
3226static bool bpf_map_is_rdonly(const struct bpf_map *map)
3227{
3228 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3229}
3230
3231static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3232{
3233 void *ptr;
3234 u64 addr;
3235 int err;
3236
3237 err = map->ops->map_direct_value_addr(map, &addr, off);
3238 if (err)
3239 return err;
2dedd7d2 3240 ptr = (void *)(long)addr + off;
a23740ec
AN
3241
3242 switch (size) {
3243 case sizeof(u8):
3244 *val = (u64)*(u8 *)ptr;
3245 break;
3246 case sizeof(u16):
3247 *val = (u64)*(u16 *)ptr;
3248 break;
3249 case sizeof(u32):
3250 *val = (u64)*(u32 *)ptr;
3251 break;
3252 case sizeof(u64):
3253 *val = *(u64 *)ptr;
3254 break;
3255 default:
3256 return -EINVAL;
3257 }
3258 return 0;
3259}
3260
9e15db66
AS
3261static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3262 struct bpf_reg_state *regs,
3263 int regno, int off, int size,
3264 enum bpf_access_type atype,
3265 int value_regno)
3266{
3267 struct bpf_reg_state *reg = regs + regno;
3268 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3269 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3270 u32 btf_id;
3271 int ret;
3272
9e15db66
AS
3273 if (off < 0) {
3274 verbose(env,
3275 "R%d is ptr_%s invalid negative access: off=%d\n",
3276 regno, tname, off);
3277 return -EACCES;
3278 }
3279 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3280 char tn_buf[48];
3281
3282 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3283 verbose(env,
3284 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3285 regno, tname, off, tn_buf);
3286 return -EACCES;
3287 }
3288
27ae7997
MKL
3289 if (env->ops->btf_struct_access) {
3290 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3291 atype, &btf_id);
3292 } else {
3293 if (atype != BPF_READ) {
3294 verbose(env, "only read is supported\n");
3295 return -EACCES;
3296 }
3297
3298 ret = btf_struct_access(&env->log, t, off, size, atype,
3299 &btf_id);
3300 }
3301
9e15db66
AS
3302 if (ret < 0)
3303 return ret;
3304
41c48f3a
AI
3305 if (atype == BPF_READ && value_regno >= 0)
3306 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3307
3308 return 0;
3309}
3310
3311static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3312 struct bpf_reg_state *regs,
3313 int regno, int off, int size,
3314 enum bpf_access_type atype,
3315 int value_regno)
3316{
3317 struct bpf_reg_state *reg = regs + regno;
3318 struct bpf_map *map = reg->map_ptr;
3319 const struct btf_type *t;
3320 const char *tname;
3321 u32 btf_id;
3322 int ret;
3323
3324 if (!btf_vmlinux) {
3325 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3326 return -ENOTSUPP;
3327 }
3328
3329 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3330 verbose(env, "map_ptr access not supported for map type %d\n",
3331 map->map_type);
3332 return -ENOTSUPP;
3333 }
3334
3335 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3336 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3337
3338 if (!env->allow_ptr_to_map_access) {
3339 verbose(env,
3340 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3341 tname);
3342 return -EPERM;
9e15db66 3343 }
27ae7997 3344
41c48f3a
AI
3345 if (off < 0) {
3346 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3347 regno, tname, off);
3348 return -EACCES;
3349 }
3350
3351 if (atype != BPF_READ) {
3352 verbose(env, "only read from %s is supported\n", tname);
3353 return -EACCES;
3354 }
3355
3356 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3357 if (ret < 0)
3358 return ret;
3359
3360 if (value_regno >= 0)
3361 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3362
9e15db66
AS
3363 return 0;
3364}
3365
41c48f3a 3366
17a52670
AS
3367/* check whether memory at (regno + off) is accessible for t = (read | write)
3368 * if t==write, value_regno is a register which value is stored into memory
3369 * if t==read, value_regno is a register which will receive the value from memory
3370 * if t==write && value_regno==-1, some unknown value is stored into memory
3371 * if t==read && value_regno==-1, don't care what we read from memory
3372 */
ca369602
DB
3373static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3374 int off, int bpf_size, enum bpf_access_type t,
3375 int value_regno, bool strict_alignment_once)
17a52670 3376{
638f5b90
AS
3377 struct bpf_reg_state *regs = cur_regs(env);
3378 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3379 struct bpf_func_state *state;
17a52670
AS
3380 int size, err = 0;
3381
3382 size = bpf_size_to_bytes(bpf_size);
3383 if (size < 0)
3384 return size;
3385
f1174f77 3386 /* alignment checks will add in reg->off themselves */
ca369602 3387 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3388 if (err)
3389 return err;
17a52670 3390
f1174f77
EC
3391 /* for access checks, reg->off is just part of off */
3392 off += reg->off;
3393
3394 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3395 if (t == BPF_WRITE && value_regno >= 0 &&
3396 is_pointer_value(env, value_regno)) {
61bd5218 3397 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3398 return -EACCES;
3399 }
591fe988
DB
3400 err = check_map_access_type(env, regno, off, size, t);
3401 if (err)
3402 return err;
9fd29c08 3403 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3404 if (!err && t == BPF_READ && value_regno >= 0) {
3405 struct bpf_map *map = reg->map_ptr;
3406
3407 /* if map is read-only, track its contents as scalars */
3408 if (tnum_is_const(reg->var_off) &&
3409 bpf_map_is_rdonly(map) &&
3410 map->ops->map_direct_value_addr) {
3411 int map_off = off + reg->var_off.value;
3412 u64 val = 0;
3413
3414 err = bpf_map_direct_read(map, map_off, size,
3415 &val);
3416 if (err)
3417 return err;
3418
3419 regs[value_regno].type = SCALAR_VALUE;
3420 __mark_reg_known(&regs[value_regno], val);
3421 } else {
3422 mark_reg_unknown(env, regs, value_regno);
3423 }
3424 }
457f4436
AN
3425 } else if (reg->type == PTR_TO_MEM) {
3426 if (t == BPF_WRITE && value_regno >= 0 &&
3427 is_pointer_value(env, value_regno)) {
3428 verbose(env, "R%d leaks addr into mem\n", value_regno);
3429 return -EACCES;
3430 }
3431 err = check_mem_region_access(env, regno, off, size,
3432 reg->mem_size, false);
3433 if (!err && t == BPF_READ && value_regno >= 0)
3434 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3435 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3436 enum bpf_reg_type reg_type = SCALAR_VALUE;
9e15db66 3437 u32 btf_id = 0;
19de99f7 3438
1be7f75d
AS
3439 if (t == BPF_WRITE && value_regno >= 0 &&
3440 is_pointer_value(env, value_regno)) {
61bd5218 3441 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3442 return -EACCES;
3443 }
f1174f77 3444
58990d1f
DB
3445 err = check_ctx_reg(env, reg, regno);
3446 if (err < 0)
3447 return err;
3448
9e15db66
AS
3449 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3450 if (err)
3451 verbose_linfo(env, insn_idx, "; ");
969bf05e 3452 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3453 /* ctx access returns either a scalar, or a
de8f3a83
DB
3454 * PTR_TO_PACKET[_META,_END]. In the latter
3455 * case, we know the offset is zero.
f1174f77 3456 */
46f8bc92 3457 if (reg_type == SCALAR_VALUE) {
638f5b90 3458 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3459 } else {
638f5b90 3460 mark_reg_known_zero(env, regs,
61bd5218 3461 value_regno);
46f8bc92
MKL
3462 if (reg_type_may_be_null(reg_type))
3463 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3464 /* A load of ctx field could have different
3465 * actual load size with the one encoded in the
3466 * insn. When the dst is PTR, it is for sure not
3467 * a sub-register.
3468 */
3469 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341
YS
3470 if (reg_type == PTR_TO_BTF_ID ||
3471 reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66 3472 regs[value_regno].btf_id = btf_id;
46f8bc92 3473 }
638f5b90 3474 regs[value_regno].type = reg_type;
969bf05e 3475 }
17a52670 3476
f1174f77 3477 } else if (reg->type == PTR_TO_STACK) {
f1174f77 3478 off += reg->var_off.value;
e4298d25
DB
3479 err = check_stack_access(env, reg, off, size);
3480 if (err)
3481 return err;
8726679a 3482
f4d7e40a
AS
3483 state = func(env, reg);
3484 err = update_stack_depth(env, state, off);
3485 if (err)
3486 return err;
8726679a 3487
638f5b90 3488 if (t == BPF_WRITE)
61bd5218 3489 err = check_stack_write(env, state, off, size,
af86ca4e 3490 value_regno, insn_idx);
638f5b90 3491 else
61bd5218
JK
3492 err = check_stack_read(env, state, off, size,
3493 value_regno);
de8f3a83 3494 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 3495 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 3496 verbose(env, "cannot write into packet\n");
969bf05e
AS
3497 return -EACCES;
3498 }
4acf6c0b
BB
3499 if (t == BPF_WRITE && value_regno >= 0 &&
3500 is_pointer_value(env, value_regno)) {
61bd5218
JK
3501 verbose(env, "R%d leaks addr into packet\n",
3502 value_regno);
4acf6c0b
BB
3503 return -EACCES;
3504 }
9fd29c08 3505 err = check_packet_access(env, regno, off, size, false);
969bf05e 3506 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 3507 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
3508 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3509 if (t == BPF_WRITE && value_regno >= 0 &&
3510 is_pointer_value(env, value_regno)) {
3511 verbose(env, "R%d leaks addr into flow keys\n",
3512 value_regno);
3513 return -EACCES;
3514 }
3515
3516 err = check_flow_keys_access(env, off, size);
3517 if (!err && t == BPF_READ && value_regno >= 0)
3518 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3519 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 3520 if (t == BPF_WRITE) {
46f8bc92
MKL
3521 verbose(env, "R%d cannot write into %s\n",
3522 regno, reg_type_str[reg->type]);
c64b7983
JS
3523 return -EACCES;
3524 }
5f456649 3525 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
3526 if (!err && value_regno >= 0)
3527 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
3528 } else if (reg->type == PTR_TO_TP_BUFFER) {
3529 err = check_tp_buffer_access(env, reg, regno, off, size);
3530 if (!err && t == BPF_READ && value_regno >= 0)
3531 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
3532 } else if (reg->type == PTR_TO_BTF_ID) {
3533 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3534 value_regno);
41c48f3a
AI
3535 } else if (reg->type == CONST_PTR_TO_MAP) {
3536 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3537 value_regno);
afbf21dc
YS
3538 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3539 if (t == BPF_WRITE) {
3540 verbose(env, "R%d cannot write into %s\n",
3541 regno, reg_type_str[reg->type]);
3542 return -EACCES;
3543 }
f6dfbe31
CIK
3544 err = check_buffer_access(env, reg, regno, off, size, false,
3545 "rdonly",
afbf21dc
YS
3546 &env->prog->aux->max_rdonly_access);
3547 if (!err && value_regno >= 0)
3548 mark_reg_unknown(env, regs, value_regno);
3549 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
3550 err = check_buffer_access(env, reg, regno, off, size, false,
3551 "rdwr",
afbf21dc
YS
3552 &env->prog->aux->max_rdwr_access);
3553 if (!err && t == BPF_READ && value_regno >= 0)
3554 mark_reg_unknown(env, regs, value_regno);
17a52670 3555 } else {
61bd5218
JK
3556 verbose(env, "R%d invalid mem access '%s'\n", regno,
3557 reg_type_str[reg->type]);
17a52670
AS
3558 return -EACCES;
3559 }
969bf05e 3560
f1174f77 3561 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 3562 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 3563 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 3564 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 3565 }
17a52670
AS
3566 return err;
3567}
3568
31fd8581 3569static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 3570{
17a52670
AS
3571 int err;
3572
3573 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3574 insn->imm != 0) {
61bd5218 3575 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
3576 return -EINVAL;
3577 }
3578
3579 /* check src1 operand */
dc503a8a 3580 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3581 if (err)
3582 return err;
3583
3584 /* check src2 operand */
dc503a8a 3585 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3586 if (err)
3587 return err;
3588
6bdf6abc 3589 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 3590 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
3591 return -EACCES;
3592 }
3593
ca369602 3594 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 3595 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
3596 is_flow_key_reg(env, insn->dst_reg) ||
3597 is_sk_reg(env, insn->dst_reg)) {
ca369602 3598 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2a159c6f
DB
3599 insn->dst_reg,
3600 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
3601 return -EACCES;
3602 }
3603
17a52670 3604 /* check whether atomic_add can read the memory */
31fd8581 3605 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3606 BPF_SIZE(insn->code), BPF_READ, -1, true);
17a52670
AS
3607 if (err)
3608 return err;
3609
3610 /* check whether atomic_add can write into the same memory */
31fd8581 3611 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3612 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
17a52670
AS
3613}
3614
2011fccf
AI
3615static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3616 int off, int access_size,
3617 bool zero_size_allowed)
3618{
3619 struct bpf_reg_state *reg = reg_state(env, regno);
3620
3621 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3622 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3623 if (tnum_is_const(reg->var_off)) {
3624 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3625 regno, off, access_size);
3626 } else {
3627 char tn_buf[48];
3628
3629 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3630 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3631 regno, tn_buf, access_size);
3632 }
3633 return -EACCES;
3634 }
3635 return 0;
3636}
3637
17a52670
AS
3638/* when register 'regno' is passed into function that will read 'access_size'
3639 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
3640 * and all elements of stack are initialized.
3641 * Unlike most pointer bounds-checking functions, this one doesn't take an
3642 * 'off' argument, so it has to add in reg->off itself.
17a52670 3643 */
58e2af8b 3644static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
3645 int access_size, bool zero_size_allowed,
3646 struct bpf_call_arg_meta *meta)
17a52670 3647{
2a159c6f 3648 struct bpf_reg_state *reg = reg_state(env, regno);
f4d7e40a 3649 struct bpf_func_state *state = func(env, reg);
f7cf25b2 3650 int err, min_off, max_off, i, j, slot, spi;
17a52670 3651
2011fccf
AI
3652 if (tnum_is_const(reg->var_off)) {
3653 min_off = max_off = reg->var_off.value + reg->off;
3654 err = __check_stack_boundary(env, regno, min_off, access_size,
3655 zero_size_allowed);
3656 if (err)
3657 return err;
3658 } else {
088ec26d
AI
3659 /* Variable offset is prohibited for unprivileged mode for
3660 * simplicity since it requires corresponding support in
3661 * Spectre masking for stack ALU.
3662 * See also retrieve_ptr_limit().
3663 */
2c78ee89 3664 if (!env->bypass_spec_v1) {
088ec26d 3665 char tn_buf[48];
f1174f77 3666
088ec26d
AI
3667 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3668 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3669 regno, tn_buf);
3670 return -EACCES;
3671 }
f2bcd05e
AI
3672 /* Only initialized buffer on stack is allowed to be accessed
3673 * with variable offset. With uninitialized buffer it's hard to
3674 * guarantee that whole memory is marked as initialized on
3675 * helper return since specific bounds are unknown what may
3676 * cause uninitialized stack leaking.
3677 */
3678 if (meta && meta->raw_mode)
3679 meta = NULL;
3680
107c26a7
AI
3681 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3682 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3683 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3684 regno);
3685 return -EACCES;
3686 }
2011fccf 3687 min_off = reg->smin_value + reg->off;
107c26a7 3688 max_off = reg->smax_value + reg->off;
2011fccf
AI
3689 err = __check_stack_boundary(env, regno, min_off, access_size,
3690 zero_size_allowed);
107c26a7
AI
3691 if (err) {
3692 verbose(env, "R%d min value is outside of stack bound\n",
3693 regno);
2011fccf 3694 return err;
107c26a7 3695 }
2011fccf
AI
3696 err = __check_stack_boundary(env, regno, max_off, access_size,
3697 zero_size_allowed);
107c26a7
AI
3698 if (err) {
3699 verbose(env, "R%d max value is outside of stack bound\n",
3700 regno);
2011fccf 3701 return err;
107c26a7 3702 }
17a52670
AS
3703 }
3704
435faee1
DB
3705 if (meta && meta->raw_mode) {
3706 meta->access_size = access_size;
3707 meta->regno = regno;
3708 return 0;
3709 }
3710
2011fccf 3711 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
3712 u8 *stype;
3713
2011fccf 3714 slot = -i - 1;
638f5b90 3715 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
3716 if (state->allocated_stack <= slot)
3717 goto err;
3718 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3719 if (*stype == STACK_MISC)
3720 goto mark;
3721 if (*stype == STACK_ZERO) {
3722 /* helper can write anything into the stack */
3723 *stype = STACK_MISC;
3724 goto mark;
17a52670 3725 }
1d68f22b
YS
3726
3727 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3728 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3729 goto mark;
3730
f7cf25b2
AS
3731 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3732 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
f54c7898 3733 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
f7cf25b2
AS
3734 for (j = 0; j < BPF_REG_SIZE; j++)
3735 state->stack[spi].slot_type[j] = STACK_MISC;
3736 goto mark;
3737 }
3738
cc2b14d5 3739err:
2011fccf
AI
3740 if (tnum_is_const(reg->var_off)) {
3741 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3742 min_off, i - min_off, access_size);
3743 } else {
3744 char tn_buf[48];
3745
3746 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3747 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3748 tn_buf, i - min_off, access_size);
3749 }
cc2b14d5
AS
3750 return -EACCES;
3751mark:
3752 /* reading any byte out of 8-byte 'spill_slot' will cause
3753 * the whole slot to be marked as 'read'
3754 */
679c782d 3755 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
3756 state->stack[spi].spilled_ptr.parent,
3757 REG_LIVE_READ64);
17a52670 3758 }
2011fccf 3759 return update_stack_depth(env, state, min_off);
17a52670
AS
3760}
3761
06c1c049
GB
3762static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3763 int access_size, bool zero_size_allowed,
3764 struct bpf_call_arg_meta *meta)
3765{
638f5b90 3766 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 3767
f1174f77 3768 switch (reg->type) {
06c1c049 3769 case PTR_TO_PACKET:
de8f3a83 3770 case PTR_TO_PACKET_META:
9fd29c08
YS
3771 return check_packet_access(env, regno, reg->off, access_size,
3772 zero_size_allowed);
06c1c049 3773 case PTR_TO_MAP_VALUE:
591fe988
DB
3774 if (check_map_access_type(env, regno, reg->off, access_size,
3775 meta && meta->raw_mode ? BPF_WRITE :
3776 BPF_READ))
3777 return -EACCES;
9fd29c08
YS
3778 return check_map_access(env, regno, reg->off, access_size,
3779 zero_size_allowed);
457f4436
AN
3780 case PTR_TO_MEM:
3781 return check_mem_region_access(env, regno, reg->off,
3782 access_size, reg->mem_size,
3783 zero_size_allowed);
afbf21dc
YS
3784 case PTR_TO_RDONLY_BUF:
3785 if (meta && meta->raw_mode)
3786 return -EACCES;
3787 return check_buffer_access(env, reg, regno, reg->off,
3788 access_size, zero_size_allowed,
3789 "rdonly",
3790 &env->prog->aux->max_rdonly_access);
3791 case PTR_TO_RDWR_BUF:
3792 return check_buffer_access(env, reg, regno, reg->off,
3793 access_size, zero_size_allowed,
3794 "rdwr",
3795 &env->prog->aux->max_rdwr_access);
0d004c02 3796 case PTR_TO_STACK:
06c1c049
GB
3797 return check_stack_boundary(env, regno, access_size,
3798 zero_size_allowed, meta);
0d004c02
LB
3799 default: /* scalar_value or invalid ptr */
3800 /* Allow zero-byte read from NULL, regardless of pointer type */
3801 if (zero_size_allowed && access_size == 0 &&
3802 register_is_null(reg))
3803 return 0;
3804
3805 verbose(env, "R%d type=%s expected=%s\n", regno,
3806 reg_type_str[reg->type],
3807 reg_type_str[PTR_TO_STACK]);
3808 return -EACCES;
06c1c049
GB
3809 }
3810}
3811
d83525ca
AS
3812/* Implementation details:
3813 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3814 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3815 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3816 * value_or_null->value transition, since the verifier only cares about
3817 * the range of access to valid map value pointer and doesn't care about actual
3818 * address of the map element.
3819 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3820 * reg->id > 0 after value_or_null->value transition. By doing so
3821 * two bpf_map_lookups will be considered two different pointers that
3822 * point to different bpf_spin_locks.
3823 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3824 * dead-locks.
3825 * Since only one bpf_spin_lock is allowed the checks are simpler than
3826 * reg_is_refcounted() logic. The verifier needs to remember only
3827 * one spin_lock instead of array of acquired_refs.
3828 * cur_state->active_spin_lock remembers which map value element got locked
3829 * and clears it after bpf_spin_unlock.
3830 */
3831static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3832 bool is_lock)
3833{
3834 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3835 struct bpf_verifier_state *cur = env->cur_state;
3836 bool is_const = tnum_is_const(reg->var_off);
3837 struct bpf_map *map = reg->map_ptr;
3838 u64 val = reg->var_off.value;
3839
d83525ca
AS
3840 if (!is_const) {
3841 verbose(env,
3842 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3843 regno);
3844 return -EINVAL;
3845 }
3846 if (!map->btf) {
3847 verbose(env,
3848 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3849 map->name);
3850 return -EINVAL;
3851 }
3852 if (!map_value_has_spin_lock(map)) {
3853 if (map->spin_lock_off == -E2BIG)
3854 verbose(env,
3855 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3856 map->name);
3857 else if (map->spin_lock_off == -ENOENT)
3858 verbose(env,
3859 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3860 map->name);
3861 else
3862 verbose(env,
3863 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3864 map->name);
3865 return -EINVAL;
3866 }
3867 if (map->spin_lock_off != val + reg->off) {
3868 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3869 val + reg->off);
3870 return -EINVAL;
3871 }
3872 if (is_lock) {
3873 if (cur->active_spin_lock) {
3874 verbose(env,
3875 "Locking two bpf_spin_locks are not allowed\n");
3876 return -EINVAL;
3877 }
3878 cur->active_spin_lock = reg->id;
3879 } else {
3880 if (!cur->active_spin_lock) {
3881 verbose(env, "bpf_spin_unlock without taking a lock\n");
3882 return -EINVAL;
3883 }
3884 if (cur->active_spin_lock != reg->id) {
3885 verbose(env, "bpf_spin_unlock of different lock\n");
3886 return -EINVAL;
3887 }
3888 cur->active_spin_lock = 0;
3889 }
3890 return 0;
3891}
3892
90133415
DB
3893static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3894{
3895 return type == ARG_PTR_TO_MEM ||
3896 type == ARG_PTR_TO_MEM_OR_NULL ||
3897 type == ARG_PTR_TO_UNINIT_MEM;
3898}
3899
3900static bool arg_type_is_mem_size(enum bpf_arg_type type)
3901{
3902 return type == ARG_CONST_SIZE ||
3903 type == ARG_CONST_SIZE_OR_ZERO;
3904}
3905
457f4436
AN
3906static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3907{
3908 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3909}
3910
57c3bb72
AI
3911static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3912{
3913 return type == ARG_PTR_TO_INT ||
3914 type == ARG_PTR_TO_LONG;
3915}
3916
3917static int int_ptr_type_to_size(enum bpf_arg_type type)
3918{
3919 if (type == ARG_PTR_TO_INT)
3920 return sizeof(u32);
3921 else if (type == ARG_PTR_TO_LONG)
3922 return sizeof(u64);
3923
3924 return -EINVAL;
3925}
3926
912f442c
LB
3927static int resolve_map_arg_type(struct bpf_verifier_env *env,
3928 const struct bpf_call_arg_meta *meta,
3929 enum bpf_arg_type *arg_type)
3930{
3931 if (!meta->map_ptr) {
3932 /* kernel subsystem misconfigured verifier */
3933 verbose(env, "invalid map_ptr to access map->type\n");
3934 return -EACCES;
3935 }
3936
3937 switch (meta->map_ptr->map_type) {
3938 case BPF_MAP_TYPE_SOCKMAP:
3939 case BPF_MAP_TYPE_SOCKHASH:
3940 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
3941 *arg_type = ARG_PTR_TO_SOCKET;
3942 } else {
3943 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3944 return -EINVAL;
3945 }
3946 break;
3947
3948 default:
3949 break;
3950 }
3951 return 0;
3952}
3953
f79e7ea5
LB
3954struct bpf_reg_types {
3955 const enum bpf_reg_type types[10];
3956};
3957
3958static const struct bpf_reg_types map_key_value_types = {
3959 .types = {
3960 PTR_TO_STACK,
3961 PTR_TO_PACKET,
3962 PTR_TO_PACKET_META,
3963 PTR_TO_MAP_VALUE,
3964 },
3965};
3966
3967static const struct bpf_reg_types sock_types = {
3968 .types = {
3969 PTR_TO_SOCK_COMMON,
3970 PTR_TO_SOCKET,
3971 PTR_TO_TCP_SOCK,
3972 PTR_TO_XDP_SOCK,
3973 },
3974};
3975
3976static const struct bpf_reg_types mem_types = {
3977 .types = {
3978 PTR_TO_STACK,
3979 PTR_TO_PACKET,
3980 PTR_TO_PACKET_META,
3981 PTR_TO_MAP_VALUE,
3982 PTR_TO_MEM,
3983 PTR_TO_RDONLY_BUF,
3984 PTR_TO_RDWR_BUF,
3985 },
3986};
3987
3988static const struct bpf_reg_types int_ptr_types = {
3989 .types = {
3990 PTR_TO_STACK,
3991 PTR_TO_PACKET,
3992 PTR_TO_PACKET_META,
3993 PTR_TO_MAP_VALUE,
3994 },
3995};
3996
3997static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
3998static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
3999static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4000static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4001static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4002static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4003static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4004
0789e13b 4005static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4006 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4007 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4008 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4009 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4010 [ARG_CONST_SIZE] = &scalar_types,
4011 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4012 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4013 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4014 [ARG_PTR_TO_CTX] = &context_types,
4015 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4016 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4017 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4018 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4019 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4020 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4021 [ARG_PTR_TO_MEM] = &mem_types,
4022 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4023 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4024 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4025 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4026 [ARG_PTR_TO_INT] = &int_ptr_types,
4027 [ARG_PTR_TO_LONG] = &int_ptr_types,
f79e7ea5
LB
4028};
4029
4030static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4031 const struct bpf_reg_types *compatible)
4032{
4033 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4034 enum bpf_reg_type expected, type = reg->type;
4035 int i, j;
4036
4037 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4038 expected = compatible->types[i];
4039 if (expected == NOT_INIT)
4040 break;
4041
4042 if (type == expected)
4043 return 0;
4044 }
4045
4046 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4047 for (j = 0; j + 1 < i; j++)
4048 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4049 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4050 return -EACCES;
4051}
4052
af7ec138
YS
4053static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4054 struct bpf_call_arg_meta *meta,
4055 const struct bpf_func_proto *fn)
17a52670 4056{
af7ec138 4057 u32 regno = BPF_REG_1 + arg;
638f5b90 4058 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4059 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5
LB
4060 const struct bpf_reg_types *compatible;
4061 enum bpf_reg_type type = reg->type;
17a52670
AS
4062 int err = 0;
4063
80f1d68c 4064 if (arg_type == ARG_DONTCARE)
17a52670
AS
4065 return 0;
4066
dc503a8a
EC
4067 err = check_reg_arg(env, regno, SRC_OP);
4068 if (err)
4069 return err;
17a52670 4070
1be7f75d
AS
4071 if (arg_type == ARG_ANYTHING) {
4072 if (is_pointer_value(env, regno)) {
61bd5218
JK
4073 verbose(env, "R%d leaks addr into helper function\n",
4074 regno);
1be7f75d
AS
4075 return -EACCES;
4076 }
80f1d68c 4077 return 0;
1be7f75d 4078 }
80f1d68c 4079
de8f3a83 4080 if (type_is_pkt_pointer(type) &&
3a0af8fd 4081 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4082 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4083 return -EACCES;
4084 }
4085
912f442c
LB
4086 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4087 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4088 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4089 err = resolve_map_arg_type(env, meta, &arg_type);
4090 if (err)
4091 return err;
4092 }
4093
fd1b0d60
LB
4094 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4095 /* A NULL register has a SCALAR_VALUE type, so skip
4096 * type checking.
4097 */
4098 goto skip_type_check;
4099
f79e7ea5
LB
4100 compatible = compatible_reg_types[arg_type];
4101 if (!compatible) {
4102 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
17a52670
AS
4103 return -EFAULT;
4104 }
4105
f79e7ea5
LB
4106 err = check_reg_type(env, regno, compatible);
4107 if (err)
4108 return err;
4109
d7b9454a
LB
4110 if (type == PTR_TO_BTF_ID) {
4111 const u32 *btf_id = fn->arg_btf_id[arg];
4112
4113 if (!btf_id) {
4114 verbose(env, "verifier internal error: missing BTF ID\n");
4115 return -EFAULT;
f318903c 4116 }
a7658e1a 4117
d7b9454a
LB
4118 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id, *btf_id)) {
4119 verbose(env, "R%d is of type %s but %s is expected\n",
4120 regno, kernel_type_name(reg->btf_id), kernel_type_name(*btf_id));
a7658e1a
AS
4121 return -EACCES;
4122 }
d7b9454a 4123 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
a7658e1a
AS
4124 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4125 regno);
4126 return -EACCES;
4127 }
feec7040
LB
4128 } else if (type == PTR_TO_CTX) {
4129 err = check_ctx_reg(env, reg, regno);
4130 if (err < 0)
4131 return err;
d7b9454a
LB
4132 }
4133
fd1b0d60 4134skip_type_check:
02f7c958 4135 if (reg->ref_obj_id) {
457f4436
AN
4136 if (meta->ref_obj_id) {
4137 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4138 regno, reg->ref_obj_id,
4139 meta->ref_obj_id);
4140 return -EFAULT;
4141 }
4142 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4143 }
4144
17a52670
AS
4145 if (arg_type == ARG_CONST_MAP_PTR) {
4146 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4147 meta->map_ptr = reg->map_ptr;
17a52670
AS
4148 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4149 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4150 * check that [key, key + map->key_size) are within
4151 * stack limits and initialized
4152 */
33ff9823 4153 if (!meta->map_ptr) {
17a52670
AS
4154 /* in function declaration map_ptr must come before
4155 * map_key, so that it's verified and known before
4156 * we have to check map_key here. Otherwise it means
4157 * that kernel subsystem misconfigured verifier
4158 */
61bd5218 4159 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4160 return -EACCES;
4161 }
d71962f3
PC
4162 err = check_helper_mem_access(env, regno,
4163 meta->map_ptr->key_size, false,
4164 NULL);
2ea864c5 4165 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4166 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4167 !register_is_null(reg)) ||
2ea864c5 4168 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4169 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4170 * check [value, value + map->value_size) validity
4171 */
33ff9823 4172 if (!meta->map_ptr) {
17a52670 4173 /* kernel subsystem misconfigured verifier */
61bd5218 4174 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4175 return -EACCES;
4176 }
2ea864c5 4177 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4178 err = check_helper_mem_access(env, regno,
4179 meta->map_ptr->value_size, false,
2ea864c5 4180 meta);
c18f0b6a
LB
4181 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4182 if (meta->func_id == BPF_FUNC_spin_lock) {
4183 if (process_spin_lock(env, regno, true))
4184 return -EACCES;
4185 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4186 if (process_spin_lock(env, regno, false))
4187 return -EACCES;
4188 } else {
4189 verbose(env, "verifier internal error\n");
4190 return -EFAULT;
4191 }
a2bbe7cc
LB
4192 } else if (arg_type_is_mem_ptr(arg_type)) {
4193 /* The access to this pointer is only checked when we hit the
4194 * next is_mem_size argument below.
4195 */
4196 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 4197 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4198 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4199
10060503
JF
4200 /* This is used to refine r0 return value bounds for helpers
4201 * that enforce this value as an upper bound on return values.
4202 * See do_refine_retval_range() for helpers that can refine
4203 * the return value. C type of helper is u32 so we pull register
4204 * bound from umax_value however, if negative verifier errors
4205 * out. Only upper bounds can be learned because retval is an
4206 * int type and negative retvals are allowed.
849fa506 4207 */
10060503 4208 meta->msize_max_value = reg->umax_value;
849fa506 4209
f1174f77
EC
4210 /* The register is SCALAR_VALUE; the access check
4211 * happens using its boundaries.
06c1c049 4212 */
f1174f77 4213 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4214 /* For unprivileged variable accesses, disable raw
4215 * mode so that the program is required to
4216 * initialize all the memory that the helper could
4217 * just partially fill up.
4218 */
4219 meta = NULL;
4220
b03c9f9f 4221 if (reg->smin_value < 0) {
61bd5218 4222 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4223 regno);
4224 return -EACCES;
4225 }
06c1c049 4226
b03c9f9f 4227 if (reg->umin_value == 0) {
f1174f77
EC
4228 err = check_helper_mem_access(env, regno - 1, 0,
4229 zero_size_allowed,
4230 meta);
06c1c049
GB
4231 if (err)
4232 return err;
06c1c049 4233 }
f1174f77 4234
b03c9f9f 4235 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4236 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4237 regno);
4238 return -EACCES;
4239 }
4240 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4241 reg->umax_value,
f1174f77 4242 zero_size_allowed, meta);
b5dc0163
AS
4243 if (!err)
4244 err = mark_chain_precision(env, regno);
457f4436
AN
4245 } else if (arg_type_is_alloc_size(arg_type)) {
4246 if (!tnum_is_const(reg->var_off)) {
4247 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4248 regno);
4249 return -EACCES;
4250 }
4251 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4252 } else if (arg_type_is_int_ptr(arg_type)) {
4253 int size = int_ptr_type_to_size(arg_type);
4254
4255 err = check_helper_mem_access(env, regno, size, false, meta);
4256 if (err)
4257 return err;
4258 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4259 }
4260
4261 return err;
4262}
4263
0126240f
LB
4264static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4265{
4266 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4267 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4268
4269 if (func_id != BPF_FUNC_map_update_elem)
4270 return false;
4271
4272 /* It's not possible to get access to a locked struct sock in these
4273 * contexts, so updating is safe.
4274 */
4275 switch (type) {
4276 case BPF_PROG_TYPE_TRACING:
4277 if (eatype == BPF_TRACE_ITER)
4278 return true;
4279 break;
4280 case BPF_PROG_TYPE_SOCKET_FILTER:
4281 case BPF_PROG_TYPE_SCHED_CLS:
4282 case BPF_PROG_TYPE_SCHED_ACT:
4283 case BPF_PROG_TYPE_XDP:
4284 case BPF_PROG_TYPE_SK_REUSEPORT:
4285 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4286 case BPF_PROG_TYPE_SK_LOOKUP:
4287 return true;
4288 default:
4289 break;
4290 }
4291
4292 verbose(env, "cannot update sockmap in this context\n");
4293 return false;
4294}
4295
e411901c
MF
4296static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4297{
4298 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4299}
4300
61bd5218
JK
4301static int check_map_func_compatibility(struct bpf_verifier_env *env,
4302 struct bpf_map *map, int func_id)
35578d79 4303{
35578d79
KX
4304 if (!map)
4305 return 0;
4306
6aff67c8
AS
4307 /* We need a two way check, first is from map perspective ... */
4308 switch (map->map_type) {
4309 case BPF_MAP_TYPE_PROG_ARRAY:
4310 if (func_id != BPF_FUNC_tail_call)
4311 goto error;
4312 break;
4313 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4314 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4315 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4316 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4317 func_id != BPF_FUNC_perf_event_read_value &&
4318 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4319 goto error;
4320 break;
457f4436
AN
4321 case BPF_MAP_TYPE_RINGBUF:
4322 if (func_id != BPF_FUNC_ringbuf_output &&
4323 func_id != BPF_FUNC_ringbuf_reserve &&
4324 func_id != BPF_FUNC_ringbuf_submit &&
4325 func_id != BPF_FUNC_ringbuf_discard &&
4326 func_id != BPF_FUNC_ringbuf_query)
4327 goto error;
4328 break;
6aff67c8
AS
4329 case BPF_MAP_TYPE_STACK_TRACE:
4330 if (func_id != BPF_FUNC_get_stackid)
4331 goto error;
4332 break;
4ed8ec52 4333 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4334 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4335 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4336 goto error;
4337 break;
cd339431 4338 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4339 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4340 if (func_id != BPF_FUNC_get_local_storage)
4341 goto error;
4342 break;
546ac1ff 4343 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4344 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4345 if (func_id != BPF_FUNC_redirect_map &&
4346 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4347 goto error;
4348 break;
fbfc504a
BT
4349 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4350 * appear.
4351 */
6710e112
JDB
4352 case BPF_MAP_TYPE_CPUMAP:
4353 if (func_id != BPF_FUNC_redirect_map)
4354 goto error;
4355 break;
fada7fdc
JL
4356 case BPF_MAP_TYPE_XSKMAP:
4357 if (func_id != BPF_FUNC_redirect_map &&
4358 func_id != BPF_FUNC_map_lookup_elem)
4359 goto error;
4360 break;
56f668df 4361 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4362 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4363 if (func_id != BPF_FUNC_map_lookup_elem)
4364 goto error;
16a43625 4365 break;
174a79ff
JF
4366 case BPF_MAP_TYPE_SOCKMAP:
4367 if (func_id != BPF_FUNC_sk_redirect_map &&
4368 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4369 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4370 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4371 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4372 func_id != BPF_FUNC_map_lookup_elem &&
4373 !may_update_sockmap(env, func_id))
174a79ff
JF
4374 goto error;
4375 break;
81110384
JF
4376 case BPF_MAP_TYPE_SOCKHASH:
4377 if (func_id != BPF_FUNC_sk_redirect_hash &&
4378 func_id != BPF_FUNC_sock_hash_update &&
4379 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4380 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 4381 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4382 func_id != BPF_FUNC_map_lookup_elem &&
4383 !may_update_sockmap(env, func_id))
81110384
JF
4384 goto error;
4385 break;
2dbb9b9e
MKL
4386 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4387 if (func_id != BPF_FUNC_sk_select_reuseport)
4388 goto error;
4389 break;
f1a2e44a
MV
4390 case BPF_MAP_TYPE_QUEUE:
4391 case BPF_MAP_TYPE_STACK:
4392 if (func_id != BPF_FUNC_map_peek_elem &&
4393 func_id != BPF_FUNC_map_pop_elem &&
4394 func_id != BPF_FUNC_map_push_elem)
4395 goto error;
4396 break;
6ac99e8f
MKL
4397 case BPF_MAP_TYPE_SK_STORAGE:
4398 if (func_id != BPF_FUNC_sk_storage_get &&
4399 func_id != BPF_FUNC_sk_storage_delete)
4400 goto error;
4401 break;
8ea63684
KS
4402 case BPF_MAP_TYPE_INODE_STORAGE:
4403 if (func_id != BPF_FUNC_inode_storage_get &&
4404 func_id != BPF_FUNC_inode_storage_delete)
4405 goto error;
4406 break;
6aff67c8
AS
4407 default:
4408 break;
4409 }
4410
4411 /* ... and second from the function itself. */
4412 switch (func_id) {
4413 case BPF_FUNC_tail_call:
4414 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4415 goto error;
e411901c
MF
4416 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4417 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
4418 return -EINVAL;
4419 }
6aff67c8
AS
4420 break;
4421 case BPF_FUNC_perf_event_read:
4422 case BPF_FUNC_perf_event_output:
908432ca 4423 case BPF_FUNC_perf_event_read_value:
a7658e1a 4424 case BPF_FUNC_skb_output:
d831ee84 4425 case BPF_FUNC_xdp_output:
6aff67c8
AS
4426 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4427 goto error;
4428 break;
4429 case BPF_FUNC_get_stackid:
4430 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4431 goto error;
4432 break;
60d20f91 4433 case BPF_FUNC_current_task_under_cgroup:
747ea55e 4434 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
4435 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4436 goto error;
4437 break;
97f91a7c 4438 case BPF_FUNC_redirect_map:
9c270af3 4439 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 4440 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
4441 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4442 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
4443 goto error;
4444 break;
174a79ff 4445 case BPF_FUNC_sk_redirect_map:
4f738adb 4446 case BPF_FUNC_msg_redirect_map:
81110384 4447 case BPF_FUNC_sock_map_update:
174a79ff
JF
4448 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4449 goto error;
4450 break;
81110384
JF
4451 case BPF_FUNC_sk_redirect_hash:
4452 case BPF_FUNC_msg_redirect_hash:
4453 case BPF_FUNC_sock_hash_update:
4454 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
4455 goto error;
4456 break;
cd339431 4457 case BPF_FUNC_get_local_storage:
b741f163
RG
4458 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4459 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
4460 goto error;
4461 break;
2dbb9b9e 4462 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
4463 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4464 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4465 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
4466 goto error;
4467 break;
f1a2e44a
MV
4468 case BPF_FUNC_map_peek_elem:
4469 case BPF_FUNC_map_pop_elem:
4470 case BPF_FUNC_map_push_elem:
4471 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4472 map->map_type != BPF_MAP_TYPE_STACK)
4473 goto error;
4474 break;
6ac99e8f
MKL
4475 case BPF_FUNC_sk_storage_get:
4476 case BPF_FUNC_sk_storage_delete:
4477 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4478 goto error;
4479 break;
8ea63684
KS
4480 case BPF_FUNC_inode_storage_get:
4481 case BPF_FUNC_inode_storage_delete:
4482 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4483 goto error;
4484 break;
6aff67c8
AS
4485 default:
4486 break;
35578d79
KX
4487 }
4488
4489 return 0;
6aff67c8 4490error:
61bd5218 4491 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 4492 map->map_type, func_id_name(func_id), func_id);
6aff67c8 4493 return -EINVAL;
35578d79
KX
4494}
4495
90133415 4496static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
4497{
4498 int count = 0;
4499
39f19ebb 4500 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4501 count++;
39f19ebb 4502 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4503 count++;
39f19ebb 4504 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4505 count++;
39f19ebb 4506 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4507 count++;
39f19ebb 4508 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
4509 count++;
4510
90133415
DB
4511 /* We only support one arg being in raw mode at the moment,
4512 * which is sufficient for the helper functions we have
4513 * right now.
4514 */
4515 return count <= 1;
4516}
4517
4518static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4519 enum bpf_arg_type arg_next)
4520{
4521 return (arg_type_is_mem_ptr(arg_curr) &&
4522 !arg_type_is_mem_size(arg_next)) ||
4523 (!arg_type_is_mem_ptr(arg_curr) &&
4524 arg_type_is_mem_size(arg_next));
4525}
4526
4527static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4528{
4529 /* bpf_xxx(..., buf, len) call will access 'len'
4530 * bytes from memory 'buf'. Both arg types need
4531 * to be paired, so make sure there's no buggy
4532 * helper function specification.
4533 */
4534 if (arg_type_is_mem_size(fn->arg1_type) ||
4535 arg_type_is_mem_ptr(fn->arg5_type) ||
4536 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4537 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4538 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4539 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4540 return false;
4541
4542 return true;
4543}
4544
1b986589 4545static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
4546{
4547 int count = 0;
4548
1b986589 4549 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 4550 count++;
1b986589 4551 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 4552 count++;
1b986589 4553 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 4554 count++;
1b986589 4555 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 4556 count++;
1b986589 4557 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
4558 count++;
4559
1b986589
MKL
4560 /* A reference acquiring function cannot acquire
4561 * another refcounted ptr.
4562 */
64d85290 4563 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
4564 return false;
4565
fd978bf7
JS
4566 /* We only support one arg being unreferenced at the moment,
4567 * which is sufficient for the helper functions we have right now.
4568 */
4569 return count <= 1;
4570}
4571
9436ef6e
LB
4572static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4573{
4574 int i;
4575
4576 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++)
4577 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4578 return false;
4579
4580 return true;
4581}
4582
1b986589 4583static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
4584{
4585 return check_raw_mode_ok(fn) &&
fd978bf7 4586 check_arg_pair_ok(fn) &&
9436ef6e 4587 check_btf_id_ok(fn) &&
1b986589 4588 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
4589}
4590
de8f3a83
DB
4591/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4592 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 4593 */
f4d7e40a
AS
4594static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4595 struct bpf_func_state *state)
969bf05e 4596{
58e2af8b 4597 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
4598 int i;
4599
4600 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 4601 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 4602 mark_reg_unknown(env, regs, i);
969bf05e 4603
f3709f69
JS
4604 bpf_for_each_spilled_reg(i, state, reg) {
4605 if (!reg)
969bf05e 4606 continue;
de8f3a83 4607 if (reg_is_pkt_pointer_any(reg))
f54c7898 4608 __mark_reg_unknown(env, reg);
969bf05e
AS
4609 }
4610}
4611
f4d7e40a
AS
4612static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4613{
4614 struct bpf_verifier_state *vstate = env->cur_state;
4615 int i;
4616
4617 for (i = 0; i <= vstate->curframe; i++)
4618 __clear_all_pkt_pointers(env, vstate->frame[i]);
4619}
4620
fd978bf7 4621static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
4622 struct bpf_func_state *state,
4623 int ref_obj_id)
fd978bf7
JS
4624{
4625 struct bpf_reg_state *regs = state->regs, *reg;
4626 int i;
4627
4628 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 4629 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
4630 mark_reg_unknown(env, regs, i);
4631
4632 bpf_for_each_spilled_reg(i, state, reg) {
4633 if (!reg)
4634 continue;
1b986589 4635 if (reg->ref_obj_id == ref_obj_id)
f54c7898 4636 __mark_reg_unknown(env, reg);
fd978bf7
JS
4637 }
4638}
4639
4640/* The pointer with the specified id has released its reference to kernel
4641 * resources. Identify all copies of the same pointer and clear the reference.
4642 */
4643static int release_reference(struct bpf_verifier_env *env,
1b986589 4644 int ref_obj_id)
fd978bf7
JS
4645{
4646 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 4647 int err;
fd978bf7
JS
4648 int i;
4649
1b986589
MKL
4650 err = release_reference_state(cur_func(env), ref_obj_id);
4651 if (err)
4652 return err;
4653
fd978bf7 4654 for (i = 0; i <= vstate->curframe; i++)
1b986589 4655 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 4656
1b986589 4657 return 0;
fd978bf7
JS
4658}
4659
51c39bb1
AS
4660static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4661 struct bpf_reg_state *regs)
4662{
4663 int i;
4664
4665 /* after the call registers r0 - r5 were scratched */
4666 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4667 mark_reg_not_init(env, regs, caller_saved[i]);
4668 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4669 }
4670}
4671
f4d7e40a
AS
4672static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4673 int *insn_idx)
4674{
4675 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 4676 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 4677 struct bpf_func_state *caller, *callee;
fd978bf7 4678 int i, err, subprog, target_insn;
51c39bb1 4679 bool is_global = false;
f4d7e40a 4680
aada9ce6 4681 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 4682 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 4683 state->curframe + 2);
f4d7e40a
AS
4684 return -E2BIG;
4685 }
4686
4687 target_insn = *insn_idx + insn->imm;
4688 subprog = find_subprog(env, target_insn + 1);
4689 if (subprog < 0) {
4690 verbose(env, "verifier bug. No program starts at insn %d\n",
4691 target_insn + 1);
4692 return -EFAULT;
4693 }
4694
4695 caller = state->frame[state->curframe];
4696 if (state->frame[state->curframe + 1]) {
4697 verbose(env, "verifier bug. Frame %d already allocated\n",
4698 state->curframe + 1);
4699 return -EFAULT;
4700 }
4701
51c39bb1
AS
4702 func_info_aux = env->prog->aux->func_info_aux;
4703 if (func_info_aux)
4704 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4705 err = btf_check_func_arg_match(env, subprog, caller->regs);
4706 if (err == -EFAULT)
4707 return err;
4708 if (is_global) {
4709 if (err) {
4710 verbose(env, "Caller passes invalid args into func#%d\n",
4711 subprog);
4712 return err;
4713 } else {
4714 if (env->log.level & BPF_LOG_LEVEL)
4715 verbose(env,
4716 "Func#%d is global and valid. Skipping.\n",
4717 subprog);
4718 clear_caller_saved_regs(env, caller->regs);
4719
4720 /* All global functions return SCALAR_VALUE */
4721 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4722
4723 /* continue with next insn after call */
4724 return 0;
4725 }
4726 }
4727
f4d7e40a
AS
4728 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4729 if (!callee)
4730 return -ENOMEM;
4731 state->frame[state->curframe + 1] = callee;
4732
4733 /* callee cannot access r0, r6 - r9 for reading and has to write
4734 * into its own stack before reading from it.
4735 * callee can read/write into caller's stack
4736 */
4737 init_func_state(env, callee,
4738 /* remember the callsite, it will be used by bpf_exit */
4739 *insn_idx /* callsite */,
4740 state->curframe + 1 /* frameno within this callchain */,
f910cefa 4741 subprog /* subprog number within this prog */);
f4d7e40a 4742
fd978bf7
JS
4743 /* Transfer references to the callee */
4744 err = transfer_reference_state(callee, caller);
4745 if (err)
4746 return err;
4747
679c782d
EC
4748 /* copy r1 - r5 args that callee can access. The copy includes parent
4749 * pointers, which connects us up to the liveness chain
4750 */
f4d7e40a
AS
4751 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4752 callee->regs[i] = caller->regs[i];
4753
51c39bb1 4754 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
4755
4756 /* only increment it after check_reg_arg() finished */
4757 state->curframe++;
4758
4759 /* and go analyze first insn of the callee */
4760 *insn_idx = target_insn;
4761
06ee7115 4762 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4763 verbose(env, "caller:\n");
4764 print_verifier_state(env, caller);
4765 verbose(env, "callee:\n");
4766 print_verifier_state(env, callee);
4767 }
4768 return 0;
4769}
4770
4771static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4772{
4773 struct bpf_verifier_state *state = env->cur_state;
4774 struct bpf_func_state *caller, *callee;
4775 struct bpf_reg_state *r0;
fd978bf7 4776 int err;
f4d7e40a
AS
4777
4778 callee = state->frame[state->curframe];
4779 r0 = &callee->regs[BPF_REG_0];
4780 if (r0->type == PTR_TO_STACK) {
4781 /* technically it's ok to return caller's stack pointer
4782 * (or caller's caller's pointer) back to the caller,
4783 * since these pointers are valid. Only current stack
4784 * pointer will be invalid as soon as function exits,
4785 * but let's be conservative
4786 */
4787 verbose(env, "cannot return stack pointer to the caller\n");
4788 return -EINVAL;
4789 }
4790
4791 state->curframe--;
4792 caller = state->frame[state->curframe];
4793 /* return to the caller whatever r0 had in the callee */
4794 caller->regs[BPF_REG_0] = *r0;
4795
fd978bf7
JS
4796 /* Transfer references to the caller */
4797 err = transfer_reference_state(caller, callee);
4798 if (err)
4799 return err;
4800
f4d7e40a 4801 *insn_idx = callee->callsite + 1;
06ee7115 4802 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4803 verbose(env, "returning from callee:\n");
4804 print_verifier_state(env, callee);
4805 verbose(env, "to caller at %d:\n", *insn_idx);
4806 print_verifier_state(env, caller);
4807 }
4808 /* clear everything in the callee */
4809 free_func_state(callee);
4810 state->frame[state->curframe + 1] = NULL;
4811 return 0;
4812}
4813
849fa506
YS
4814static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4815 int func_id,
4816 struct bpf_call_arg_meta *meta)
4817{
4818 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4819
4820 if (ret_type != RET_INTEGER ||
4821 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
4822 func_id != BPF_FUNC_probe_read_str &&
4823 func_id != BPF_FUNC_probe_read_kernel_str &&
4824 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
4825 return;
4826
10060503 4827 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 4828 ret_reg->s32_max_value = meta->msize_max_value;
849fa506
YS
4829 __reg_deduce_bounds(ret_reg);
4830 __reg_bound_offset(ret_reg);
10060503 4831 __update_reg_bounds(ret_reg);
849fa506
YS
4832}
4833
c93552c4
DB
4834static int
4835record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4836 int func_id, int insn_idx)
4837{
4838 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 4839 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
4840
4841 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
4842 func_id != BPF_FUNC_map_lookup_elem &&
4843 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
4844 func_id != BPF_FUNC_map_delete_elem &&
4845 func_id != BPF_FUNC_map_push_elem &&
4846 func_id != BPF_FUNC_map_pop_elem &&
4847 func_id != BPF_FUNC_map_peek_elem)
c93552c4 4848 return 0;
09772d92 4849
591fe988 4850 if (map == NULL) {
c93552c4
DB
4851 verbose(env, "kernel subsystem misconfigured verifier\n");
4852 return -EINVAL;
4853 }
4854
591fe988
DB
4855 /* In case of read-only, some additional restrictions
4856 * need to be applied in order to prevent altering the
4857 * state of the map from program side.
4858 */
4859 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4860 (func_id == BPF_FUNC_map_delete_elem ||
4861 func_id == BPF_FUNC_map_update_elem ||
4862 func_id == BPF_FUNC_map_push_elem ||
4863 func_id == BPF_FUNC_map_pop_elem)) {
4864 verbose(env, "write into map forbidden\n");
4865 return -EACCES;
4866 }
4867
d2e4c1e6 4868 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 4869 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 4870 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 4871 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 4872 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 4873 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
4874 return 0;
4875}
4876
d2e4c1e6
DB
4877static int
4878record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4879 int func_id, int insn_idx)
4880{
4881 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4882 struct bpf_reg_state *regs = cur_regs(env), *reg;
4883 struct bpf_map *map = meta->map_ptr;
4884 struct tnum range;
4885 u64 val;
cc52d914 4886 int err;
d2e4c1e6
DB
4887
4888 if (func_id != BPF_FUNC_tail_call)
4889 return 0;
4890 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4891 verbose(env, "kernel subsystem misconfigured verifier\n");
4892 return -EINVAL;
4893 }
4894
4895 range = tnum_range(0, map->max_entries - 1);
4896 reg = &regs[BPF_REG_3];
4897
4898 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4899 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4900 return 0;
4901 }
4902
cc52d914
DB
4903 err = mark_chain_precision(env, BPF_REG_3);
4904 if (err)
4905 return err;
4906
d2e4c1e6
DB
4907 val = reg->var_off.value;
4908 if (bpf_map_key_unseen(aux))
4909 bpf_map_key_store(aux, val);
4910 else if (!bpf_map_key_poisoned(aux) &&
4911 bpf_map_key_immediate(aux) != val)
4912 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4913 return 0;
4914}
4915
fd978bf7
JS
4916static int check_reference_leak(struct bpf_verifier_env *env)
4917{
4918 struct bpf_func_state *state = cur_func(env);
4919 int i;
4920
4921 for (i = 0; i < state->acquired_refs; i++) {
4922 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4923 state->refs[i].id, state->refs[i].insn_idx);
4924 }
4925 return state->acquired_refs ? -EINVAL : 0;
4926}
4927
f4d7e40a 4928static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 4929{
17a52670 4930 const struct bpf_func_proto *fn = NULL;
638f5b90 4931 struct bpf_reg_state *regs;
33ff9823 4932 struct bpf_call_arg_meta meta;
969bf05e 4933 bool changes_data;
17a52670
AS
4934 int i, err;
4935
4936 /* find function prototype */
4937 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
4938 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4939 func_id);
17a52670
AS
4940 return -EINVAL;
4941 }
4942
00176a34 4943 if (env->ops->get_func_proto)
5e43f899 4944 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 4945 if (!fn) {
61bd5218
JK
4946 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4947 func_id);
17a52670
AS
4948 return -EINVAL;
4949 }
4950
4951 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 4952 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 4953 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
4954 return -EINVAL;
4955 }
4956
eae2e83e
JO
4957 if (fn->allowed && !fn->allowed(env->prog)) {
4958 verbose(env, "helper call is not allowed in probe\n");
4959 return -EINVAL;
4960 }
4961
04514d13 4962 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 4963 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
4964 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4965 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4966 func_id_name(func_id), func_id);
4967 return -EINVAL;
4968 }
969bf05e 4969
33ff9823 4970 memset(&meta, 0, sizeof(meta));
36bbef52 4971 meta.pkt_access = fn->pkt_access;
33ff9823 4972
1b986589 4973 err = check_func_proto(fn, func_id);
435faee1 4974 if (err) {
61bd5218 4975 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 4976 func_id_name(func_id), func_id);
435faee1
DB
4977 return err;
4978 }
4979
d83525ca 4980 meta.func_id = func_id;
17a52670 4981 /* check args */
a7658e1a 4982 for (i = 0; i < 5; i++) {
af7ec138 4983 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
4984 if (err)
4985 return err;
4986 }
17a52670 4987
c93552c4
DB
4988 err = record_func_map(env, &meta, func_id, insn_idx);
4989 if (err)
4990 return err;
4991
d2e4c1e6
DB
4992 err = record_func_key(env, &meta, func_id, insn_idx);
4993 if (err)
4994 return err;
4995
435faee1
DB
4996 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4997 * is inferred from register state.
4998 */
4999 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
5000 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5001 BPF_WRITE, -1, false);
435faee1
DB
5002 if (err)
5003 return err;
5004 }
5005
fd978bf7
JS
5006 if (func_id == BPF_FUNC_tail_call) {
5007 err = check_reference_leak(env);
5008 if (err) {
5009 verbose(env, "tail_call would lead to reference leak\n");
5010 return err;
5011 }
5012 } else if (is_release_function(func_id)) {
1b986589 5013 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
5014 if (err) {
5015 verbose(env, "func %s#%d reference has not been acquired before\n",
5016 func_id_name(func_id), func_id);
fd978bf7 5017 return err;
46f8bc92 5018 }
fd978bf7
JS
5019 }
5020
638f5b90 5021 regs = cur_regs(env);
cd339431
RG
5022
5023 /* check that flags argument in get_local_storage(map, flags) is 0,
5024 * this is required because get_local_storage() can't return an error.
5025 */
5026 if (func_id == BPF_FUNC_get_local_storage &&
5027 !register_is_null(&regs[BPF_REG_2])) {
5028 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5029 return -EINVAL;
5030 }
5031
17a52670 5032 /* reset caller saved regs */
dc503a8a 5033 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5034 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5035 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5036 }
17a52670 5037
5327ed3d
JW
5038 /* helper call returns 64-bit value. */
5039 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5040
dc503a8a 5041 /* update return register (already marked as written above) */
17a52670 5042 if (fn->ret_type == RET_INTEGER) {
f1174f77 5043 /* sets type to SCALAR_VALUE */
61bd5218 5044 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5045 } else if (fn->ret_type == RET_VOID) {
5046 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5047 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5048 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5049 /* There is no offset yet applied, variable or fixed */
61bd5218 5050 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5051 /* remember map_ptr, so that check_map_access()
5052 * can check 'value_size' boundary of memory access
5053 * to map element returned from bpf_map_lookup_elem()
5054 */
33ff9823 5055 if (meta.map_ptr == NULL) {
61bd5218
JK
5056 verbose(env,
5057 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5058 return -EINVAL;
5059 }
33ff9823 5060 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5061 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5062 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5063 if (map_value_has_spin_lock(meta.map_ptr))
5064 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5065 } else {
5066 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5067 regs[BPF_REG_0].id = ++env->id_gen;
5068 }
c64b7983
JS
5069 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5070 mark_reg_known_zero(env, regs, BPF_REG_0);
5071 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
0f3adc28 5072 regs[BPF_REG_0].id = ++env->id_gen;
85a51f8c
LB
5073 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5074 mark_reg_known_zero(env, regs, BPF_REG_0);
5075 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5076 regs[BPF_REG_0].id = ++env->id_gen;
655a51e5
MKL
5077 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5078 mark_reg_known_zero(env, regs, BPF_REG_0);
5079 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5080 regs[BPF_REG_0].id = ++env->id_gen;
457f4436
AN
5081 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5082 mark_reg_known_zero(env, regs, BPF_REG_0);
5083 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5084 regs[BPF_REG_0].id = ++env->id_gen;
5085 regs[BPF_REG_0].mem_size = meta.mem_size;
af7ec138
YS
5086 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5087 int ret_btf_id;
5088
5089 mark_reg_known_zero(env, regs, BPF_REG_0);
5090 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5091 ret_btf_id = *fn->ret_btf_id;
5092 if (ret_btf_id == 0) {
5093 verbose(env, "invalid return type %d of func %s#%d\n",
5094 fn->ret_type, func_id_name(func_id), func_id);
5095 return -EINVAL;
5096 }
5097 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5098 } else {
61bd5218 5099 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5100 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5101 return -EINVAL;
5102 }
04fd61ab 5103
0f3adc28 5104 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5105 /* For release_reference() */
5106 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5107 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5108 int id = acquire_reference_state(env, insn_idx);
5109
5110 if (id < 0)
5111 return id;
5112 /* For mark_ptr_or_null_reg() */
5113 regs[BPF_REG_0].id = id;
5114 /* For release_reference() */
5115 regs[BPF_REG_0].ref_obj_id = id;
5116 }
1b986589 5117
849fa506
YS
5118 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5119
61bd5218 5120 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5121 if (err)
5122 return err;
04fd61ab 5123
fa28dcb8
SL
5124 if ((func_id == BPF_FUNC_get_stack ||
5125 func_id == BPF_FUNC_get_task_stack) &&
5126 !env->prog->has_callchain_buf) {
c195651e
YS
5127 const char *err_str;
5128
5129#ifdef CONFIG_PERF_EVENTS
5130 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5131 err_str = "cannot get callchain buffer for func %s#%d\n";
5132#else
5133 err = -ENOTSUPP;
5134 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5135#endif
5136 if (err) {
5137 verbose(env, err_str, func_id_name(func_id), func_id);
5138 return err;
5139 }
5140
5141 env->prog->has_callchain_buf = true;
5142 }
5143
5d99cb2c
SL
5144 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5145 env->prog->call_get_stack = true;
5146
969bf05e
AS
5147 if (changes_data)
5148 clear_all_pkt_pointers(env);
5149 return 0;
5150}
5151
b03c9f9f
EC
5152static bool signed_add_overflows(s64 a, s64 b)
5153{
5154 /* Do the add in u64, where overflow is well-defined */
5155 s64 res = (s64)((u64)a + (u64)b);
5156
5157 if (b < 0)
5158 return res > a;
5159 return res < a;
5160}
5161
3f50f132
JF
5162static bool signed_add32_overflows(s64 a, s64 b)
5163{
5164 /* Do the add in u32, where overflow is well-defined */
5165 s32 res = (s32)((u32)a + (u32)b);
5166
5167 if (b < 0)
5168 return res > a;
5169 return res < a;
5170}
5171
5172static bool signed_sub_overflows(s32 a, s32 b)
b03c9f9f
EC
5173{
5174 /* Do the sub in u64, where overflow is well-defined */
5175 s64 res = (s64)((u64)a - (u64)b);
5176
5177 if (b < 0)
5178 return res < a;
5179 return res > a;
969bf05e
AS
5180}
5181
3f50f132
JF
5182static bool signed_sub32_overflows(s32 a, s32 b)
5183{
5184 /* Do the sub in u64, where overflow is well-defined */
5185 s32 res = (s32)((u32)a - (u32)b);
5186
5187 if (b < 0)
5188 return res < a;
5189 return res > a;
5190}
5191
bb7f0f98
AS
5192static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5193 const struct bpf_reg_state *reg,
5194 enum bpf_reg_type type)
5195{
5196 bool known = tnum_is_const(reg->var_off);
5197 s64 val = reg->var_off.value;
5198 s64 smin = reg->smin_value;
5199
5200 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5201 verbose(env, "math between %s pointer and %lld is not allowed\n",
5202 reg_type_str[type], val);
5203 return false;
5204 }
5205
5206 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5207 verbose(env, "%s pointer offset %d is not allowed\n",
5208 reg_type_str[type], reg->off);
5209 return false;
5210 }
5211
5212 if (smin == S64_MIN) {
5213 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5214 reg_type_str[type]);
5215 return false;
5216 }
5217
5218 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5219 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5220 smin, reg_type_str[type]);
5221 return false;
5222 }
5223
5224 return true;
5225}
5226
979d63d5
DB
5227static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5228{
5229 return &env->insn_aux_data[env->insn_idx];
5230}
5231
5232static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5233 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5234{
5235 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5236 (opcode == BPF_SUB && !off_is_neg);
5237 u32 off;
5238
5239 switch (ptr_reg->type) {
5240 case PTR_TO_STACK:
088ec26d
AI
5241 /* Indirect variable offset stack access is prohibited in
5242 * unprivileged mode so it's not handled here.
5243 */
979d63d5
DB
5244 off = ptr_reg->off + ptr_reg->var_off.value;
5245 if (mask_to_left)
5246 *ptr_limit = MAX_BPF_STACK + off;
5247 else
5248 *ptr_limit = -off;
5249 return 0;
5250 case PTR_TO_MAP_VALUE:
5251 if (mask_to_left) {
5252 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5253 } else {
5254 off = ptr_reg->smin_value + ptr_reg->off;
5255 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5256 }
5257 return 0;
5258 default:
5259 return -EINVAL;
5260 }
5261}
5262
d3bd7413
DB
5263static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5264 const struct bpf_insn *insn)
5265{
2c78ee89 5266 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
5267}
5268
5269static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5270 u32 alu_state, u32 alu_limit)
5271{
5272 /* If we arrived here from different branches with different
5273 * state or limits to sanitize, then this won't work.
5274 */
5275 if (aux->alu_state &&
5276 (aux->alu_state != alu_state ||
5277 aux->alu_limit != alu_limit))
5278 return -EACCES;
5279
5280 /* Corresponding fixup done in fixup_bpf_calls(). */
5281 aux->alu_state = alu_state;
5282 aux->alu_limit = alu_limit;
5283 return 0;
5284}
5285
5286static int sanitize_val_alu(struct bpf_verifier_env *env,
5287 struct bpf_insn *insn)
5288{
5289 struct bpf_insn_aux_data *aux = cur_aux(env);
5290
5291 if (can_skip_alu_sanitation(env, insn))
5292 return 0;
5293
5294 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5295}
5296
979d63d5
DB
5297static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5298 struct bpf_insn *insn,
5299 const struct bpf_reg_state *ptr_reg,
5300 struct bpf_reg_state *dst_reg,
5301 bool off_is_neg)
5302{
5303 struct bpf_verifier_state *vstate = env->cur_state;
5304 struct bpf_insn_aux_data *aux = cur_aux(env);
5305 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5306 u8 opcode = BPF_OP(insn->code);
5307 u32 alu_state, alu_limit;
5308 struct bpf_reg_state tmp;
5309 bool ret;
5310
d3bd7413 5311 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
5312 return 0;
5313
5314 /* We already marked aux for masking from non-speculative
5315 * paths, thus we got here in the first place. We only care
5316 * to explore bad access from here.
5317 */
5318 if (vstate->speculative)
5319 goto do_sim;
5320
5321 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5322 alu_state |= ptr_is_dst_reg ?
5323 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5324
5325 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5326 return 0;
d3bd7413 5327 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 5328 return -EACCES;
979d63d5
DB
5329do_sim:
5330 /* Simulate and find potential out-of-bounds access under
5331 * speculative execution from truncation as a result of
5332 * masking when off was not within expected range. If off
5333 * sits in dst, then we temporarily need to move ptr there
5334 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5335 * for cases where we use K-based arithmetic in one direction
5336 * and truncated reg-based in the other in order to explore
5337 * bad access.
5338 */
5339 if (!ptr_is_dst_reg) {
5340 tmp = *dst_reg;
5341 *dst_reg = *ptr_reg;
5342 }
5343 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 5344 if (!ptr_is_dst_reg && ret)
979d63d5
DB
5345 *dst_reg = tmp;
5346 return !ret ? -EFAULT : 0;
5347}
5348
f1174f77 5349/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
5350 * Caller should also handle BPF_MOV case separately.
5351 * If we return -EACCES, caller may want to try again treating pointer as a
5352 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5353 */
5354static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5355 struct bpf_insn *insn,
5356 const struct bpf_reg_state *ptr_reg,
5357 const struct bpf_reg_state *off_reg)
969bf05e 5358{
f4d7e40a
AS
5359 struct bpf_verifier_state *vstate = env->cur_state;
5360 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5361 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 5362 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
5363 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5364 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5365 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5366 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 5367 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 5368 u8 opcode = BPF_OP(insn->code);
979d63d5 5369 int ret;
969bf05e 5370
f1174f77 5371 dst_reg = &regs[dst];
969bf05e 5372
6f16101e
DB
5373 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5374 smin_val > smax_val || umin_val > umax_val) {
5375 /* Taint dst register if offset had invalid bounds derived from
5376 * e.g. dead branches.
5377 */
f54c7898 5378 __mark_reg_unknown(env, dst_reg);
6f16101e 5379 return 0;
f1174f77
EC
5380 }
5381
5382 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5383 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
5384 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5385 __mark_reg_unknown(env, dst_reg);
5386 return 0;
5387 }
5388
82abbf8d
AS
5389 verbose(env,
5390 "R%d 32-bit pointer arithmetic prohibited\n",
5391 dst);
f1174f77 5392 return -EACCES;
969bf05e
AS
5393 }
5394
aad2eeaf
JS
5395 switch (ptr_reg->type) {
5396 case PTR_TO_MAP_VALUE_OR_NULL:
5397 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5398 dst, reg_type_str[ptr_reg->type]);
f1174f77 5399 return -EACCES;
aad2eeaf 5400 case CONST_PTR_TO_MAP:
7c696732
YS
5401 /* smin_val represents the known value */
5402 if (known && smin_val == 0 && opcode == BPF_ADD)
5403 break;
5404 /* fall-through */
aad2eeaf 5405 case PTR_TO_PACKET_END:
c64b7983
JS
5406 case PTR_TO_SOCKET:
5407 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
5408 case PTR_TO_SOCK_COMMON:
5409 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
5410 case PTR_TO_TCP_SOCK:
5411 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 5412 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
5413 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5414 dst, reg_type_str[ptr_reg->type]);
f1174f77 5415 return -EACCES;
9d7eceed
DB
5416 case PTR_TO_MAP_VALUE:
5417 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5418 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5419 off_reg == dst_reg ? dst : src);
5420 return -EACCES;
5421 }
df561f66 5422 fallthrough;
aad2eeaf
JS
5423 default:
5424 break;
f1174f77
EC
5425 }
5426
5427 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5428 * The id may be overwritten later if we create a new variable offset.
969bf05e 5429 */
f1174f77
EC
5430 dst_reg->type = ptr_reg->type;
5431 dst_reg->id = ptr_reg->id;
969bf05e 5432
bb7f0f98
AS
5433 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5434 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5435 return -EINVAL;
5436
3f50f132
JF
5437 /* pointer types do not carry 32-bit bounds at the moment. */
5438 __mark_reg32_unbounded(dst_reg);
5439
f1174f77
EC
5440 switch (opcode) {
5441 case BPF_ADD:
979d63d5
DB
5442 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5443 if (ret < 0) {
5444 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5445 return ret;
5446 }
f1174f77
EC
5447 /* We can take a fixed offset as long as it doesn't overflow
5448 * the s32 'off' field
969bf05e 5449 */
b03c9f9f
EC
5450 if (known && (ptr_reg->off + smin_val ==
5451 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 5452 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
5453 dst_reg->smin_value = smin_ptr;
5454 dst_reg->smax_value = smax_ptr;
5455 dst_reg->umin_value = umin_ptr;
5456 dst_reg->umax_value = umax_ptr;
f1174f77 5457 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 5458 dst_reg->off = ptr_reg->off + smin_val;
0962590e 5459 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5460 break;
5461 }
f1174f77
EC
5462 /* A new variable offset is created. Note that off_reg->off
5463 * == 0, since it's a scalar.
5464 * dst_reg gets the pointer type and since some positive
5465 * integer value was added to the pointer, give it a new 'id'
5466 * if it's a PTR_TO_PACKET.
5467 * this creates a new 'base' pointer, off_reg (variable) gets
5468 * added into the variable offset, and we copy the fixed offset
5469 * from ptr_reg.
969bf05e 5470 */
b03c9f9f
EC
5471 if (signed_add_overflows(smin_ptr, smin_val) ||
5472 signed_add_overflows(smax_ptr, smax_val)) {
5473 dst_reg->smin_value = S64_MIN;
5474 dst_reg->smax_value = S64_MAX;
5475 } else {
5476 dst_reg->smin_value = smin_ptr + smin_val;
5477 dst_reg->smax_value = smax_ptr + smax_val;
5478 }
5479 if (umin_ptr + umin_val < umin_ptr ||
5480 umax_ptr + umax_val < umax_ptr) {
5481 dst_reg->umin_value = 0;
5482 dst_reg->umax_value = U64_MAX;
5483 } else {
5484 dst_reg->umin_value = umin_ptr + umin_val;
5485 dst_reg->umax_value = umax_ptr + umax_val;
5486 }
f1174f77
EC
5487 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5488 dst_reg->off = ptr_reg->off;
0962590e 5489 dst_reg->raw = ptr_reg->raw;
de8f3a83 5490 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5491 dst_reg->id = ++env->id_gen;
5492 /* something was added to pkt_ptr, set range to zero */
0962590e 5493 dst_reg->raw = 0;
f1174f77
EC
5494 }
5495 break;
5496 case BPF_SUB:
979d63d5
DB
5497 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5498 if (ret < 0) {
5499 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5500 return ret;
5501 }
f1174f77
EC
5502 if (dst_reg == off_reg) {
5503 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
5504 verbose(env, "R%d tried to subtract pointer from scalar\n",
5505 dst);
f1174f77
EC
5506 return -EACCES;
5507 }
5508 /* We don't allow subtraction from FP, because (according to
5509 * test_verifier.c test "invalid fp arithmetic", JITs might not
5510 * be able to deal with it.
969bf05e 5511 */
f1174f77 5512 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
5513 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5514 dst);
f1174f77
EC
5515 return -EACCES;
5516 }
b03c9f9f
EC
5517 if (known && (ptr_reg->off - smin_val ==
5518 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 5519 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
5520 dst_reg->smin_value = smin_ptr;
5521 dst_reg->smax_value = smax_ptr;
5522 dst_reg->umin_value = umin_ptr;
5523 dst_reg->umax_value = umax_ptr;
f1174f77
EC
5524 dst_reg->var_off = ptr_reg->var_off;
5525 dst_reg->id = ptr_reg->id;
b03c9f9f 5526 dst_reg->off = ptr_reg->off - smin_val;
0962590e 5527 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5528 break;
5529 }
f1174f77
EC
5530 /* A new variable offset is created. If the subtrahend is known
5531 * nonnegative, then any reg->range we had before is still good.
969bf05e 5532 */
b03c9f9f
EC
5533 if (signed_sub_overflows(smin_ptr, smax_val) ||
5534 signed_sub_overflows(smax_ptr, smin_val)) {
5535 /* Overflow possible, we know nothing */
5536 dst_reg->smin_value = S64_MIN;
5537 dst_reg->smax_value = S64_MAX;
5538 } else {
5539 dst_reg->smin_value = smin_ptr - smax_val;
5540 dst_reg->smax_value = smax_ptr - smin_val;
5541 }
5542 if (umin_ptr < umax_val) {
5543 /* Overflow possible, we know nothing */
5544 dst_reg->umin_value = 0;
5545 dst_reg->umax_value = U64_MAX;
5546 } else {
5547 /* Cannot overflow (as long as bounds are consistent) */
5548 dst_reg->umin_value = umin_ptr - umax_val;
5549 dst_reg->umax_value = umax_ptr - umin_val;
5550 }
f1174f77
EC
5551 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5552 dst_reg->off = ptr_reg->off;
0962590e 5553 dst_reg->raw = ptr_reg->raw;
de8f3a83 5554 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5555 dst_reg->id = ++env->id_gen;
5556 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 5557 if (smin_val < 0)
0962590e 5558 dst_reg->raw = 0;
43188702 5559 }
f1174f77
EC
5560 break;
5561 case BPF_AND:
5562 case BPF_OR:
5563 case BPF_XOR:
82abbf8d
AS
5564 /* bitwise ops on pointers are troublesome, prohibit. */
5565 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5566 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
5567 return -EACCES;
5568 default:
5569 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
5570 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5571 dst, bpf_alu_string[opcode >> 4]);
f1174f77 5572 return -EACCES;
43188702
JF
5573 }
5574
bb7f0f98
AS
5575 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5576 return -EINVAL;
5577
b03c9f9f
EC
5578 __update_reg_bounds(dst_reg);
5579 __reg_deduce_bounds(dst_reg);
5580 __reg_bound_offset(dst_reg);
0d6303db
DB
5581
5582 /* For unprivileged we require that resulting offset must be in bounds
5583 * in order to be able to sanitize access later on.
5584 */
2c78ee89 5585 if (!env->bypass_spec_v1) {
e4298d25
DB
5586 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5587 check_map_access(env, dst, dst_reg->off, 1, false)) {
5588 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5589 "prohibited for !root\n", dst);
5590 return -EACCES;
5591 } else if (dst_reg->type == PTR_TO_STACK &&
5592 check_stack_access(env, dst_reg, dst_reg->off +
5593 dst_reg->var_off.value, 1)) {
5594 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5595 "prohibited for !root\n", dst);
5596 return -EACCES;
5597 }
0d6303db
DB
5598 }
5599
43188702
JF
5600 return 0;
5601}
5602
3f50f132
JF
5603static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5604 struct bpf_reg_state *src_reg)
5605{
5606 s32 smin_val = src_reg->s32_min_value;
5607 s32 smax_val = src_reg->s32_max_value;
5608 u32 umin_val = src_reg->u32_min_value;
5609 u32 umax_val = src_reg->u32_max_value;
5610
5611 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5612 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5613 dst_reg->s32_min_value = S32_MIN;
5614 dst_reg->s32_max_value = S32_MAX;
5615 } else {
5616 dst_reg->s32_min_value += smin_val;
5617 dst_reg->s32_max_value += smax_val;
5618 }
5619 if (dst_reg->u32_min_value + umin_val < umin_val ||
5620 dst_reg->u32_max_value + umax_val < umax_val) {
5621 dst_reg->u32_min_value = 0;
5622 dst_reg->u32_max_value = U32_MAX;
5623 } else {
5624 dst_reg->u32_min_value += umin_val;
5625 dst_reg->u32_max_value += umax_val;
5626 }
5627}
5628
07cd2631
JF
5629static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5630 struct bpf_reg_state *src_reg)
5631{
5632 s64 smin_val = src_reg->smin_value;
5633 s64 smax_val = src_reg->smax_value;
5634 u64 umin_val = src_reg->umin_value;
5635 u64 umax_val = src_reg->umax_value;
5636
5637 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5638 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5639 dst_reg->smin_value = S64_MIN;
5640 dst_reg->smax_value = S64_MAX;
5641 } else {
5642 dst_reg->smin_value += smin_val;
5643 dst_reg->smax_value += smax_val;
5644 }
5645 if (dst_reg->umin_value + umin_val < umin_val ||
5646 dst_reg->umax_value + umax_val < umax_val) {
5647 dst_reg->umin_value = 0;
5648 dst_reg->umax_value = U64_MAX;
5649 } else {
5650 dst_reg->umin_value += umin_val;
5651 dst_reg->umax_value += umax_val;
5652 }
3f50f132
JF
5653}
5654
5655static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5656 struct bpf_reg_state *src_reg)
5657{
5658 s32 smin_val = src_reg->s32_min_value;
5659 s32 smax_val = src_reg->s32_max_value;
5660 u32 umin_val = src_reg->u32_min_value;
5661 u32 umax_val = src_reg->u32_max_value;
5662
5663 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5664 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5665 /* Overflow possible, we know nothing */
5666 dst_reg->s32_min_value = S32_MIN;
5667 dst_reg->s32_max_value = S32_MAX;
5668 } else {
5669 dst_reg->s32_min_value -= smax_val;
5670 dst_reg->s32_max_value -= smin_val;
5671 }
5672 if (dst_reg->u32_min_value < umax_val) {
5673 /* Overflow possible, we know nothing */
5674 dst_reg->u32_min_value = 0;
5675 dst_reg->u32_max_value = U32_MAX;
5676 } else {
5677 /* Cannot overflow (as long as bounds are consistent) */
5678 dst_reg->u32_min_value -= umax_val;
5679 dst_reg->u32_max_value -= umin_val;
5680 }
07cd2631
JF
5681}
5682
5683static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5684 struct bpf_reg_state *src_reg)
5685{
5686 s64 smin_val = src_reg->smin_value;
5687 s64 smax_val = src_reg->smax_value;
5688 u64 umin_val = src_reg->umin_value;
5689 u64 umax_val = src_reg->umax_value;
5690
5691 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5692 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5693 /* Overflow possible, we know nothing */
5694 dst_reg->smin_value = S64_MIN;
5695 dst_reg->smax_value = S64_MAX;
5696 } else {
5697 dst_reg->smin_value -= smax_val;
5698 dst_reg->smax_value -= smin_val;
5699 }
5700 if (dst_reg->umin_value < umax_val) {
5701 /* Overflow possible, we know nothing */
5702 dst_reg->umin_value = 0;
5703 dst_reg->umax_value = U64_MAX;
5704 } else {
5705 /* Cannot overflow (as long as bounds are consistent) */
5706 dst_reg->umin_value -= umax_val;
5707 dst_reg->umax_value -= umin_val;
5708 }
3f50f132
JF
5709}
5710
5711static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5712 struct bpf_reg_state *src_reg)
5713{
5714 s32 smin_val = src_reg->s32_min_value;
5715 u32 umin_val = src_reg->u32_min_value;
5716 u32 umax_val = src_reg->u32_max_value;
5717
5718 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5719 /* Ain't nobody got time to multiply that sign */
5720 __mark_reg32_unbounded(dst_reg);
5721 return;
5722 }
5723 /* Both values are positive, so we can work with unsigned and
5724 * copy the result to signed (unless it exceeds S32_MAX).
5725 */
5726 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5727 /* Potential overflow, we know nothing */
5728 __mark_reg32_unbounded(dst_reg);
5729 return;
5730 }
5731 dst_reg->u32_min_value *= umin_val;
5732 dst_reg->u32_max_value *= umax_val;
5733 if (dst_reg->u32_max_value > S32_MAX) {
5734 /* Overflow possible, we know nothing */
5735 dst_reg->s32_min_value = S32_MIN;
5736 dst_reg->s32_max_value = S32_MAX;
5737 } else {
5738 dst_reg->s32_min_value = dst_reg->u32_min_value;
5739 dst_reg->s32_max_value = dst_reg->u32_max_value;
5740 }
07cd2631
JF
5741}
5742
5743static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5744 struct bpf_reg_state *src_reg)
5745{
5746 s64 smin_val = src_reg->smin_value;
5747 u64 umin_val = src_reg->umin_value;
5748 u64 umax_val = src_reg->umax_value;
5749
07cd2631
JF
5750 if (smin_val < 0 || dst_reg->smin_value < 0) {
5751 /* Ain't nobody got time to multiply that sign */
3f50f132 5752 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5753 return;
5754 }
5755 /* Both values are positive, so we can work with unsigned and
5756 * copy the result to signed (unless it exceeds S64_MAX).
5757 */
5758 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5759 /* Potential overflow, we know nothing */
3f50f132 5760 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5761 return;
5762 }
5763 dst_reg->umin_value *= umin_val;
5764 dst_reg->umax_value *= umax_val;
5765 if (dst_reg->umax_value > S64_MAX) {
5766 /* Overflow possible, we know nothing */
5767 dst_reg->smin_value = S64_MIN;
5768 dst_reg->smax_value = S64_MAX;
5769 } else {
5770 dst_reg->smin_value = dst_reg->umin_value;
5771 dst_reg->smax_value = dst_reg->umax_value;
5772 }
5773}
5774
3f50f132
JF
5775static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5776 struct bpf_reg_state *src_reg)
5777{
5778 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5779 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5780 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5781 s32 smin_val = src_reg->s32_min_value;
5782 u32 umax_val = src_reg->u32_max_value;
5783
5784 /* Assuming scalar64_min_max_and will be called so its safe
5785 * to skip updating register for known 32-bit case.
5786 */
5787 if (src_known && dst_known)
5788 return;
5789
5790 /* We get our minimum from the var_off, since that's inherently
5791 * bitwise. Our maximum is the minimum of the operands' maxima.
5792 */
5793 dst_reg->u32_min_value = var32_off.value;
5794 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5795 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5796 /* Lose signed bounds when ANDing negative numbers,
5797 * ain't nobody got time for that.
5798 */
5799 dst_reg->s32_min_value = S32_MIN;
5800 dst_reg->s32_max_value = S32_MAX;
5801 } else {
5802 /* ANDing two positives gives a positive, so safe to
5803 * cast result into s64.
5804 */
5805 dst_reg->s32_min_value = dst_reg->u32_min_value;
5806 dst_reg->s32_max_value = dst_reg->u32_max_value;
5807 }
5808
5809}
5810
07cd2631
JF
5811static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5812 struct bpf_reg_state *src_reg)
5813{
3f50f132
JF
5814 bool src_known = tnum_is_const(src_reg->var_off);
5815 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5816 s64 smin_val = src_reg->smin_value;
5817 u64 umax_val = src_reg->umax_value;
5818
3f50f132
JF
5819 if (src_known && dst_known) {
5820 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5821 src_reg->var_off.value);
5822 return;
5823 }
5824
07cd2631
JF
5825 /* We get our minimum from the var_off, since that's inherently
5826 * bitwise. Our maximum is the minimum of the operands' maxima.
5827 */
07cd2631
JF
5828 dst_reg->umin_value = dst_reg->var_off.value;
5829 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5830 if (dst_reg->smin_value < 0 || smin_val < 0) {
5831 /* Lose signed bounds when ANDing negative numbers,
5832 * ain't nobody got time for that.
5833 */
5834 dst_reg->smin_value = S64_MIN;
5835 dst_reg->smax_value = S64_MAX;
5836 } else {
5837 /* ANDing two positives gives a positive, so safe to
5838 * cast result into s64.
5839 */
5840 dst_reg->smin_value = dst_reg->umin_value;
5841 dst_reg->smax_value = dst_reg->umax_value;
5842 }
5843 /* We may learn something more from the var_off */
5844 __update_reg_bounds(dst_reg);
5845}
5846
3f50f132
JF
5847static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5848 struct bpf_reg_state *src_reg)
5849{
5850 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5851 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5852 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5853 s32 smin_val = src_reg->smin_value;
5854 u32 umin_val = src_reg->umin_value;
5855
5856 /* Assuming scalar64_min_max_or will be called so it is safe
5857 * to skip updating register for known case.
5858 */
5859 if (src_known && dst_known)
5860 return;
5861
5862 /* We get our maximum from the var_off, and our minimum is the
5863 * maximum of the operands' minima
5864 */
5865 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5866 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5867 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5868 /* Lose signed bounds when ORing negative numbers,
5869 * ain't nobody got time for that.
5870 */
5871 dst_reg->s32_min_value = S32_MIN;
5872 dst_reg->s32_max_value = S32_MAX;
5873 } else {
5874 /* ORing two positives gives a positive, so safe to
5875 * cast result into s64.
5876 */
5877 dst_reg->s32_min_value = dst_reg->umin_value;
5878 dst_reg->s32_max_value = dst_reg->umax_value;
5879 }
5880}
5881
07cd2631
JF
5882static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5883 struct bpf_reg_state *src_reg)
5884{
3f50f132
JF
5885 bool src_known = tnum_is_const(src_reg->var_off);
5886 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5887 s64 smin_val = src_reg->smin_value;
5888 u64 umin_val = src_reg->umin_value;
5889
3f50f132
JF
5890 if (src_known && dst_known) {
5891 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5892 src_reg->var_off.value);
5893 return;
5894 }
5895
07cd2631
JF
5896 /* We get our maximum from the var_off, and our minimum is the
5897 * maximum of the operands' minima
5898 */
07cd2631
JF
5899 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5900 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5901 if (dst_reg->smin_value < 0 || smin_val < 0) {
5902 /* Lose signed bounds when ORing negative numbers,
5903 * ain't nobody got time for that.
5904 */
5905 dst_reg->smin_value = S64_MIN;
5906 dst_reg->smax_value = S64_MAX;
5907 } else {
5908 /* ORing two positives gives a positive, so safe to
5909 * cast result into s64.
5910 */
5911 dst_reg->smin_value = dst_reg->umin_value;
5912 dst_reg->smax_value = dst_reg->umax_value;
5913 }
5914 /* We may learn something more from the var_off */
5915 __update_reg_bounds(dst_reg);
5916}
5917
2921c90d
YS
5918static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
5919 struct bpf_reg_state *src_reg)
5920{
5921 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5922 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5923 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5924 s32 smin_val = src_reg->s32_min_value;
5925
5926 /* Assuming scalar64_min_max_xor will be called so it is safe
5927 * to skip updating register for known case.
5928 */
5929 if (src_known && dst_known)
5930 return;
5931
5932 /* We get both minimum and maximum from the var32_off. */
5933 dst_reg->u32_min_value = var32_off.value;
5934 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5935
5936 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
5937 /* XORing two positive sign numbers gives a positive,
5938 * so safe to cast u32 result into s32.
5939 */
5940 dst_reg->s32_min_value = dst_reg->u32_min_value;
5941 dst_reg->s32_max_value = dst_reg->u32_max_value;
5942 } else {
5943 dst_reg->s32_min_value = S32_MIN;
5944 dst_reg->s32_max_value = S32_MAX;
5945 }
5946}
5947
5948static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
5949 struct bpf_reg_state *src_reg)
5950{
5951 bool src_known = tnum_is_const(src_reg->var_off);
5952 bool dst_known = tnum_is_const(dst_reg->var_off);
5953 s64 smin_val = src_reg->smin_value;
5954
5955 if (src_known && dst_known) {
5956 /* dst_reg->var_off.value has been updated earlier */
5957 __mark_reg_known(dst_reg, dst_reg->var_off.value);
5958 return;
5959 }
5960
5961 /* We get both minimum and maximum from the var_off. */
5962 dst_reg->umin_value = dst_reg->var_off.value;
5963 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5964
5965 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
5966 /* XORing two positive sign numbers gives a positive,
5967 * so safe to cast u64 result into s64.
5968 */
5969 dst_reg->smin_value = dst_reg->umin_value;
5970 dst_reg->smax_value = dst_reg->umax_value;
5971 } else {
5972 dst_reg->smin_value = S64_MIN;
5973 dst_reg->smax_value = S64_MAX;
5974 }
5975
5976 __update_reg_bounds(dst_reg);
5977}
5978
3f50f132
JF
5979static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5980 u64 umin_val, u64 umax_val)
07cd2631 5981{
07cd2631
JF
5982 /* We lose all sign bit information (except what we can pick
5983 * up from var_off)
5984 */
3f50f132
JF
5985 dst_reg->s32_min_value = S32_MIN;
5986 dst_reg->s32_max_value = S32_MAX;
5987 /* If we might shift our top bit out, then we know nothing */
5988 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5989 dst_reg->u32_min_value = 0;
5990 dst_reg->u32_max_value = U32_MAX;
5991 } else {
5992 dst_reg->u32_min_value <<= umin_val;
5993 dst_reg->u32_max_value <<= umax_val;
5994 }
5995}
5996
5997static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5998 struct bpf_reg_state *src_reg)
5999{
6000 u32 umax_val = src_reg->u32_max_value;
6001 u32 umin_val = src_reg->u32_min_value;
6002 /* u32 alu operation will zext upper bits */
6003 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6004
6005 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6006 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6007 /* Not required but being careful mark reg64 bounds as unknown so
6008 * that we are forced to pick them up from tnum and zext later and
6009 * if some path skips this step we are still safe.
6010 */
6011 __mark_reg64_unbounded(dst_reg);
6012 __update_reg32_bounds(dst_reg);
6013}
6014
6015static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6016 u64 umin_val, u64 umax_val)
6017{
6018 /* Special case <<32 because it is a common compiler pattern to sign
6019 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6020 * positive we know this shift will also be positive so we can track
6021 * bounds correctly. Otherwise we lose all sign bit information except
6022 * what we can pick up from var_off. Perhaps we can generalize this
6023 * later to shifts of any length.
6024 */
6025 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6026 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6027 else
6028 dst_reg->smax_value = S64_MAX;
6029
6030 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6031 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6032 else
6033 dst_reg->smin_value = S64_MIN;
6034
07cd2631
JF
6035 /* If we might shift our top bit out, then we know nothing */
6036 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6037 dst_reg->umin_value = 0;
6038 dst_reg->umax_value = U64_MAX;
6039 } else {
6040 dst_reg->umin_value <<= umin_val;
6041 dst_reg->umax_value <<= umax_val;
6042 }
3f50f132
JF
6043}
6044
6045static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6046 struct bpf_reg_state *src_reg)
6047{
6048 u64 umax_val = src_reg->umax_value;
6049 u64 umin_val = src_reg->umin_value;
6050
6051 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6052 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6053 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6054
07cd2631
JF
6055 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6056 /* We may learn something more from the var_off */
6057 __update_reg_bounds(dst_reg);
6058}
6059
3f50f132
JF
6060static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6061 struct bpf_reg_state *src_reg)
6062{
6063 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6064 u32 umax_val = src_reg->u32_max_value;
6065 u32 umin_val = src_reg->u32_min_value;
6066
6067 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6068 * be negative, then either:
6069 * 1) src_reg might be zero, so the sign bit of the result is
6070 * unknown, so we lose our signed bounds
6071 * 2) it's known negative, thus the unsigned bounds capture the
6072 * signed bounds
6073 * 3) the signed bounds cross zero, so they tell us nothing
6074 * about the result
6075 * If the value in dst_reg is known nonnegative, then again the
6076 * unsigned bounts capture the signed bounds.
6077 * Thus, in all cases it suffices to blow away our signed bounds
6078 * and rely on inferring new ones from the unsigned bounds and
6079 * var_off of the result.
6080 */
6081 dst_reg->s32_min_value = S32_MIN;
6082 dst_reg->s32_max_value = S32_MAX;
6083
6084 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6085 dst_reg->u32_min_value >>= umax_val;
6086 dst_reg->u32_max_value >>= umin_val;
6087
6088 __mark_reg64_unbounded(dst_reg);
6089 __update_reg32_bounds(dst_reg);
6090}
6091
07cd2631
JF
6092static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6093 struct bpf_reg_state *src_reg)
6094{
6095 u64 umax_val = src_reg->umax_value;
6096 u64 umin_val = src_reg->umin_value;
6097
6098 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6099 * be negative, then either:
6100 * 1) src_reg might be zero, so the sign bit of the result is
6101 * unknown, so we lose our signed bounds
6102 * 2) it's known negative, thus the unsigned bounds capture the
6103 * signed bounds
6104 * 3) the signed bounds cross zero, so they tell us nothing
6105 * about the result
6106 * If the value in dst_reg is known nonnegative, then again the
6107 * unsigned bounts capture the signed bounds.
6108 * Thus, in all cases it suffices to blow away our signed bounds
6109 * and rely on inferring new ones from the unsigned bounds and
6110 * var_off of the result.
6111 */
6112 dst_reg->smin_value = S64_MIN;
6113 dst_reg->smax_value = S64_MAX;
6114 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6115 dst_reg->umin_value >>= umax_val;
6116 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6117
6118 /* Its not easy to operate on alu32 bounds here because it depends
6119 * on bits being shifted in. Take easy way out and mark unbounded
6120 * so we can recalculate later from tnum.
6121 */
6122 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6123 __update_reg_bounds(dst_reg);
6124}
6125
3f50f132
JF
6126static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6127 struct bpf_reg_state *src_reg)
07cd2631 6128{
3f50f132 6129 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6130
6131 /* Upon reaching here, src_known is true and
6132 * umax_val is equal to umin_val.
6133 */
3f50f132
JF
6134 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6135 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6136
3f50f132
JF
6137 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6138
6139 /* blow away the dst_reg umin_value/umax_value and rely on
6140 * dst_reg var_off to refine the result.
6141 */
6142 dst_reg->u32_min_value = 0;
6143 dst_reg->u32_max_value = U32_MAX;
6144
6145 __mark_reg64_unbounded(dst_reg);
6146 __update_reg32_bounds(dst_reg);
6147}
6148
6149static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6150 struct bpf_reg_state *src_reg)
6151{
6152 u64 umin_val = src_reg->umin_value;
6153
6154 /* Upon reaching here, src_known is true and umax_val is equal
6155 * to umin_val.
6156 */
6157 dst_reg->smin_value >>= umin_val;
6158 dst_reg->smax_value >>= umin_val;
6159
6160 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
6161
6162 /* blow away the dst_reg umin_value/umax_value and rely on
6163 * dst_reg var_off to refine the result.
6164 */
6165 dst_reg->umin_value = 0;
6166 dst_reg->umax_value = U64_MAX;
3f50f132
JF
6167
6168 /* Its not easy to operate on alu32 bounds here because it depends
6169 * on bits being shifted in from upper 32-bits. Take easy way out
6170 * and mark unbounded so we can recalculate later from tnum.
6171 */
6172 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6173 __update_reg_bounds(dst_reg);
6174}
6175
468f6eaf
JH
6176/* WARNING: This function does calculations on 64-bit values, but the actual
6177 * execution may occur on 32-bit values. Therefore, things like bitshifts
6178 * need extra checks in the 32-bit case.
6179 */
f1174f77
EC
6180static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6181 struct bpf_insn *insn,
6182 struct bpf_reg_state *dst_reg,
6183 struct bpf_reg_state src_reg)
969bf05e 6184{
638f5b90 6185 struct bpf_reg_state *regs = cur_regs(env);
48461135 6186 u8 opcode = BPF_OP(insn->code);
b0b3fb67 6187 bool src_known;
b03c9f9f
EC
6188 s64 smin_val, smax_val;
6189 u64 umin_val, umax_val;
3f50f132
JF
6190 s32 s32_min_val, s32_max_val;
6191 u32 u32_min_val, u32_max_val;
468f6eaf 6192 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
6193 u32 dst = insn->dst_reg;
6194 int ret;
3f50f132 6195 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 6196
b03c9f9f
EC
6197 smin_val = src_reg.smin_value;
6198 smax_val = src_reg.smax_value;
6199 umin_val = src_reg.umin_value;
6200 umax_val = src_reg.umax_value;
f23cc643 6201
3f50f132
JF
6202 s32_min_val = src_reg.s32_min_value;
6203 s32_max_val = src_reg.s32_max_value;
6204 u32_min_val = src_reg.u32_min_value;
6205 u32_max_val = src_reg.u32_max_value;
6206
6207 if (alu32) {
6208 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
6209 if ((src_known &&
6210 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6211 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6212 /* Taint dst register if offset had invalid bounds
6213 * derived from e.g. dead branches.
6214 */
6215 __mark_reg_unknown(env, dst_reg);
6216 return 0;
6217 }
6218 } else {
6219 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
6220 if ((src_known &&
6221 (smin_val != smax_val || umin_val != umax_val)) ||
6222 smin_val > smax_val || umin_val > umax_val) {
6223 /* Taint dst register if offset had invalid bounds
6224 * derived from e.g. dead branches.
6225 */
6226 __mark_reg_unknown(env, dst_reg);
6227 return 0;
6228 }
6f16101e
DB
6229 }
6230
bb7f0f98
AS
6231 if (!src_known &&
6232 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 6233 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
6234 return 0;
6235 }
6236
3f50f132
JF
6237 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6238 * There are two classes of instructions: The first class we track both
6239 * alu32 and alu64 sign/unsigned bounds independently this provides the
6240 * greatest amount of precision when alu operations are mixed with jmp32
6241 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6242 * and BPF_OR. This is possible because these ops have fairly easy to
6243 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6244 * See alu32 verifier tests for examples. The second class of
6245 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6246 * with regards to tracking sign/unsigned bounds because the bits may
6247 * cross subreg boundaries in the alu64 case. When this happens we mark
6248 * the reg unbounded in the subreg bound space and use the resulting
6249 * tnum to calculate an approximation of the sign/unsigned bounds.
6250 */
48461135
JB
6251 switch (opcode) {
6252 case BPF_ADD:
d3bd7413
DB
6253 ret = sanitize_val_alu(env, insn);
6254 if (ret < 0) {
6255 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6256 return ret;
6257 }
3f50f132 6258 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 6259 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 6260 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
6261 break;
6262 case BPF_SUB:
d3bd7413
DB
6263 ret = sanitize_val_alu(env, insn);
6264 if (ret < 0) {
6265 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6266 return ret;
6267 }
3f50f132 6268 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 6269 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 6270 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
6271 break;
6272 case BPF_MUL:
3f50f132
JF
6273 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6274 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 6275 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
6276 break;
6277 case BPF_AND:
3f50f132
JF
6278 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6279 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 6280 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
6281 break;
6282 case BPF_OR:
3f50f132
JF
6283 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6284 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 6285 scalar_min_max_or(dst_reg, &src_reg);
48461135 6286 break;
2921c90d
YS
6287 case BPF_XOR:
6288 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6289 scalar32_min_max_xor(dst_reg, &src_reg);
6290 scalar_min_max_xor(dst_reg, &src_reg);
6291 break;
48461135 6292 case BPF_LSH:
468f6eaf
JH
6293 if (umax_val >= insn_bitness) {
6294 /* Shifts greater than 31 or 63 are undefined.
6295 * This includes shifts by a negative number.
b03c9f9f 6296 */
61bd5218 6297 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6298 break;
6299 }
3f50f132
JF
6300 if (alu32)
6301 scalar32_min_max_lsh(dst_reg, &src_reg);
6302 else
6303 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
6304 break;
6305 case BPF_RSH:
468f6eaf
JH
6306 if (umax_val >= insn_bitness) {
6307 /* Shifts greater than 31 or 63 are undefined.
6308 * This includes shifts by a negative number.
b03c9f9f 6309 */
61bd5218 6310 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6311 break;
6312 }
3f50f132
JF
6313 if (alu32)
6314 scalar32_min_max_rsh(dst_reg, &src_reg);
6315 else
6316 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 6317 break;
9cbe1f5a
YS
6318 case BPF_ARSH:
6319 if (umax_val >= insn_bitness) {
6320 /* Shifts greater than 31 or 63 are undefined.
6321 * This includes shifts by a negative number.
6322 */
6323 mark_reg_unknown(env, regs, insn->dst_reg);
6324 break;
6325 }
3f50f132
JF
6326 if (alu32)
6327 scalar32_min_max_arsh(dst_reg, &src_reg);
6328 else
6329 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 6330 break;
48461135 6331 default:
61bd5218 6332 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
6333 break;
6334 }
6335
3f50f132
JF
6336 /* ALU32 ops are zero extended into 64bit register */
6337 if (alu32)
6338 zext_32_to_64(dst_reg);
468f6eaf 6339
294f2fc6 6340 __update_reg_bounds(dst_reg);
b03c9f9f
EC
6341 __reg_deduce_bounds(dst_reg);
6342 __reg_bound_offset(dst_reg);
f1174f77
EC
6343 return 0;
6344}
6345
6346/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6347 * and var_off.
6348 */
6349static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6350 struct bpf_insn *insn)
6351{
f4d7e40a
AS
6352 struct bpf_verifier_state *vstate = env->cur_state;
6353 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6354 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
6355 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6356 u8 opcode = BPF_OP(insn->code);
b5dc0163 6357 int err;
f1174f77
EC
6358
6359 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
6360 src_reg = NULL;
6361 if (dst_reg->type != SCALAR_VALUE)
6362 ptr_reg = dst_reg;
6363 if (BPF_SRC(insn->code) == BPF_X) {
6364 src_reg = &regs[insn->src_reg];
f1174f77
EC
6365 if (src_reg->type != SCALAR_VALUE) {
6366 if (dst_reg->type != SCALAR_VALUE) {
6367 /* Combining two pointers by any ALU op yields
82abbf8d
AS
6368 * an arbitrary scalar. Disallow all math except
6369 * pointer subtraction
f1174f77 6370 */
dd066823 6371 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
6372 mark_reg_unknown(env, regs, insn->dst_reg);
6373 return 0;
f1174f77 6374 }
82abbf8d
AS
6375 verbose(env, "R%d pointer %s pointer prohibited\n",
6376 insn->dst_reg,
6377 bpf_alu_string[opcode >> 4]);
6378 return -EACCES;
f1174f77
EC
6379 } else {
6380 /* scalar += pointer
6381 * This is legal, but we have to reverse our
6382 * src/dest handling in computing the range
6383 */
b5dc0163
AS
6384 err = mark_chain_precision(env, insn->dst_reg);
6385 if (err)
6386 return err;
82abbf8d
AS
6387 return adjust_ptr_min_max_vals(env, insn,
6388 src_reg, dst_reg);
f1174f77
EC
6389 }
6390 } else if (ptr_reg) {
6391 /* pointer += scalar */
b5dc0163
AS
6392 err = mark_chain_precision(env, insn->src_reg);
6393 if (err)
6394 return err;
82abbf8d
AS
6395 return adjust_ptr_min_max_vals(env, insn,
6396 dst_reg, src_reg);
f1174f77
EC
6397 }
6398 } else {
6399 /* Pretend the src is a reg with a known value, since we only
6400 * need to be able to read from this state.
6401 */
6402 off_reg.type = SCALAR_VALUE;
b03c9f9f 6403 __mark_reg_known(&off_reg, insn->imm);
f1174f77 6404 src_reg = &off_reg;
82abbf8d
AS
6405 if (ptr_reg) /* pointer += K */
6406 return adjust_ptr_min_max_vals(env, insn,
6407 ptr_reg, src_reg);
f1174f77
EC
6408 }
6409
6410 /* Got here implies adding two SCALAR_VALUEs */
6411 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 6412 print_verifier_state(env, state);
61bd5218 6413 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
6414 return -EINVAL;
6415 }
6416 if (WARN_ON(!src_reg)) {
f4d7e40a 6417 print_verifier_state(env, state);
61bd5218 6418 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
6419 return -EINVAL;
6420 }
6421 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
6422}
6423
17a52670 6424/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 6425static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 6426{
638f5b90 6427 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
6428 u8 opcode = BPF_OP(insn->code);
6429 int err;
6430
6431 if (opcode == BPF_END || opcode == BPF_NEG) {
6432 if (opcode == BPF_NEG) {
6433 if (BPF_SRC(insn->code) != 0 ||
6434 insn->src_reg != BPF_REG_0 ||
6435 insn->off != 0 || insn->imm != 0) {
61bd5218 6436 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
6437 return -EINVAL;
6438 }
6439 } else {
6440 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
6441 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6442 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 6443 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
6444 return -EINVAL;
6445 }
6446 }
6447
6448 /* check src operand */
dc503a8a 6449 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6450 if (err)
6451 return err;
6452
1be7f75d 6453 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 6454 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
6455 insn->dst_reg);
6456 return -EACCES;
6457 }
6458
17a52670 6459 /* check dest operand */
dc503a8a 6460 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
6461 if (err)
6462 return err;
6463
6464 } else if (opcode == BPF_MOV) {
6465
6466 if (BPF_SRC(insn->code) == BPF_X) {
6467 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6468 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6469 return -EINVAL;
6470 }
6471
6472 /* check src operand */
dc503a8a 6473 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6474 if (err)
6475 return err;
6476 } else {
6477 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6478 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6479 return -EINVAL;
6480 }
6481 }
6482
fbeb1603
AF
6483 /* check dest operand, mark as required later */
6484 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
6485 if (err)
6486 return err;
6487
6488 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
6489 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6490 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6491
17a52670
AS
6492 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6493 /* case: R1 = R2
6494 * copy register state to dest reg
6495 */
e434b8cd
JW
6496 *dst_reg = *src_reg;
6497 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6498 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 6499 } else {
f1174f77 6500 /* R1 = (u32) R2 */
1be7f75d 6501 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
6502 verbose(env,
6503 "R%d partial copy of pointer\n",
1be7f75d
AS
6504 insn->src_reg);
6505 return -EACCES;
e434b8cd
JW
6506 } else if (src_reg->type == SCALAR_VALUE) {
6507 *dst_reg = *src_reg;
6508 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6509 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
6510 } else {
6511 mark_reg_unknown(env, regs,
6512 insn->dst_reg);
1be7f75d 6513 }
3f50f132 6514 zext_32_to_64(dst_reg);
17a52670
AS
6515 }
6516 } else {
6517 /* case: R = imm
6518 * remember the value we stored into this reg
6519 */
fbeb1603
AF
6520 /* clear any state __mark_reg_known doesn't set */
6521 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 6522 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
6523 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6524 __mark_reg_known(regs + insn->dst_reg,
6525 insn->imm);
6526 } else {
6527 __mark_reg_known(regs + insn->dst_reg,
6528 (u32)insn->imm);
6529 }
17a52670
AS
6530 }
6531
6532 } else if (opcode > BPF_END) {
61bd5218 6533 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
6534 return -EINVAL;
6535
6536 } else { /* all other ALU ops: and, sub, xor, add, ... */
6537
17a52670
AS
6538 if (BPF_SRC(insn->code) == BPF_X) {
6539 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6540 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6541 return -EINVAL;
6542 }
6543 /* check src1 operand */
dc503a8a 6544 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6545 if (err)
6546 return err;
6547 } else {
6548 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6549 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6550 return -EINVAL;
6551 }
6552 }
6553
6554 /* check src2 operand */
dc503a8a 6555 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6556 if (err)
6557 return err;
6558
6559 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6560 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 6561 verbose(env, "div by zero\n");
17a52670
AS
6562 return -EINVAL;
6563 }
6564
229394e8
RV
6565 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6566 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6567 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6568
6569 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 6570 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
6571 return -EINVAL;
6572 }
6573 }
6574
1a0dc1ac 6575 /* check dest operand */
dc503a8a 6576 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
6577 if (err)
6578 return err;
6579
f1174f77 6580 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
6581 }
6582
6583 return 0;
6584}
6585
c6a9efa1
PC
6586static void __find_good_pkt_pointers(struct bpf_func_state *state,
6587 struct bpf_reg_state *dst_reg,
6588 enum bpf_reg_type type, u16 new_range)
6589{
6590 struct bpf_reg_state *reg;
6591 int i;
6592
6593 for (i = 0; i < MAX_BPF_REG; i++) {
6594 reg = &state->regs[i];
6595 if (reg->type == type && reg->id == dst_reg->id)
6596 /* keep the maximum range already checked */
6597 reg->range = max(reg->range, new_range);
6598 }
6599
6600 bpf_for_each_spilled_reg(i, state, reg) {
6601 if (!reg)
6602 continue;
6603 if (reg->type == type && reg->id == dst_reg->id)
6604 reg->range = max(reg->range, new_range);
6605 }
6606}
6607
f4d7e40a 6608static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 6609 struct bpf_reg_state *dst_reg,
f8ddadc4 6610 enum bpf_reg_type type,
fb2a311a 6611 bool range_right_open)
969bf05e 6612{
fb2a311a 6613 u16 new_range;
c6a9efa1 6614 int i;
2d2be8ca 6615
fb2a311a
DB
6616 if (dst_reg->off < 0 ||
6617 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
6618 /* This doesn't give us any range */
6619 return;
6620
b03c9f9f
EC
6621 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6622 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
6623 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6624 * than pkt_end, but that's because it's also less than pkt.
6625 */
6626 return;
6627
fb2a311a
DB
6628 new_range = dst_reg->off;
6629 if (range_right_open)
6630 new_range--;
6631
6632 /* Examples for register markings:
2d2be8ca 6633 *
fb2a311a 6634 * pkt_data in dst register:
2d2be8ca
DB
6635 *
6636 * r2 = r3;
6637 * r2 += 8;
6638 * if (r2 > pkt_end) goto <handle exception>
6639 * <access okay>
6640 *
b4e432f1
DB
6641 * r2 = r3;
6642 * r2 += 8;
6643 * if (r2 < pkt_end) goto <access okay>
6644 * <handle exception>
6645 *
2d2be8ca
DB
6646 * Where:
6647 * r2 == dst_reg, pkt_end == src_reg
6648 * r2=pkt(id=n,off=8,r=0)
6649 * r3=pkt(id=n,off=0,r=0)
6650 *
fb2a311a 6651 * pkt_data in src register:
2d2be8ca
DB
6652 *
6653 * r2 = r3;
6654 * r2 += 8;
6655 * if (pkt_end >= r2) goto <access okay>
6656 * <handle exception>
6657 *
b4e432f1
DB
6658 * r2 = r3;
6659 * r2 += 8;
6660 * if (pkt_end <= r2) goto <handle exception>
6661 * <access okay>
6662 *
2d2be8ca
DB
6663 * Where:
6664 * pkt_end == dst_reg, r2 == src_reg
6665 * r2=pkt(id=n,off=8,r=0)
6666 * r3=pkt(id=n,off=0,r=0)
6667 *
6668 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
6669 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6670 * and [r3, r3 + 8-1) respectively is safe to access depending on
6671 * the check.
969bf05e 6672 */
2d2be8ca 6673
f1174f77
EC
6674 /* If our ids match, then we must have the same max_value. And we
6675 * don't care about the other reg's fixed offset, since if it's too big
6676 * the range won't allow anything.
6677 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6678 */
c6a9efa1
PC
6679 for (i = 0; i <= vstate->curframe; i++)
6680 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6681 new_range);
969bf05e
AS
6682}
6683
3f50f132 6684static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 6685{
3f50f132
JF
6686 struct tnum subreg = tnum_subreg(reg->var_off);
6687 s32 sval = (s32)val;
a72dafaf 6688
3f50f132
JF
6689 switch (opcode) {
6690 case BPF_JEQ:
6691 if (tnum_is_const(subreg))
6692 return !!tnum_equals_const(subreg, val);
6693 break;
6694 case BPF_JNE:
6695 if (tnum_is_const(subreg))
6696 return !tnum_equals_const(subreg, val);
6697 break;
6698 case BPF_JSET:
6699 if ((~subreg.mask & subreg.value) & val)
6700 return 1;
6701 if (!((subreg.mask | subreg.value) & val))
6702 return 0;
6703 break;
6704 case BPF_JGT:
6705 if (reg->u32_min_value > val)
6706 return 1;
6707 else if (reg->u32_max_value <= val)
6708 return 0;
6709 break;
6710 case BPF_JSGT:
6711 if (reg->s32_min_value > sval)
6712 return 1;
6713 else if (reg->s32_max_value < sval)
6714 return 0;
6715 break;
6716 case BPF_JLT:
6717 if (reg->u32_max_value < val)
6718 return 1;
6719 else if (reg->u32_min_value >= val)
6720 return 0;
6721 break;
6722 case BPF_JSLT:
6723 if (reg->s32_max_value < sval)
6724 return 1;
6725 else if (reg->s32_min_value >= sval)
6726 return 0;
6727 break;
6728 case BPF_JGE:
6729 if (reg->u32_min_value >= val)
6730 return 1;
6731 else if (reg->u32_max_value < val)
6732 return 0;
6733 break;
6734 case BPF_JSGE:
6735 if (reg->s32_min_value >= sval)
6736 return 1;
6737 else if (reg->s32_max_value < sval)
6738 return 0;
6739 break;
6740 case BPF_JLE:
6741 if (reg->u32_max_value <= val)
6742 return 1;
6743 else if (reg->u32_min_value > val)
6744 return 0;
6745 break;
6746 case BPF_JSLE:
6747 if (reg->s32_max_value <= sval)
6748 return 1;
6749 else if (reg->s32_min_value > sval)
6750 return 0;
6751 break;
6752 }
4f7b3e82 6753
3f50f132
JF
6754 return -1;
6755}
092ed096 6756
3f50f132
JF
6757
6758static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6759{
6760 s64 sval = (s64)val;
a72dafaf 6761
4f7b3e82
AS
6762 switch (opcode) {
6763 case BPF_JEQ:
6764 if (tnum_is_const(reg->var_off))
6765 return !!tnum_equals_const(reg->var_off, val);
6766 break;
6767 case BPF_JNE:
6768 if (tnum_is_const(reg->var_off))
6769 return !tnum_equals_const(reg->var_off, val);
6770 break;
960ea056
JK
6771 case BPF_JSET:
6772 if ((~reg->var_off.mask & reg->var_off.value) & val)
6773 return 1;
6774 if (!((reg->var_off.mask | reg->var_off.value) & val))
6775 return 0;
6776 break;
4f7b3e82
AS
6777 case BPF_JGT:
6778 if (reg->umin_value > val)
6779 return 1;
6780 else if (reg->umax_value <= val)
6781 return 0;
6782 break;
6783 case BPF_JSGT:
a72dafaf 6784 if (reg->smin_value > sval)
4f7b3e82 6785 return 1;
a72dafaf 6786 else if (reg->smax_value < sval)
4f7b3e82
AS
6787 return 0;
6788 break;
6789 case BPF_JLT:
6790 if (reg->umax_value < val)
6791 return 1;
6792 else if (reg->umin_value >= val)
6793 return 0;
6794 break;
6795 case BPF_JSLT:
a72dafaf 6796 if (reg->smax_value < sval)
4f7b3e82 6797 return 1;
a72dafaf 6798 else if (reg->smin_value >= sval)
4f7b3e82
AS
6799 return 0;
6800 break;
6801 case BPF_JGE:
6802 if (reg->umin_value >= val)
6803 return 1;
6804 else if (reg->umax_value < val)
6805 return 0;
6806 break;
6807 case BPF_JSGE:
a72dafaf 6808 if (reg->smin_value >= sval)
4f7b3e82 6809 return 1;
a72dafaf 6810 else if (reg->smax_value < sval)
4f7b3e82
AS
6811 return 0;
6812 break;
6813 case BPF_JLE:
6814 if (reg->umax_value <= val)
6815 return 1;
6816 else if (reg->umin_value > val)
6817 return 0;
6818 break;
6819 case BPF_JSLE:
a72dafaf 6820 if (reg->smax_value <= sval)
4f7b3e82 6821 return 1;
a72dafaf 6822 else if (reg->smin_value > sval)
4f7b3e82
AS
6823 return 0;
6824 break;
6825 }
6826
6827 return -1;
6828}
6829
3f50f132
JF
6830/* compute branch direction of the expression "if (reg opcode val) goto target;"
6831 * and return:
6832 * 1 - branch will be taken and "goto target" will be executed
6833 * 0 - branch will not be taken and fall-through to next insn
6834 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6835 * range [0,10]
604dca5e 6836 */
3f50f132
JF
6837static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6838 bool is_jmp32)
604dca5e 6839{
cac616db
JF
6840 if (__is_pointer_value(false, reg)) {
6841 if (!reg_type_not_null(reg->type))
6842 return -1;
6843
6844 /* If pointer is valid tests against zero will fail so we can
6845 * use this to direct branch taken.
6846 */
6847 if (val != 0)
6848 return -1;
6849
6850 switch (opcode) {
6851 case BPF_JEQ:
6852 return 0;
6853 case BPF_JNE:
6854 return 1;
6855 default:
6856 return -1;
6857 }
6858 }
604dca5e 6859
3f50f132
JF
6860 if (is_jmp32)
6861 return is_branch32_taken(reg, val, opcode);
6862 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
6863}
6864
48461135
JB
6865/* Adjusts the register min/max values in the case that the dst_reg is the
6866 * variable register that we are working on, and src_reg is a constant or we're
6867 * simply doing a BPF_K check.
f1174f77 6868 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
6869 */
6870static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
6871 struct bpf_reg_state *false_reg,
6872 u64 val, u32 val32,
092ed096 6873 u8 opcode, bool is_jmp32)
48461135 6874{
3f50f132
JF
6875 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6876 struct tnum false_64off = false_reg->var_off;
6877 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6878 struct tnum true_64off = true_reg->var_off;
6879 s64 sval = (s64)val;
6880 s32 sval32 = (s32)val32;
a72dafaf 6881
f1174f77
EC
6882 /* If the dst_reg is a pointer, we can't learn anything about its
6883 * variable offset from the compare (unless src_reg were a pointer into
6884 * the same object, but we don't bother with that.
6885 * Since false_reg and true_reg have the same type by construction, we
6886 * only need to check one of them for pointerness.
6887 */
6888 if (__is_pointer_value(false, false_reg))
6889 return;
4cabc5b1 6890
48461135
JB
6891 switch (opcode) {
6892 case BPF_JEQ:
48461135 6893 case BPF_JNE:
a72dafaf
JW
6894 {
6895 struct bpf_reg_state *reg =
6896 opcode == BPF_JEQ ? true_reg : false_reg;
6897
6898 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6899 * if it is true we know the value for sure. Likewise for
6900 * BPF_JNE.
48461135 6901 */
3f50f132
JF
6902 if (is_jmp32)
6903 __mark_reg32_known(reg, val32);
6904 else
092ed096 6905 __mark_reg_known(reg, val);
48461135 6906 break;
a72dafaf 6907 }
960ea056 6908 case BPF_JSET:
3f50f132
JF
6909 if (is_jmp32) {
6910 false_32off = tnum_and(false_32off, tnum_const(~val32));
6911 if (is_power_of_2(val32))
6912 true_32off = tnum_or(true_32off,
6913 tnum_const(val32));
6914 } else {
6915 false_64off = tnum_and(false_64off, tnum_const(~val));
6916 if (is_power_of_2(val))
6917 true_64off = tnum_or(true_64off,
6918 tnum_const(val));
6919 }
960ea056 6920 break;
48461135 6921 case BPF_JGE:
a72dafaf
JW
6922 case BPF_JGT:
6923 {
3f50f132
JF
6924 if (is_jmp32) {
6925 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
6926 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6927
6928 false_reg->u32_max_value = min(false_reg->u32_max_value,
6929 false_umax);
6930 true_reg->u32_min_value = max(true_reg->u32_min_value,
6931 true_umin);
6932 } else {
6933 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
6934 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6935
6936 false_reg->umax_value = min(false_reg->umax_value, false_umax);
6937 true_reg->umin_value = max(true_reg->umin_value, true_umin);
6938 }
b03c9f9f 6939 break;
a72dafaf 6940 }
48461135 6941 case BPF_JSGE:
a72dafaf
JW
6942 case BPF_JSGT:
6943 {
3f50f132
JF
6944 if (is_jmp32) {
6945 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
6946 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 6947
3f50f132
JF
6948 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6949 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6950 } else {
6951 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
6952 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6953
6954 false_reg->smax_value = min(false_reg->smax_value, false_smax);
6955 true_reg->smin_value = max(true_reg->smin_value, true_smin);
6956 }
48461135 6957 break;
a72dafaf 6958 }
b4e432f1 6959 case BPF_JLE:
a72dafaf
JW
6960 case BPF_JLT:
6961 {
3f50f132
JF
6962 if (is_jmp32) {
6963 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
6964 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6965
6966 false_reg->u32_min_value = max(false_reg->u32_min_value,
6967 false_umin);
6968 true_reg->u32_max_value = min(true_reg->u32_max_value,
6969 true_umax);
6970 } else {
6971 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
6972 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6973
6974 false_reg->umin_value = max(false_reg->umin_value, false_umin);
6975 true_reg->umax_value = min(true_reg->umax_value, true_umax);
6976 }
b4e432f1 6977 break;
a72dafaf 6978 }
b4e432f1 6979 case BPF_JSLE:
a72dafaf
JW
6980 case BPF_JSLT:
6981 {
3f50f132
JF
6982 if (is_jmp32) {
6983 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
6984 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 6985
3f50f132
JF
6986 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6987 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6988 } else {
6989 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
6990 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6991
6992 false_reg->smin_value = max(false_reg->smin_value, false_smin);
6993 true_reg->smax_value = min(true_reg->smax_value, true_smax);
6994 }
b4e432f1 6995 break;
a72dafaf 6996 }
48461135 6997 default:
0fc31b10 6998 return;
48461135
JB
6999 }
7000
3f50f132
JF
7001 if (is_jmp32) {
7002 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7003 tnum_subreg(false_32off));
7004 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7005 tnum_subreg(true_32off));
7006 __reg_combine_32_into_64(false_reg);
7007 __reg_combine_32_into_64(true_reg);
7008 } else {
7009 false_reg->var_off = false_64off;
7010 true_reg->var_off = true_64off;
7011 __reg_combine_64_into_32(false_reg);
7012 __reg_combine_64_into_32(true_reg);
7013 }
48461135
JB
7014}
7015
f1174f77
EC
7016/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7017 * the variable reg.
48461135
JB
7018 */
7019static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
7020 struct bpf_reg_state *false_reg,
7021 u64 val, u32 val32,
092ed096 7022 u8 opcode, bool is_jmp32)
48461135 7023{
0fc31b10
JH
7024 /* How can we transform "a <op> b" into "b <op> a"? */
7025 static const u8 opcode_flip[16] = {
7026 /* these stay the same */
7027 [BPF_JEQ >> 4] = BPF_JEQ,
7028 [BPF_JNE >> 4] = BPF_JNE,
7029 [BPF_JSET >> 4] = BPF_JSET,
7030 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7031 [BPF_JGE >> 4] = BPF_JLE,
7032 [BPF_JGT >> 4] = BPF_JLT,
7033 [BPF_JLE >> 4] = BPF_JGE,
7034 [BPF_JLT >> 4] = BPF_JGT,
7035 [BPF_JSGE >> 4] = BPF_JSLE,
7036 [BPF_JSGT >> 4] = BPF_JSLT,
7037 [BPF_JSLE >> 4] = BPF_JSGE,
7038 [BPF_JSLT >> 4] = BPF_JSGT
7039 };
7040 opcode = opcode_flip[opcode >> 4];
7041 /* This uses zero as "not present in table"; luckily the zero opcode,
7042 * BPF_JA, can't get here.
b03c9f9f 7043 */
0fc31b10 7044 if (opcode)
3f50f132 7045 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7046}
7047
7048/* Regs are known to be equal, so intersect their min/max/var_off */
7049static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7050 struct bpf_reg_state *dst_reg)
7051{
b03c9f9f
EC
7052 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7053 dst_reg->umin_value);
7054 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7055 dst_reg->umax_value);
7056 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7057 dst_reg->smin_value);
7058 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7059 dst_reg->smax_value);
f1174f77
EC
7060 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7061 dst_reg->var_off);
b03c9f9f
EC
7062 /* We might have learned new bounds from the var_off. */
7063 __update_reg_bounds(src_reg);
7064 __update_reg_bounds(dst_reg);
7065 /* We might have learned something about the sign bit. */
7066 __reg_deduce_bounds(src_reg);
7067 __reg_deduce_bounds(dst_reg);
7068 /* We might have learned some bits from the bounds. */
7069 __reg_bound_offset(src_reg);
7070 __reg_bound_offset(dst_reg);
7071 /* Intersecting with the old var_off might have improved our bounds
7072 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7073 * then new var_off is (0; 0x7f...fc) which improves our umax.
7074 */
7075 __update_reg_bounds(src_reg);
7076 __update_reg_bounds(dst_reg);
f1174f77
EC
7077}
7078
7079static void reg_combine_min_max(struct bpf_reg_state *true_src,
7080 struct bpf_reg_state *true_dst,
7081 struct bpf_reg_state *false_src,
7082 struct bpf_reg_state *false_dst,
7083 u8 opcode)
7084{
7085 switch (opcode) {
7086 case BPF_JEQ:
7087 __reg_combine_min_max(true_src, true_dst);
7088 break;
7089 case BPF_JNE:
7090 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 7091 break;
4cabc5b1 7092 }
48461135
JB
7093}
7094
fd978bf7
JS
7095static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7096 struct bpf_reg_state *reg, u32 id,
840b9615 7097 bool is_null)
57a09bf0 7098{
840b9615 7099 if (reg_type_may_be_null(reg->type) && reg->id == id) {
f1174f77
EC
7100 /* Old offset (both fixed and variable parts) should
7101 * have been known-zero, because we don't allow pointer
7102 * arithmetic on pointers that might be NULL.
7103 */
b03c9f9f
EC
7104 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7105 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 7106 reg->off)) {
b03c9f9f
EC
7107 __mark_reg_known_zero(reg);
7108 reg->off = 0;
f1174f77
EC
7109 }
7110 if (is_null) {
7111 reg->type = SCALAR_VALUE;
840b9615 7112 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
64d85290
JS
7113 const struct bpf_map *map = reg->map_ptr;
7114
7115 if (map->inner_map_meta) {
840b9615 7116 reg->type = CONST_PTR_TO_MAP;
64d85290
JS
7117 reg->map_ptr = map->inner_map_meta;
7118 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
fada7fdc 7119 reg->type = PTR_TO_XDP_SOCK;
64d85290
JS
7120 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7121 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7122 reg->type = PTR_TO_SOCKET;
840b9615
JS
7123 } else {
7124 reg->type = PTR_TO_MAP_VALUE;
7125 }
c64b7983
JS
7126 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7127 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
7128 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7129 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
7130 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7131 reg->type = PTR_TO_TCP_SOCK;
b121b341
YS
7132 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7133 reg->type = PTR_TO_BTF_ID;
457f4436
AN
7134 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7135 reg->type = PTR_TO_MEM;
afbf21dc
YS
7136 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7137 reg->type = PTR_TO_RDONLY_BUF;
7138 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7139 reg->type = PTR_TO_RDWR_BUF;
56f668df 7140 }
1b986589
MKL
7141 if (is_null) {
7142 /* We don't need id and ref_obj_id from this point
7143 * onwards anymore, thus we should better reset it,
7144 * so that state pruning has chances to take effect.
7145 */
7146 reg->id = 0;
7147 reg->ref_obj_id = 0;
7148 } else if (!reg_may_point_to_spin_lock(reg)) {
7149 /* For not-NULL ptr, reg->ref_obj_id will be reset
7150 * in release_reg_references().
7151 *
7152 * reg->id is still used by spin_lock ptr. Other
7153 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
7154 */
7155 reg->id = 0;
56f668df 7156 }
57a09bf0
TG
7157 }
7158}
7159
c6a9efa1
PC
7160static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7161 bool is_null)
7162{
7163 struct bpf_reg_state *reg;
7164 int i;
7165
7166 for (i = 0; i < MAX_BPF_REG; i++)
7167 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7168
7169 bpf_for_each_spilled_reg(i, state, reg) {
7170 if (!reg)
7171 continue;
7172 mark_ptr_or_null_reg(state, reg, id, is_null);
7173 }
7174}
7175
57a09bf0
TG
7176/* The logic is similar to find_good_pkt_pointers(), both could eventually
7177 * be folded together at some point.
7178 */
840b9615
JS
7179static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7180 bool is_null)
57a09bf0 7181{
f4d7e40a 7182 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 7183 struct bpf_reg_state *regs = state->regs;
1b986589 7184 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 7185 u32 id = regs[regno].id;
c6a9efa1 7186 int i;
57a09bf0 7187
1b986589
MKL
7188 if (ref_obj_id && ref_obj_id == id && is_null)
7189 /* regs[regno] is in the " == NULL" branch.
7190 * No one could have freed the reference state before
7191 * doing the NULL check.
7192 */
7193 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 7194
c6a9efa1
PC
7195 for (i = 0; i <= vstate->curframe; i++)
7196 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
7197}
7198
5beca081
DB
7199static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7200 struct bpf_reg_state *dst_reg,
7201 struct bpf_reg_state *src_reg,
7202 struct bpf_verifier_state *this_branch,
7203 struct bpf_verifier_state *other_branch)
7204{
7205 if (BPF_SRC(insn->code) != BPF_X)
7206 return false;
7207
092ed096
JW
7208 /* Pointers are always 64-bit. */
7209 if (BPF_CLASS(insn->code) == BPF_JMP32)
7210 return false;
7211
5beca081
DB
7212 switch (BPF_OP(insn->code)) {
7213 case BPF_JGT:
7214 if ((dst_reg->type == PTR_TO_PACKET &&
7215 src_reg->type == PTR_TO_PACKET_END) ||
7216 (dst_reg->type == PTR_TO_PACKET_META &&
7217 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7218 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7219 find_good_pkt_pointers(this_branch, dst_reg,
7220 dst_reg->type, false);
7221 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7222 src_reg->type == PTR_TO_PACKET) ||
7223 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7224 src_reg->type == PTR_TO_PACKET_META)) {
7225 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7226 find_good_pkt_pointers(other_branch, src_reg,
7227 src_reg->type, true);
7228 } else {
7229 return false;
7230 }
7231 break;
7232 case BPF_JLT:
7233 if ((dst_reg->type == PTR_TO_PACKET &&
7234 src_reg->type == PTR_TO_PACKET_END) ||
7235 (dst_reg->type == PTR_TO_PACKET_META &&
7236 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7237 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7238 find_good_pkt_pointers(other_branch, dst_reg,
7239 dst_reg->type, true);
7240 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7241 src_reg->type == PTR_TO_PACKET) ||
7242 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7243 src_reg->type == PTR_TO_PACKET_META)) {
7244 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7245 find_good_pkt_pointers(this_branch, src_reg,
7246 src_reg->type, false);
7247 } else {
7248 return false;
7249 }
7250 break;
7251 case BPF_JGE:
7252 if ((dst_reg->type == PTR_TO_PACKET &&
7253 src_reg->type == PTR_TO_PACKET_END) ||
7254 (dst_reg->type == PTR_TO_PACKET_META &&
7255 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7256 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7257 find_good_pkt_pointers(this_branch, dst_reg,
7258 dst_reg->type, true);
7259 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7260 src_reg->type == PTR_TO_PACKET) ||
7261 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7262 src_reg->type == PTR_TO_PACKET_META)) {
7263 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7264 find_good_pkt_pointers(other_branch, src_reg,
7265 src_reg->type, false);
7266 } else {
7267 return false;
7268 }
7269 break;
7270 case BPF_JLE:
7271 if ((dst_reg->type == PTR_TO_PACKET &&
7272 src_reg->type == PTR_TO_PACKET_END) ||
7273 (dst_reg->type == PTR_TO_PACKET_META &&
7274 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7275 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7276 find_good_pkt_pointers(other_branch, dst_reg,
7277 dst_reg->type, false);
7278 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7279 src_reg->type == PTR_TO_PACKET) ||
7280 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7281 src_reg->type == PTR_TO_PACKET_META)) {
7282 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7283 find_good_pkt_pointers(this_branch, src_reg,
7284 src_reg->type, true);
7285 } else {
7286 return false;
7287 }
7288 break;
7289 default:
7290 return false;
7291 }
7292
7293 return true;
7294}
7295
58e2af8b 7296static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
7297 struct bpf_insn *insn, int *insn_idx)
7298{
f4d7e40a
AS
7299 struct bpf_verifier_state *this_branch = env->cur_state;
7300 struct bpf_verifier_state *other_branch;
7301 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 7302 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 7303 u8 opcode = BPF_OP(insn->code);
092ed096 7304 bool is_jmp32;
fb8d251e 7305 int pred = -1;
17a52670
AS
7306 int err;
7307
092ed096
JW
7308 /* Only conditional jumps are expected to reach here. */
7309 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7310 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
7311 return -EINVAL;
7312 }
7313
7314 if (BPF_SRC(insn->code) == BPF_X) {
7315 if (insn->imm != 0) {
092ed096 7316 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7317 return -EINVAL;
7318 }
7319
7320 /* check src1 operand */
dc503a8a 7321 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7322 if (err)
7323 return err;
1be7f75d
AS
7324
7325 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 7326 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
7327 insn->src_reg);
7328 return -EACCES;
7329 }
fb8d251e 7330 src_reg = &regs[insn->src_reg];
17a52670
AS
7331 } else {
7332 if (insn->src_reg != BPF_REG_0) {
092ed096 7333 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7334 return -EINVAL;
7335 }
7336 }
7337
7338 /* check src2 operand */
dc503a8a 7339 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7340 if (err)
7341 return err;
7342
1a0dc1ac 7343 dst_reg = &regs[insn->dst_reg];
092ed096 7344 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 7345
3f50f132
JF
7346 if (BPF_SRC(insn->code) == BPF_K) {
7347 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7348 } else if (src_reg->type == SCALAR_VALUE &&
7349 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7350 pred = is_branch_taken(dst_reg,
7351 tnum_subreg(src_reg->var_off).value,
7352 opcode,
7353 is_jmp32);
7354 } else if (src_reg->type == SCALAR_VALUE &&
7355 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7356 pred = is_branch_taken(dst_reg,
7357 src_reg->var_off.value,
7358 opcode,
7359 is_jmp32);
7360 }
7361
b5dc0163 7362 if (pred >= 0) {
cac616db
JF
7363 /* If we get here with a dst_reg pointer type it is because
7364 * above is_branch_taken() special cased the 0 comparison.
7365 */
7366 if (!__is_pointer_value(false, dst_reg))
7367 err = mark_chain_precision(env, insn->dst_reg);
b5dc0163
AS
7368 if (BPF_SRC(insn->code) == BPF_X && !err)
7369 err = mark_chain_precision(env, insn->src_reg);
7370 if (err)
7371 return err;
7372 }
fb8d251e
AS
7373 if (pred == 1) {
7374 /* only follow the goto, ignore fall-through */
7375 *insn_idx += insn->off;
7376 return 0;
7377 } else if (pred == 0) {
7378 /* only follow fall-through branch, since
7379 * that's where the program will go
7380 */
7381 return 0;
17a52670
AS
7382 }
7383
979d63d5
DB
7384 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7385 false);
17a52670
AS
7386 if (!other_branch)
7387 return -EFAULT;
f4d7e40a 7388 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 7389
48461135
JB
7390 /* detect if we are comparing against a constant value so we can adjust
7391 * our min/max values for our dst register.
f1174f77
EC
7392 * this is only legit if both are scalars (or pointers to the same
7393 * object, I suppose, but we don't support that right now), because
7394 * otherwise the different base pointers mean the offsets aren't
7395 * comparable.
48461135
JB
7396 */
7397 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 7398 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 7399
f1174f77 7400 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
7401 src_reg->type == SCALAR_VALUE) {
7402 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
7403 (is_jmp32 &&
7404 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 7405 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 7406 dst_reg,
3f50f132
JF
7407 src_reg->var_off.value,
7408 tnum_subreg(src_reg->var_off).value,
092ed096
JW
7409 opcode, is_jmp32);
7410 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
7411 (is_jmp32 &&
7412 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 7413 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 7414 src_reg,
3f50f132
JF
7415 dst_reg->var_off.value,
7416 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
7417 opcode, is_jmp32);
7418 else if (!is_jmp32 &&
7419 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 7420 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
7421 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7422 &other_branch_regs[insn->dst_reg],
092ed096 7423 src_reg, dst_reg, opcode);
f1174f77
EC
7424 }
7425 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 7426 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
7427 dst_reg, insn->imm, (u32)insn->imm,
7428 opcode, is_jmp32);
48461135
JB
7429 }
7430
092ed096
JW
7431 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7432 * NOTE: these optimizations below are related with pointer comparison
7433 * which will never be JMP32.
7434 */
7435 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 7436 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
7437 reg_type_may_be_null(dst_reg->type)) {
7438 /* Mark all identical registers in each branch as either
57a09bf0
TG
7439 * safe or unknown depending R == 0 or R != 0 conditional.
7440 */
840b9615
JS
7441 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7442 opcode == BPF_JNE);
7443 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7444 opcode == BPF_JEQ);
5beca081
DB
7445 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7446 this_branch, other_branch) &&
7447 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
7448 verbose(env, "R%d pointer comparison prohibited\n",
7449 insn->dst_reg);
1be7f75d 7450 return -EACCES;
17a52670 7451 }
06ee7115 7452 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 7453 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
7454 return 0;
7455}
7456
17a52670 7457/* verify BPF_LD_IMM64 instruction */
58e2af8b 7458static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7459{
d8eca5bb 7460 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 7461 struct bpf_reg_state *regs = cur_regs(env);
d8eca5bb 7462 struct bpf_map *map;
17a52670
AS
7463 int err;
7464
7465 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 7466 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
7467 return -EINVAL;
7468 }
7469 if (insn->off != 0) {
61bd5218 7470 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
7471 return -EINVAL;
7472 }
7473
dc503a8a 7474 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7475 if (err)
7476 return err;
7477
6b173873 7478 if (insn->src_reg == 0) {
6b173873
JK
7479 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7480
f1174f77 7481 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 7482 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 7483 return 0;
6b173873 7484 }
17a52670 7485
d8eca5bb
DB
7486 map = env->used_maps[aux->map_index];
7487 mark_reg_known_zero(env, regs, insn->dst_reg);
7488 regs[insn->dst_reg].map_ptr = map;
7489
7490 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7491 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
7492 regs[insn->dst_reg].off = aux->map_off;
7493 if (map_value_has_spin_lock(map))
7494 regs[insn->dst_reg].id = ++env->id_gen;
7495 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7496 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
7497 } else {
7498 verbose(env, "bpf verifier is misconfigured\n");
7499 return -EINVAL;
7500 }
17a52670 7501
17a52670
AS
7502 return 0;
7503}
7504
96be4325
DB
7505static bool may_access_skb(enum bpf_prog_type type)
7506{
7507 switch (type) {
7508 case BPF_PROG_TYPE_SOCKET_FILTER:
7509 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 7510 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
7511 return true;
7512 default:
7513 return false;
7514 }
7515}
7516
ddd872bc
AS
7517/* verify safety of LD_ABS|LD_IND instructions:
7518 * - they can only appear in the programs where ctx == skb
7519 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7520 * preserve R6-R9, and store return value into R0
7521 *
7522 * Implicit input:
7523 * ctx == skb == R6 == CTX
7524 *
7525 * Explicit input:
7526 * SRC == any register
7527 * IMM == 32-bit immediate
7528 *
7529 * Output:
7530 * R0 - 8/16/32-bit skb data converted to cpu endianness
7531 */
58e2af8b 7532static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 7533{
638f5b90 7534 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 7535 static const int ctx_reg = BPF_REG_6;
ddd872bc 7536 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
7537 int i, err;
7538
7e40781c 7539 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 7540 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
7541 return -EINVAL;
7542 }
7543
e0cea7ce
DB
7544 if (!env->ops->gen_ld_abs) {
7545 verbose(env, "bpf verifier is misconfigured\n");
7546 return -EINVAL;
7547 }
7548
ddd872bc 7549 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 7550 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 7551 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 7552 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
7553 return -EINVAL;
7554 }
7555
7556 /* check whether implicit source operand (register R6) is readable */
6d4f151a 7557 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
7558 if (err)
7559 return err;
7560
fd978bf7
JS
7561 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7562 * gen_ld_abs() may terminate the program at runtime, leading to
7563 * reference leak.
7564 */
7565 err = check_reference_leak(env);
7566 if (err) {
7567 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7568 return err;
7569 }
7570
d83525ca
AS
7571 if (env->cur_state->active_spin_lock) {
7572 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7573 return -EINVAL;
7574 }
7575
6d4f151a 7576 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
7577 verbose(env,
7578 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
7579 return -EINVAL;
7580 }
7581
7582 if (mode == BPF_IND) {
7583 /* check explicit source operand */
dc503a8a 7584 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
7585 if (err)
7586 return err;
7587 }
7588
6d4f151a
DB
7589 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7590 if (err < 0)
7591 return err;
7592
ddd872bc 7593 /* reset caller saved regs to unreadable */
dc503a8a 7594 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 7595 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
7596 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7597 }
ddd872bc
AS
7598
7599 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
7600 * the value fetched from the packet.
7601 * Already marked as written above.
ddd872bc 7602 */
61bd5218 7603 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
7604 /* ld_abs load up to 32-bit skb data. */
7605 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
7606 return 0;
7607}
7608
390ee7e2
AS
7609static int check_return_code(struct bpf_verifier_env *env)
7610{
5cf1e914 7611 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 7612 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
7613 struct bpf_reg_state *reg;
7614 struct tnum range = tnum_range(0, 1);
7e40781c 7615 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997
MKL
7616 int err;
7617
9e4e01df 7618 /* LSM and struct_ops func-ptr's return type could be "void" */
7e40781c
UP
7619 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7620 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
7621 !prog->aux->attach_func_proto->type)
7622 return 0;
7623
7624 /* eBPF calling convetion is such that R0 is used
7625 * to return the value from eBPF program.
7626 * Make sure that it's readable at this time
7627 * of bpf_exit, which means that program wrote
7628 * something into it earlier
7629 */
7630 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7631 if (err)
7632 return err;
7633
7634 if (is_pointer_value(env, BPF_REG_0)) {
7635 verbose(env, "R0 leaks addr as return value\n");
7636 return -EACCES;
7637 }
390ee7e2 7638
7e40781c 7639 switch (prog_type) {
983695fa
DB
7640 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7641 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
7642 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7643 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7644 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7645 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7646 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 7647 range = tnum_range(1, 1);
ed4ed404 7648 break;
390ee7e2 7649 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 7650 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7651 range = tnum_range(0, 3);
7652 enforce_attach_type_range = tnum_range(2, 3);
7653 }
ed4ed404 7654 break;
390ee7e2
AS
7655 case BPF_PROG_TYPE_CGROUP_SOCK:
7656 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 7657 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 7658 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 7659 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 7660 break;
15ab09bd
AS
7661 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7662 if (!env->prog->aux->attach_btf_id)
7663 return 0;
7664 range = tnum_const(0);
7665 break;
15d83c4d 7666 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
7667 switch (env->prog->expected_attach_type) {
7668 case BPF_TRACE_FENTRY:
7669 case BPF_TRACE_FEXIT:
7670 range = tnum_const(0);
7671 break;
7672 case BPF_TRACE_RAW_TP:
7673 case BPF_MODIFY_RETURN:
15d83c4d 7674 return 0;
2ec0616e
DB
7675 case BPF_TRACE_ITER:
7676 break;
e92888c7
YS
7677 default:
7678 return -ENOTSUPP;
7679 }
15d83c4d 7680 break;
e9ddbb77
JS
7681 case BPF_PROG_TYPE_SK_LOOKUP:
7682 range = tnum_range(SK_DROP, SK_PASS);
7683 break;
e92888c7
YS
7684 case BPF_PROG_TYPE_EXT:
7685 /* freplace program can return anything as its return value
7686 * depends on the to-be-replaced kernel func or bpf program.
7687 */
390ee7e2
AS
7688 default:
7689 return 0;
7690 }
7691
638f5b90 7692 reg = cur_regs(env) + BPF_REG_0;
390ee7e2 7693 if (reg->type != SCALAR_VALUE) {
61bd5218 7694 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
7695 reg_type_str[reg->type]);
7696 return -EINVAL;
7697 }
7698
7699 if (!tnum_in(range, reg->var_off)) {
5cf1e914 7700 char tn_buf[48];
7701
61bd5218 7702 verbose(env, "At program exit the register R0 ");
390ee7e2 7703 if (!tnum_is_unknown(reg->var_off)) {
390ee7e2 7704 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 7705 verbose(env, "has value %s", tn_buf);
390ee7e2 7706 } else {
61bd5218 7707 verbose(env, "has unknown scalar value");
390ee7e2 7708 }
5cf1e914 7709 tnum_strn(tn_buf, sizeof(tn_buf), range);
983695fa 7710 verbose(env, " should have been in %s\n", tn_buf);
390ee7e2
AS
7711 return -EINVAL;
7712 }
5cf1e914 7713
7714 if (!tnum_is_unknown(enforce_attach_type_range) &&
7715 tnum_in(enforce_attach_type_range, reg->var_off))
7716 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
7717 return 0;
7718}
7719
475fb78f
AS
7720/* non-recursive DFS pseudo code
7721 * 1 procedure DFS-iterative(G,v):
7722 * 2 label v as discovered
7723 * 3 let S be a stack
7724 * 4 S.push(v)
7725 * 5 while S is not empty
7726 * 6 t <- S.pop()
7727 * 7 if t is what we're looking for:
7728 * 8 return t
7729 * 9 for all edges e in G.adjacentEdges(t) do
7730 * 10 if edge e is already labelled
7731 * 11 continue with the next edge
7732 * 12 w <- G.adjacentVertex(t,e)
7733 * 13 if vertex w is not discovered and not explored
7734 * 14 label e as tree-edge
7735 * 15 label w as discovered
7736 * 16 S.push(w)
7737 * 17 continue at 5
7738 * 18 else if vertex w is discovered
7739 * 19 label e as back-edge
7740 * 20 else
7741 * 21 // vertex w is explored
7742 * 22 label e as forward- or cross-edge
7743 * 23 label t as explored
7744 * 24 S.pop()
7745 *
7746 * convention:
7747 * 0x10 - discovered
7748 * 0x11 - discovered and fall-through edge labelled
7749 * 0x12 - discovered and fall-through and branch edges labelled
7750 * 0x20 - explored
7751 */
7752
7753enum {
7754 DISCOVERED = 0x10,
7755 EXPLORED = 0x20,
7756 FALLTHROUGH = 1,
7757 BRANCH = 2,
7758};
7759
dc2a4ebc
AS
7760static u32 state_htab_size(struct bpf_verifier_env *env)
7761{
7762 return env->prog->len;
7763}
7764
5d839021
AS
7765static struct bpf_verifier_state_list **explored_state(
7766 struct bpf_verifier_env *env,
7767 int idx)
7768{
dc2a4ebc
AS
7769 struct bpf_verifier_state *cur = env->cur_state;
7770 struct bpf_func_state *state = cur->frame[cur->curframe];
7771
7772 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
7773}
7774
7775static void init_explored_state(struct bpf_verifier_env *env, int idx)
7776{
a8f500af 7777 env->insn_aux_data[idx].prune_point = true;
5d839021 7778}
f1bca824 7779
475fb78f
AS
7780/* t, w, e - match pseudo-code above:
7781 * t - index of current instruction
7782 * w - next instruction
7783 * e - edge
7784 */
2589726d
AS
7785static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7786 bool loop_ok)
475fb78f 7787{
7df737e9
AS
7788 int *insn_stack = env->cfg.insn_stack;
7789 int *insn_state = env->cfg.insn_state;
7790
475fb78f
AS
7791 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7792 return 0;
7793
7794 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7795 return 0;
7796
7797 if (w < 0 || w >= env->prog->len) {
d9762e84 7798 verbose_linfo(env, t, "%d: ", t);
61bd5218 7799 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
7800 return -EINVAL;
7801 }
7802
f1bca824
AS
7803 if (e == BRANCH)
7804 /* mark branch target for state pruning */
5d839021 7805 init_explored_state(env, w);
f1bca824 7806
475fb78f
AS
7807 if (insn_state[w] == 0) {
7808 /* tree-edge */
7809 insn_state[t] = DISCOVERED | e;
7810 insn_state[w] = DISCOVERED;
7df737e9 7811 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 7812 return -E2BIG;
7df737e9 7813 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
7814 return 1;
7815 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 7816 if (loop_ok && env->bpf_capable)
2589726d 7817 return 0;
d9762e84
MKL
7818 verbose_linfo(env, t, "%d: ", t);
7819 verbose_linfo(env, w, "%d: ", w);
61bd5218 7820 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
7821 return -EINVAL;
7822 } else if (insn_state[w] == EXPLORED) {
7823 /* forward- or cross-edge */
7824 insn_state[t] = DISCOVERED | e;
7825 } else {
61bd5218 7826 verbose(env, "insn state internal bug\n");
475fb78f
AS
7827 return -EFAULT;
7828 }
7829 return 0;
7830}
7831
7832/* non-recursive depth-first-search to detect loops in BPF program
7833 * loop == back-edge in directed graph
7834 */
58e2af8b 7835static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
7836{
7837 struct bpf_insn *insns = env->prog->insnsi;
7838 int insn_cnt = env->prog->len;
7df737e9 7839 int *insn_stack, *insn_state;
475fb78f
AS
7840 int ret = 0;
7841 int i, t;
7842
7df737e9 7843 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
7844 if (!insn_state)
7845 return -ENOMEM;
7846
7df737e9 7847 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 7848 if (!insn_stack) {
71dde681 7849 kvfree(insn_state);
475fb78f
AS
7850 return -ENOMEM;
7851 }
7852
7853 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7854 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 7855 env->cfg.cur_stack = 1;
475fb78f
AS
7856
7857peek_stack:
7df737e9 7858 if (env->cfg.cur_stack == 0)
475fb78f 7859 goto check_state;
7df737e9 7860 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 7861
092ed096
JW
7862 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7863 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
7864 u8 opcode = BPF_OP(insns[t].code);
7865
7866 if (opcode == BPF_EXIT) {
7867 goto mark_explored;
7868 } else if (opcode == BPF_CALL) {
2589726d 7869 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
7870 if (ret == 1)
7871 goto peek_stack;
7872 else if (ret < 0)
7873 goto err_free;
07016151 7874 if (t + 1 < insn_cnt)
5d839021 7875 init_explored_state(env, t + 1);
cc8b0b92 7876 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5d839021 7877 init_explored_state(env, t);
2589726d
AS
7878 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7879 env, false);
cc8b0b92
AS
7880 if (ret == 1)
7881 goto peek_stack;
7882 else if (ret < 0)
7883 goto err_free;
7884 }
475fb78f
AS
7885 } else if (opcode == BPF_JA) {
7886 if (BPF_SRC(insns[t].code) != BPF_K) {
7887 ret = -EINVAL;
7888 goto err_free;
7889 }
7890 /* unconditional jump with single edge */
7891 ret = push_insn(t, t + insns[t].off + 1,
2589726d 7892 FALLTHROUGH, env, true);
475fb78f
AS
7893 if (ret == 1)
7894 goto peek_stack;
7895 else if (ret < 0)
7896 goto err_free;
b5dc0163
AS
7897 /* unconditional jmp is not a good pruning point,
7898 * but it's marked, since backtracking needs
7899 * to record jmp history in is_state_visited().
7900 */
7901 init_explored_state(env, t + insns[t].off + 1);
f1bca824
AS
7902 /* tell verifier to check for equivalent states
7903 * after every call and jump
7904 */
c3de6317 7905 if (t + 1 < insn_cnt)
5d839021 7906 init_explored_state(env, t + 1);
475fb78f
AS
7907 } else {
7908 /* conditional jump with two edges */
5d839021 7909 init_explored_state(env, t);
2589726d 7910 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
475fb78f
AS
7911 if (ret == 1)
7912 goto peek_stack;
7913 else if (ret < 0)
7914 goto err_free;
7915
2589726d 7916 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
475fb78f
AS
7917 if (ret == 1)
7918 goto peek_stack;
7919 else if (ret < 0)
7920 goto err_free;
7921 }
7922 } else {
7923 /* all other non-branch instructions with single
7924 * fall-through edge
7925 */
2589726d 7926 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
7927 if (ret == 1)
7928 goto peek_stack;
7929 else if (ret < 0)
7930 goto err_free;
7931 }
7932
7933mark_explored:
7934 insn_state[t] = EXPLORED;
7df737e9 7935 if (env->cfg.cur_stack-- <= 0) {
61bd5218 7936 verbose(env, "pop stack internal bug\n");
475fb78f
AS
7937 ret = -EFAULT;
7938 goto err_free;
7939 }
7940 goto peek_stack;
7941
7942check_state:
7943 for (i = 0; i < insn_cnt; i++) {
7944 if (insn_state[i] != EXPLORED) {
61bd5218 7945 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
7946 ret = -EINVAL;
7947 goto err_free;
7948 }
7949 }
7950 ret = 0; /* cfg looks good */
7951
7952err_free:
71dde681
AS
7953 kvfree(insn_state);
7954 kvfree(insn_stack);
7df737e9 7955 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
7956 return ret;
7957}
7958
09b28d76
AS
7959static int check_abnormal_return(struct bpf_verifier_env *env)
7960{
7961 int i;
7962
7963 for (i = 1; i < env->subprog_cnt; i++) {
7964 if (env->subprog_info[i].has_ld_abs) {
7965 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
7966 return -EINVAL;
7967 }
7968 if (env->subprog_info[i].has_tail_call) {
7969 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
7970 return -EINVAL;
7971 }
7972 }
7973 return 0;
7974}
7975
838e9690
YS
7976/* The minimum supported BTF func info size */
7977#define MIN_BPF_FUNCINFO_SIZE 8
7978#define MAX_FUNCINFO_REC_SIZE 252
7979
c454a46b
MKL
7980static int check_btf_func(struct bpf_verifier_env *env,
7981 const union bpf_attr *attr,
7982 union bpf_attr __user *uattr)
838e9690 7983{
09b28d76 7984 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 7985 u32 i, nfuncs, urec_size, min_size;
838e9690 7986 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 7987 struct bpf_func_info *krecord;
8c1b6e69 7988 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
7989 struct bpf_prog *prog;
7990 const struct btf *btf;
838e9690 7991 void __user *urecord;
d0b2818e 7992 u32 prev_offset = 0;
09b28d76 7993 bool scalar_return;
e7ed83d6 7994 int ret = -ENOMEM;
838e9690
YS
7995
7996 nfuncs = attr->func_info_cnt;
09b28d76
AS
7997 if (!nfuncs) {
7998 if (check_abnormal_return(env))
7999 return -EINVAL;
838e9690 8000 return 0;
09b28d76 8001 }
838e9690
YS
8002
8003 if (nfuncs != env->subprog_cnt) {
8004 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8005 return -EINVAL;
8006 }
8007
8008 urec_size = attr->func_info_rec_size;
8009 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8010 urec_size > MAX_FUNCINFO_REC_SIZE ||
8011 urec_size % sizeof(u32)) {
8012 verbose(env, "invalid func info rec size %u\n", urec_size);
8013 return -EINVAL;
8014 }
8015
c454a46b
MKL
8016 prog = env->prog;
8017 btf = prog->aux->btf;
838e9690
YS
8018
8019 urecord = u64_to_user_ptr(attr->func_info);
8020 min_size = min_t(u32, krec_size, urec_size);
8021
ba64e7d8 8022 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
8023 if (!krecord)
8024 return -ENOMEM;
8c1b6e69
AS
8025 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8026 if (!info_aux)
8027 goto err_free;
ba64e7d8 8028
838e9690
YS
8029 for (i = 0; i < nfuncs; i++) {
8030 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8031 if (ret) {
8032 if (ret == -E2BIG) {
8033 verbose(env, "nonzero tailing record in func info");
8034 /* set the size kernel expects so loader can zero
8035 * out the rest of the record.
8036 */
8037 if (put_user(min_size, &uattr->func_info_rec_size))
8038 ret = -EFAULT;
8039 }
c454a46b 8040 goto err_free;
838e9690
YS
8041 }
8042
ba64e7d8 8043 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 8044 ret = -EFAULT;
c454a46b 8045 goto err_free;
838e9690
YS
8046 }
8047
d30d42e0 8048 /* check insn_off */
09b28d76 8049 ret = -EINVAL;
838e9690 8050 if (i == 0) {
d30d42e0 8051 if (krecord[i].insn_off) {
838e9690 8052 verbose(env,
d30d42e0
MKL
8053 "nonzero insn_off %u for the first func info record",
8054 krecord[i].insn_off);
c454a46b 8055 goto err_free;
838e9690 8056 }
d30d42e0 8057 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
8058 verbose(env,
8059 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 8060 krecord[i].insn_off, prev_offset);
c454a46b 8061 goto err_free;
838e9690
YS
8062 }
8063
d30d42e0 8064 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 8065 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 8066 goto err_free;
838e9690
YS
8067 }
8068
8069 /* check type_id */
ba64e7d8 8070 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 8071 if (!type || !btf_type_is_func(type)) {
838e9690 8072 verbose(env, "invalid type id %d in func info",
ba64e7d8 8073 krecord[i].type_id);
c454a46b 8074 goto err_free;
838e9690 8075 }
51c39bb1 8076 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
8077
8078 func_proto = btf_type_by_id(btf, type->type);
8079 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8080 /* btf_func_check() already verified it during BTF load */
8081 goto err_free;
8082 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8083 scalar_return =
8084 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8085 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8086 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8087 goto err_free;
8088 }
8089 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8090 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8091 goto err_free;
8092 }
8093
d30d42e0 8094 prev_offset = krecord[i].insn_off;
838e9690
YS
8095 urecord += urec_size;
8096 }
8097
ba64e7d8
YS
8098 prog->aux->func_info = krecord;
8099 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 8100 prog->aux->func_info_aux = info_aux;
838e9690
YS
8101 return 0;
8102
c454a46b 8103err_free:
ba64e7d8 8104 kvfree(krecord);
8c1b6e69 8105 kfree(info_aux);
838e9690
YS
8106 return ret;
8107}
8108
ba64e7d8
YS
8109static void adjust_btf_func(struct bpf_verifier_env *env)
8110{
8c1b6e69 8111 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
8112 int i;
8113
8c1b6e69 8114 if (!aux->func_info)
ba64e7d8
YS
8115 return;
8116
8117 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 8118 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
8119}
8120
c454a46b
MKL
8121#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8122 sizeof(((struct bpf_line_info *)(0))->line_col))
8123#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8124
8125static int check_btf_line(struct bpf_verifier_env *env,
8126 const union bpf_attr *attr,
8127 union bpf_attr __user *uattr)
8128{
8129 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8130 struct bpf_subprog_info *sub;
8131 struct bpf_line_info *linfo;
8132 struct bpf_prog *prog;
8133 const struct btf *btf;
8134 void __user *ulinfo;
8135 int err;
8136
8137 nr_linfo = attr->line_info_cnt;
8138 if (!nr_linfo)
8139 return 0;
8140
8141 rec_size = attr->line_info_rec_size;
8142 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8143 rec_size > MAX_LINEINFO_REC_SIZE ||
8144 rec_size & (sizeof(u32) - 1))
8145 return -EINVAL;
8146
8147 /* Need to zero it in case the userspace may
8148 * pass in a smaller bpf_line_info object.
8149 */
8150 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8151 GFP_KERNEL | __GFP_NOWARN);
8152 if (!linfo)
8153 return -ENOMEM;
8154
8155 prog = env->prog;
8156 btf = prog->aux->btf;
8157
8158 s = 0;
8159 sub = env->subprog_info;
8160 ulinfo = u64_to_user_ptr(attr->line_info);
8161 expected_size = sizeof(struct bpf_line_info);
8162 ncopy = min_t(u32, expected_size, rec_size);
8163 for (i = 0; i < nr_linfo; i++) {
8164 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8165 if (err) {
8166 if (err == -E2BIG) {
8167 verbose(env, "nonzero tailing record in line_info");
8168 if (put_user(expected_size,
8169 &uattr->line_info_rec_size))
8170 err = -EFAULT;
8171 }
8172 goto err_free;
8173 }
8174
8175 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8176 err = -EFAULT;
8177 goto err_free;
8178 }
8179
8180 /*
8181 * Check insn_off to ensure
8182 * 1) strictly increasing AND
8183 * 2) bounded by prog->len
8184 *
8185 * The linfo[0].insn_off == 0 check logically falls into
8186 * the later "missing bpf_line_info for func..." case
8187 * because the first linfo[0].insn_off must be the
8188 * first sub also and the first sub must have
8189 * subprog_info[0].start == 0.
8190 */
8191 if ((i && linfo[i].insn_off <= prev_offset) ||
8192 linfo[i].insn_off >= prog->len) {
8193 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8194 i, linfo[i].insn_off, prev_offset,
8195 prog->len);
8196 err = -EINVAL;
8197 goto err_free;
8198 }
8199
fdbaa0be
MKL
8200 if (!prog->insnsi[linfo[i].insn_off].code) {
8201 verbose(env,
8202 "Invalid insn code at line_info[%u].insn_off\n",
8203 i);
8204 err = -EINVAL;
8205 goto err_free;
8206 }
8207
23127b33
MKL
8208 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8209 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
8210 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8211 err = -EINVAL;
8212 goto err_free;
8213 }
8214
8215 if (s != env->subprog_cnt) {
8216 if (linfo[i].insn_off == sub[s].start) {
8217 sub[s].linfo_idx = i;
8218 s++;
8219 } else if (sub[s].start < linfo[i].insn_off) {
8220 verbose(env, "missing bpf_line_info for func#%u\n", s);
8221 err = -EINVAL;
8222 goto err_free;
8223 }
8224 }
8225
8226 prev_offset = linfo[i].insn_off;
8227 ulinfo += rec_size;
8228 }
8229
8230 if (s != env->subprog_cnt) {
8231 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8232 env->subprog_cnt - s, s);
8233 err = -EINVAL;
8234 goto err_free;
8235 }
8236
8237 prog->aux->linfo = linfo;
8238 prog->aux->nr_linfo = nr_linfo;
8239
8240 return 0;
8241
8242err_free:
8243 kvfree(linfo);
8244 return err;
8245}
8246
8247static int check_btf_info(struct bpf_verifier_env *env,
8248 const union bpf_attr *attr,
8249 union bpf_attr __user *uattr)
8250{
8251 struct btf *btf;
8252 int err;
8253
09b28d76
AS
8254 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8255 if (check_abnormal_return(env))
8256 return -EINVAL;
c454a46b 8257 return 0;
09b28d76 8258 }
c454a46b
MKL
8259
8260 btf = btf_get_by_fd(attr->prog_btf_fd);
8261 if (IS_ERR(btf))
8262 return PTR_ERR(btf);
8263 env->prog->aux->btf = btf;
8264
8265 err = check_btf_func(env, attr, uattr);
8266 if (err)
8267 return err;
8268
8269 err = check_btf_line(env, attr, uattr);
8270 if (err)
8271 return err;
8272
8273 return 0;
ba64e7d8
YS
8274}
8275
f1174f77
EC
8276/* check %cur's range satisfies %old's */
8277static bool range_within(struct bpf_reg_state *old,
8278 struct bpf_reg_state *cur)
8279{
b03c9f9f
EC
8280 return old->umin_value <= cur->umin_value &&
8281 old->umax_value >= cur->umax_value &&
8282 old->smin_value <= cur->smin_value &&
8283 old->smax_value >= cur->smax_value;
f1174f77
EC
8284}
8285
8286/* Maximum number of register states that can exist at once */
8287#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8288struct idpair {
8289 u32 old;
8290 u32 cur;
8291};
8292
8293/* If in the old state two registers had the same id, then they need to have
8294 * the same id in the new state as well. But that id could be different from
8295 * the old state, so we need to track the mapping from old to new ids.
8296 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8297 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8298 * regs with a different old id could still have new id 9, we don't care about
8299 * that.
8300 * So we look through our idmap to see if this old id has been seen before. If
8301 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 8302 */
f1174f77 8303static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 8304{
f1174f77 8305 unsigned int i;
969bf05e 8306
f1174f77
EC
8307 for (i = 0; i < ID_MAP_SIZE; i++) {
8308 if (!idmap[i].old) {
8309 /* Reached an empty slot; haven't seen this id before */
8310 idmap[i].old = old_id;
8311 idmap[i].cur = cur_id;
8312 return true;
8313 }
8314 if (idmap[i].old == old_id)
8315 return idmap[i].cur == cur_id;
8316 }
8317 /* We ran out of idmap slots, which should be impossible */
8318 WARN_ON_ONCE(1);
8319 return false;
8320}
8321
9242b5f5
AS
8322static void clean_func_state(struct bpf_verifier_env *env,
8323 struct bpf_func_state *st)
8324{
8325 enum bpf_reg_liveness live;
8326 int i, j;
8327
8328 for (i = 0; i < BPF_REG_FP; i++) {
8329 live = st->regs[i].live;
8330 /* liveness must not touch this register anymore */
8331 st->regs[i].live |= REG_LIVE_DONE;
8332 if (!(live & REG_LIVE_READ))
8333 /* since the register is unused, clear its state
8334 * to make further comparison simpler
8335 */
f54c7898 8336 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
8337 }
8338
8339 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8340 live = st->stack[i].spilled_ptr.live;
8341 /* liveness must not touch this stack slot anymore */
8342 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8343 if (!(live & REG_LIVE_READ)) {
f54c7898 8344 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
8345 for (j = 0; j < BPF_REG_SIZE; j++)
8346 st->stack[i].slot_type[j] = STACK_INVALID;
8347 }
8348 }
8349}
8350
8351static void clean_verifier_state(struct bpf_verifier_env *env,
8352 struct bpf_verifier_state *st)
8353{
8354 int i;
8355
8356 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8357 /* all regs in this state in all frames were already marked */
8358 return;
8359
8360 for (i = 0; i <= st->curframe; i++)
8361 clean_func_state(env, st->frame[i]);
8362}
8363
8364/* the parentage chains form a tree.
8365 * the verifier states are added to state lists at given insn and
8366 * pushed into state stack for future exploration.
8367 * when the verifier reaches bpf_exit insn some of the verifer states
8368 * stored in the state lists have their final liveness state already,
8369 * but a lot of states will get revised from liveness point of view when
8370 * the verifier explores other branches.
8371 * Example:
8372 * 1: r0 = 1
8373 * 2: if r1 == 100 goto pc+1
8374 * 3: r0 = 2
8375 * 4: exit
8376 * when the verifier reaches exit insn the register r0 in the state list of
8377 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8378 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8379 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8380 *
8381 * Since the verifier pushes the branch states as it sees them while exploring
8382 * the program the condition of walking the branch instruction for the second
8383 * time means that all states below this branch were already explored and
8384 * their final liveness markes are already propagated.
8385 * Hence when the verifier completes the search of state list in is_state_visited()
8386 * we can call this clean_live_states() function to mark all liveness states
8387 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8388 * will not be used.
8389 * This function also clears the registers and stack for states that !READ
8390 * to simplify state merging.
8391 *
8392 * Important note here that walking the same branch instruction in the callee
8393 * doesn't meant that the states are DONE. The verifier has to compare
8394 * the callsites
8395 */
8396static void clean_live_states(struct bpf_verifier_env *env, int insn,
8397 struct bpf_verifier_state *cur)
8398{
8399 struct bpf_verifier_state_list *sl;
8400 int i;
8401
5d839021 8402 sl = *explored_state(env, insn);
a8f500af 8403 while (sl) {
2589726d
AS
8404 if (sl->state.branches)
8405 goto next;
dc2a4ebc
AS
8406 if (sl->state.insn_idx != insn ||
8407 sl->state.curframe != cur->curframe)
9242b5f5
AS
8408 goto next;
8409 for (i = 0; i <= cur->curframe; i++)
8410 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8411 goto next;
8412 clean_verifier_state(env, &sl->state);
8413next:
8414 sl = sl->next;
8415 }
8416}
8417
f1174f77 8418/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
8419static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8420 struct idpair *idmap)
f1174f77 8421{
f4d7e40a
AS
8422 bool equal;
8423
dc503a8a
EC
8424 if (!(rold->live & REG_LIVE_READ))
8425 /* explored state didn't use this */
8426 return true;
8427
679c782d 8428 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
8429
8430 if (rold->type == PTR_TO_STACK)
8431 /* two stack pointers are equal only if they're pointing to
8432 * the same stack frame, since fp-8 in foo != fp-8 in bar
8433 */
8434 return equal && rold->frameno == rcur->frameno;
8435
8436 if (equal)
969bf05e
AS
8437 return true;
8438
f1174f77
EC
8439 if (rold->type == NOT_INIT)
8440 /* explored state can't have used this */
969bf05e 8441 return true;
f1174f77
EC
8442 if (rcur->type == NOT_INIT)
8443 return false;
8444 switch (rold->type) {
8445 case SCALAR_VALUE:
8446 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
8447 if (!rold->precise && !rcur->precise)
8448 return true;
f1174f77
EC
8449 /* new val must satisfy old val knowledge */
8450 return range_within(rold, rcur) &&
8451 tnum_in(rold->var_off, rcur->var_off);
8452 } else {
179d1c56
JH
8453 /* We're trying to use a pointer in place of a scalar.
8454 * Even if the scalar was unbounded, this could lead to
8455 * pointer leaks because scalars are allowed to leak
8456 * while pointers are not. We could make this safe in
8457 * special cases if root is calling us, but it's
8458 * probably not worth the hassle.
f1174f77 8459 */
179d1c56 8460 return false;
f1174f77
EC
8461 }
8462 case PTR_TO_MAP_VALUE:
1b688a19
EC
8463 /* If the new min/max/var_off satisfy the old ones and
8464 * everything else matches, we are OK.
d83525ca
AS
8465 * 'id' is not compared, since it's only used for maps with
8466 * bpf_spin_lock inside map element and in such cases if
8467 * the rest of the prog is valid for one map element then
8468 * it's valid for all map elements regardless of the key
8469 * used in bpf_map_lookup()
1b688a19
EC
8470 */
8471 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8472 range_within(rold, rcur) &&
8473 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
8474 case PTR_TO_MAP_VALUE_OR_NULL:
8475 /* a PTR_TO_MAP_VALUE could be safe to use as a
8476 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8477 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8478 * checked, doing so could have affected others with the same
8479 * id, and we can't check for that because we lost the id when
8480 * we converted to a PTR_TO_MAP_VALUE.
8481 */
8482 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8483 return false;
8484 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8485 return false;
8486 /* Check our ids match any regs they're supposed to */
8487 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 8488 case PTR_TO_PACKET_META:
f1174f77 8489 case PTR_TO_PACKET:
de8f3a83 8490 if (rcur->type != rold->type)
f1174f77
EC
8491 return false;
8492 /* We must have at least as much range as the old ptr
8493 * did, so that any accesses which were safe before are
8494 * still safe. This is true even if old range < old off,
8495 * since someone could have accessed through (ptr - k), or
8496 * even done ptr -= k in a register, to get a safe access.
8497 */
8498 if (rold->range > rcur->range)
8499 return false;
8500 /* If the offsets don't match, we can't trust our alignment;
8501 * nor can we be sure that we won't fall out of range.
8502 */
8503 if (rold->off != rcur->off)
8504 return false;
8505 /* id relations must be preserved */
8506 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8507 return false;
8508 /* new val must satisfy old val knowledge */
8509 return range_within(rold, rcur) &&
8510 tnum_in(rold->var_off, rcur->var_off);
8511 case PTR_TO_CTX:
8512 case CONST_PTR_TO_MAP:
f1174f77 8513 case PTR_TO_PACKET_END:
d58e468b 8514 case PTR_TO_FLOW_KEYS:
c64b7983
JS
8515 case PTR_TO_SOCKET:
8516 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
8517 case PTR_TO_SOCK_COMMON:
8518 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
8519 case PTR_TO_TCP_SOCK:
8520 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 8521 case PTR_TO_XDP_SOCK:
f1174f77
EC
8522 /* Only valid matches are exact, which memcmp() above
8523 * would have accepted
8524 */
8525 default:
8526 /* Don't know what's going on, just say it's not safe */
8527 return false;
8528 }
969bf05e 8529
f1174f77
EC
8530 /* Shouldn't get here; if we do, say it's not safe */
8531 WARN_ON_ONCE(1);
969bf05e
AS
8532 return false;
8533}
8534
f4d7e40a
AS
8535static bool stacksafe(struct bpf_func_state *old,
8536 struct bpf_func_state *cur,
638f5b90
AS
8537 struct idpair *idmap)
8538{
8539 int i, spi;
8540
638f5b90
AS
8541 /* walk slots of the explored stack and ignore any additional
8542 * slots in the current stack, since explored(safe) state
8543 * didn't use them
8544 */
8545 for (i = 0; i < old->allocated_stack; i++) {
8546 spi = i / BPF_REG_SIZE;
8547
b233920c
AS
8548 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8549 i += BPF_REG_SIZE - 1;
cc2b14d5 8550 /* explored state didn't use this */
fd05e57b 8551 continue;
b233920c 8552 }
cc2b14d5 8553
638f5b90
AS
8554 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8555 continue;
19e2dbb7
AS
8556
8557 /* explored stack has more populated slots than current stack
8558 * and these slots were used
8559 */
8560 if (i >= cur->allocated_stack)
8561 return false;
8562
cc2b14d5
AS
8563 /* if old state was safe with misc data in the stack
8564 * it will be safe with zero-initialized stack.
8565 * The opposite is not true
8566 */
8567 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8568 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8569 continue;
638f5b90
AS
8570 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8571 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8572 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 8573 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
8574 * this verifier states are not equivalent,
8575 * return false to continue verification of this path
8576 */
8577 return false;
8578 if (i % BPF_REG_SIZE)
8579 continue;
8580 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8581 continue;
8582 if (!regsafe(&old->stack[spi].spilled_ptr,
8583 &cur->stack[spi].spilled_ptr,
8584 idmap))
8585 /* when explored and current stack slot are both storing
8586 * spilled registers, check that stored pointers types
8587 * are the same as well.
8588 * Ex: explored safe path could have stored
8589 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8590 * but current path has stored:
8591 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8592 * such verifier states are not equivalent.
8593 * return false to continue verification of this path
8594 */
8595 return false;
8596 }
8597 return true;
8598}
8599
fd978bf7
JS
8600static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8601{
8602 if (old->acquired_refs != cur->acquired_refs)
8603 return false;
8604 return !memcmp(old->refs, cur->refs,
8605 sizeof(*old->refs) * old->acquired_refs);
8606}
8607
f1bca824
AS
8608/* compare two verifier states
8609 *
8610 * all states stored in state_list are known to be valid, since
8611 * verifier reached 'bpf_exit' instruction through them
8612 *
8613 * this function is called when verifier exploring different branches of
8614 * execution popped from the state stack. If it sees an old state that has
8615 * more strict register state and more strict stack state then this execution
8616 * branch doesn't need to be explored further, since verifier already
8617 * concluded that more strict state leads to valid finish.
8618 *
8619 * Therefore two states are equivalent if register state is more conservative
8620 * and explored stack state is more conservative than the current one.
8621 * Example:
8622 * explored current
8623 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8624 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8625 *
8626 * In other words if current stack state (one being explored) has more
8627 * valid slots than old one that already passed validation, it means
8628 * the verifier can stop exploring and conclude that current state is valid too
8629 *
8630 * Similarly with registers. If explored state has register type as invalid
8631 * whereas register type in current state is meaningful, it means that
8632 * the current state will reach 'bpf_exit' instruction safely
8633 */
f4d7e40a
AS
8634static bool func_states_equal(struct bpf_func_state *old,
8635 struct bpf_func_state *cur)
f1bca824 8636{
f1174f77
EC
8637 struct idpair *idmap;
8638 bool ret = false;
f1bca824
AS
8639 int i;
8640
f1174f77
EC
8641 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8642 /* If we failed to allocate the idmap, just say it's not safe */
8643 if (!idmap)
1a0dc1ac 8644 return false;
f1174f77
EC
8645
8646 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 8647 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 8648 goto out_free;
f1bca824
AS
8649 }
8650
638f5b90
AS
8651 if (!stacksafe(old, cur, idmap))
8652 goto out_free;
fd978bf7
JS
8653
8654 if (!refsafe(old, cur))
8655 goto out_free;
f1174f77
EC
8656 ret = true;
8657out_free:
8658 kfree(idmap);
8659 return ret;
f1bca824
AS
8660}
8661
f4d7e40a
AS
8662static bool states_equal(struct bpf_verifier_env *env,
8663 struct bpf_verifier_state *old,
8664 struct bpf_verifier_state *cur)
8665{
8666 int i;
8667
8668 if (old->curframe != cur->curframe)
8669 return false;
8670
979d63d5
DB
8671 /* Verification state from speculative execution simulation
8672 * must never prune a non-speculative execution one.
8673 */
8674 if (old->speculative && !cur->speculative)
8675 return false;
8676
d83525ca
AS
8677 if (old->active_spin_lock != cur->active_spin_lock)
8678 return false;
8679
f4d7e40a
AS
8680 /* for states to be equal callsites have to be the same
8681 * and all frame states need to be equivalent
8682 */
8683 for (i = 0; i <= old->curframe; i++) {
8684 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8685 return false;
8686 if (!func_states_equal(old->frame[i], cur->frame[i]))
8687 return false;
8688 }
8689 return true;
8690}
8691
5327ed3d
JW
8692/* Return 0 if no propagation happened. Return negative error code if error
8693 * happened. Otherwise, return the propagated bit.
8694 */
55e7f3b5
JW
8695static int propagate_liveness_reg(struct bpf_verifier_env *env,
8696 struct bpf_reg_state *reg,
8697 struct bpf_reg_state *parent_reg)
8698{
5327ed3d
JW
8699 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8700 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
8701 int err;
8702
5327ed3d
JW
8703 /* When comes here, read flags of PARENT_REG or REG could be any of
8704 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8705 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8706 */
8707 if (parent_flag == REG_LIVE_READ64 ||
8708 /* Or if there is no read flag from REG. */
8709 !flag ||
8710 /* Or if the read flag from REG is the same as PARENT_REG. */
8711 parent_flag == flag)
55e7f3b5
JW
8712 return 0;
8713
5327ed3d 8714 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
8715 if (err)
8716 return err;
8717
5327ed3d 8718 return flag;
55e7f3b5
JW
8719}
8720
8e9cd9ce 8721/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
8722 * straight-line code between a state and its parent. When we arrive at an
8723 * equivalent state (jump target or such) we didn't arrive by the straight-line
8724 * code, so read marks in the state must propagate to the parent regardless
8725 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 8726 * in mark_reg_read() is for.
8e9cd9ce 8727 */
f4d7e40a
AS
8728static int propagate_liveness(struct bpf_verifier_env *env,
8729 const struct bpf_verifier_state *vstate,
8730 struct bpf_verifier_state *vparent)
dc503a8a 8731{
3f8cafa4 8732 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 8733 struct bpf_func_state *state, *parent;
3f8cafa4 8734 int i, frame, err = 0;
dc503a8a 8735
f4d7e40a
AS
8736 if (vparent->curframe != vstate->curframe) {
8737 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8738 vparent->curframe, vstate->curframe);
8739 return -EFAULT;
8740 }
dc503a8a
EC
8741 /* Propagate read liveness of registers... */
8742 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 8743 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
8744 parent = vparent->frame[frame];
8745 state = vstate->frame[frame];
8746 parent_reg = parent->regs;
8747 state_reg = state->regs;
83d16312
JK
8748 /* We don't need to worry about FP liveness, it's read-only */
8749 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
8750 err = propagate_liveness_reg(env, &state_reg[i],
8751 &parent_reg[i]);
5327ed3d 8752 if (err < 0)
3f8cafa4 8753 return err;
5327ed3d
JW
8754 if (err == REG_LIVE_READ64)
8755 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 8756 }
f4d7e40a 8757
1b04aee7 8758 /* Propagate stack slots. */
f4d7e40a
AS
8759 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8760 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
8761 parent_reg = &parent->stack[i].spilled_ptr;
8762 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
8763 err = propagate_liveness_reg(env, state_reg,
8764 parent_reg);
5327ed3d 8765 if (err < 0)
3f8cafa4 8766 return err;
dc503a8a
EC
8767 }
8768 }
5327ed3d 8769 return 0;
dc503a8a
EC
8770}
8771
a3ce685d
AS
8772/* find precise scalars in the previous equivalent state and
8773 * propagate them into the current state
8774 */
8775static int propagate_precision(struct bpf_verifier_env *env,
8776 const struct bpf_verifier_state *old)
8777{
8778 struct bpf_reg_state *state_reg;
8779 struct bpf_func_state *state;
8780 int i, err = 0;
8781
8782 state = old->frame[old->curframe];
8783 state_reg = state->regs;
8784 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8785 if (state_reg->type != SCALAR_VALUE ||
8786 !state_reg->precise)
8787 continue;
8788 if (env->log.level & BPF_LOG_LEVEL2)
8789 verbose(env, "propagating r%d\n", i);
8790 err = mark_chain_precision(env, i);
8791 if (err < 0)
8792 return err;
8793 }
8794
8795 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8796 if (state->stack[i].slot_type[0] != STACK_SPILL)
8797 continue;
8798 state_reg = &state->stack[i].spilled_ptr;
8799 if (state_reg->type != SCALAR_VALUE ||
8800 !state_reg->precise)
8801 continue;
8802 if (env->log.level & BPF_LOG_LEVEL2)
8803 verbose(env, "propagating fp%d\n",
8804 (-i - 1) * BPF_REG_SIZE);
8805 err = mark_chain_precision_stack(env, i);
8806 if (err < 0)
8807 return err;
8808 }
8809 return 0;
8810}
8811
2589726d
AS
8812static bool states_maybe_looping(struct bpf_verifier_state *old,
8813 struct bpf_verifier_state *cur)
8814{
8815 struct bpf_func_state *fold, *fcur;
8816 int i, fr = cur->curframe;
8817
8818 if (old->curframe != fr)
8819 return false;
8820
8821 fold = old->frame[fr];
8822 fcur = cur->frame[fr];
8823 for (i = 0; i < MAX_BPF_REG; i++)
8824 if (memcmp(&fold->regs[i], &fcur->regs[i],
8825 offsetof(struct bpf_reg_state, parent)))
8826 return false;
8827 return true;
8828}
8829
8830
58e2af8b 8831static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 8832{
58e2af8b 8833 struct bpf_verifier_state_list *new_sl;
9f4686c4 8834 struct bpf_verifier_state_list *sl, **pprev;
679c782d 8835 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 8836 int i, j, err, states_cnt = 0;
10d274e8 8837 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 8838
b5dc0163 8839 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 8840 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
8841 /* this 'insn_idx' instruction wasn't marked, so we will not
8842 * be doing state search here
8843 */
8844 return 0;
8845
2589726d
AS
8846 /* bpf progs typically have pruning point every 4 instructions
8847 * http://vger.kernel.org/bpfconf2019.html#session-1
8848 * Do not add new state for future pruning if the verifier hasn't seen
8849 * at least 2 jumps and at least 8 instructions.
8850 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8851 * In tests that amounts to up to 50% reduction into total verifier
8852 * memory consumption and 20% verifier time speedup.
8853 */
8854 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8855 env->insn_processed - env->prev_insn_processed >= 8)
8856 add_new_state = true;
8857
a8f500af
AS
8858 pprev = explored_state(env, insn_idx);
8859 sl = *pprev;
8860
9242b5f5
AS
8861 clean_live_states(env, insn_idx, cur);
8862
a8f500af 8863 while (sl) {
dc2a4ebc
AS
8864 states_cnt++;
8865 if (sl->state.insn_idx != insn_idx)
8866 goto next;
2589726d
AS
8867 if (sl->state.branches) {
8868 if (states_maybe_looping(&sl->state, cur) &&
8869 states_equal(env, &sl->state, cur)) {
8870 verbose_linfo(env, insn_idx, "; ");
8871 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8872 return -EINVAL;
8873 }
8874 /* if the verifier is processing a loop, avoid adding new state
8875 * too often, since different loop iterations have distinct
8876 * states and may not help future pruning.
8877 * This threshold shouldn't be too low to make sure that
8878 * a loop with large bound will be rejected quickly.
8879 * The most abusive loop will be:
8880 * r1 += 1
8881 * if r1 < 1000000 goto pc-2
8882 * 1M insn_procssed limit / 100 == 10k peak states.
8883 * This threshold shouldn't be too high either, since states
8884 * at the end of the loop are likely to be useful in pruning.
8885 */
8886 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8887 env->insn_processed - env->prev_insn_processed < 100)
8888 add_new_state = false;
8889 goto miss;
8890 }
638f5b90 8891 if (states_equal(env, &sl->state, cur)) {
9f4686c4 8892 sl->hit_cnt++;
f1bca824 8893 /* reached equivalent register/stack state,
dc503a8a
EC
8894 * prune the search.
8895 * Registers read by the continuation are read by us.
8e9cd9ce
EC
8896 * If we have any write marks in env->cur_state, they
8897 * will prevent corresponding reads in the continuation
8898 * from reaching our parent (an explored_state). Our
8899 * own state will get the read marks recorded, but
8900 * they'll be immediately forgotten as we're pruning
8901 * this state and will pop a new one.
f1bca824 8902 */
f4d7e40a 8903 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
8904
8905 /* if previous state reached the exit with precision and
8906 * current state is equivalent to it (except precsion marks)
8907 * the precision needs to be propagated back in
8908 * the current state.
8909 */
8910 err = err ? : push_jmp_history(env, cur);
8911 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
8912 if (err)
8913 return err;
f1bca824 8914 return 1;
dc503a8a 8915 }
2589726d
AS
8916miss:
8917 /* when new state is not going to be added do not increase miss count.
8918 * Otherwise several loop iterations will remove the state
8919 * recorded earlier. The goal of these heuristics is to have
8920 * states from some iterations of the loop (some in the beginning
8921 * and some at the end) to help pruning.
8922 */
8923 if (add_new_state)
8924 sl->miss_cnt++;
9f4686c4
AS
8925 /* heuristic to determine whether this state is beneficial
8926 * to keep checking from state equivalence point of view.
8927 * Higher numbers increase max_states_per_insn and verification time,
8928 * but do not meaningfully decrease insn_processed.
8929 */
8930 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8931 /* the state is unlikely to be useful. Remove it to
8932 * speed up verification
8933 */
8934 *pprev = sl->next;
8935 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
8936 u32 br = sl->state.branches;
8937
8938 WARN_ONCE(br,
8939 "BUG live_done but branches_to_explore %d\n",
8940 br);
9f4686c4
AS
8941 free_verifier_state(&sl->state, false);
8942 kfree(sl);
8943 env->peak_states--;
8944 } else {
8945 /* cannot free this state, since parentage chain may
8946 * walk it later. Add it for free_list instead to
8947 * be freed at the end of verification
8948 */
8949 sl->next = env->free_list;
8950 env->free_list = sl;
8951 }
8952 sl = *pprev;
8953 continue;
8954 }
dc2a4ebc 8955next:
9f4686c4
AS
8956 pprev = &sl->next;
8957 sl = *pprev;
f1bca824
AS
8958 }
8959
06ee7115
AS
8960 if (env->max_states_per_insn < states_cnt)
8961 env->max_states_per_insn = states_cnt;
8962
2c78ee89 8963 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 8964 return push_jmp_history(env, cur);
ceefbc96 8965
2589726d 8966 if (!add_new_state)
b5dc0163 8967 return push_jmp_history(env, cur);
ceefbc96 8968
2589726d
AS
8969 /* There were no equivalent states, remember the current one.
8970 * Technically the current state is not proven to be safe yet,
f4d7e40a 8971 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 8972 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 8973 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
8974 * again on the way to bpf_exit.
8975 * When looping the sl->state.branches will be > 0 and this state
8976 * will not be considered for equivalence until branches == 0.
f1bca824 8977 */
638f5b90 8978 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
8979 if (!new_sl)
8980 return -ENOMEM;
06ee7115
AS
8981 env->total_states++;
8982 env->peak_states++;
2589726d
AS
8983 env->prev_jmps_processed = env->jmps_processed;
8984 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
8985
8986 /* add new state to the head of linked list */
679c782d
EC
8987 new = &new_sl->state;
8988 err = copy_verifier_state(new, cur);
1969db47 8989 if (err) {
679c782d 8990 free_verifier_state(new, false);
1969db47
AS
8991 kfree(new_sl);
8992 return err;
8993 }
dc2a4ebc 8994 new->insn_idx = insn_idx;
2589726d
AS
8995 WARN_ONCE(new->branches != 1,
8996 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 8997
2589726d 8998 cur->parent = new;
b5dc0163
AS
8999 cur->first_insn_idx = insn_idx;
9000 clear_jmp_history(cur);
5d839021
AS
9001 new_sl->next = *explored_state(env, insn_idx);
9002 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
9003 /* connect new state to parentage chain. Current frame needs all
9004 * registers connected. Only r6 - r9 of the callers are alive (pushed
9005 * to the stack implicitly by JITs) so in callers' frames connect just
9006 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9007 * the state of the call instruction (with WRITTEN set), and r0 comes
9008 * from callee with its full parentage chain, anyway.
9009 */
8e9cd9ce
EC
9010 /* clear write marks in current state: the writes we did are not writes
9011 * our child did, so they don't screen off its reads from us.
9012 * (There are no read marks in current state, because reads always mark
9013 * their parent and current state never has children yet. Only
9014 * explored_states can get read marks.)
9015 */
eea1c227
AS
9016 for (j = 0; j <= cur->curframe; j++) {
9017 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9018 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9019 for (i = 0; i < BPF_REG_FP; i++)
9020 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9021 }
f4d7e40a
AS
9022
9023 /* all stack frames are accessible from callee, clear them all */
9024 for (j = 0; j <= cur->curframe; j++) {
9025 struct bpf_func_state *frame = cur->frame[j];
679c782d 9026 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 9027
679c782d 9028 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 9029 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
9030 frame->stack[i].spilled_ptr.parent =
9031 &newframe->stack[i].spilled_ptr;
9032 }
f4d7e40a 9033 }
f1bca824
AS
9034 return 0;
9035}
9036
c64b7983
JS
9037/* Return true if it's OK to have the same insn return a different type. */
9038static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9039{
9040 switch (type) {
9041 case PTR_TO_CTX:
9042 case PTR_TO_SOCKET:
9043 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
9044 case PTR_TO_SOCK_COMMON:
9045 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
9046 case PTR_TO_TCP_SOCK:
9047 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 9048 case PTR_TO_XDP_SOCK:
2a02759e 9049 case PTR_TO_BTF_ID:
b121b341 9050 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
9051 return false;
9052 default:
9053 return true;
9054 }
9055}
9056
9057/* If an instruction was previously used with particular pointer types, then we
9058 * need to be careful to avoid cases such as the below, where it may be ok
9059 * for one branch accessing the pointer, but not ok for the other branch:
9060 *
9061 * R1 = sock_ptr
9062 * goto X;
9063 * ...
9064 * R1 = some_other_valid_ptr;
9065 * goto X;
9066 * ...
9067 * R2 = *(u32 *)(R1 + 0);
9068 */
9069static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9070{
9071 return src != prev && (!reg_type_mismatch_ok(src) ||
9072 !reg_type_mismatch_ok(prev));
9073}
9074
58e2af8b 9075static int do_check(struct bpf_verifier_env *env)
17a52670 9076{
6f8a57cc 9077 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 9078 struct bpf_verifier_state *state = env->cur_state;
17a52670 9079 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 9080 struct bpf_reg_state *regs;
06ee7115 9081 int insn_cnt = env->prog->len;
17a52670 9082 bool do_print_state = false;
b5dc0163 9083 int prev_insn_idx = -1;
17a52670 9084
17a52670
AS
9085 for (;;) {
9086 struct bpf_insn *insn;
9087 u8 class;
9088 int err;
9089
b5dc0163 9090 env->prev_insn_idx = prev_insn_idx;
c08435ec 9091 if (env->insn_idx >= insn_cnt) {
61bd5218 9092 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 9093 env->insn_idx, insn_cnt);
17a52670
AS
9094 return -EFAULT;
9095 }
9096
c08435ec 9097 insn = &insns[env->insn_idx];
17a52670
AS
9098 class = BPF_CLASS(insn->code);
9099
06ee7115 9100 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
9101 verbose(env,
9102 "BPF program is too large. Processed %d insn\n",
06ee7115 9103 env->insn_processed);
17a52670
AS
9104 return -E2BIG;
9105 }
9106
c08435ec 9107 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
9108 if (err < 0)
9109 return err;
9110 if (err == 1) {
9111 /* found equivalent state, can prune the search */
06ee7115 9112 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 9113 if (do_print_state)
979d63d5
DB
9114 verbose(env, "\nfrom %d to %d%s: safe\n",
9115 env->prev_insn_idx, env->insn_idx,
9116 env->cur_state->speculative ?
9117 " (speculative execution)" : "");
f1bca824 9118 else
c08435ec 9119 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
9120 }
9121 goto process_bpf_exit;
9122 }
9123
c3494801
AS
9124 if (signal_pending(current))
9125 return -EAGAIN;
9126
3c2ce60b
DB
9127 if (need_resched())
9128 cond_resched();
9129
06ee7115
AS
9130 if (env->log.level & BPF_LOG_LEVEL2 ||
9131 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9132 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 9133 verbose(env, "%d:", env->insn_idx);
c5fc9692 9134 else
979d63d5
DB
9135 verbose(env, "\nfrom %d to %d%s:",
9136 env->prev_insn_idx, env->insn_idx,
9137 env->cur_state->speculative ?
9138 " (speculative execution)" : "");
f4d7e40a 9139 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
9140 do_print_state = false;
9141 }
9142
06ee7115 9143 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
9144 const struct bpf_insn_cbs cbs = {
9145 .cb_print = verbose,
abe08840 9146 .private_data = env,
7105e828
DB
9147 };
9148
c08435ec
DB
9149 verbose_linfo(env, env->insn_idx, "; ");
9150 verbose(env, "%d: ", env->insn_idx);
abe08840 9151 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
9152 }
9153
cae1927c 9154 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
9155 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9156 env->prev_insn_idx);
cae1927c
JK
9157 if (err)
9158 return err;
9159 }
13a27dfc 9160
638f5b90 9161 regs = cur_regs(env);
51c39bb1 9162 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 9163 prev_insn_idx = env->insn_idx;
fd978bf7 9164
17a52670 9165 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 9166 err = check_alu_op(env, insn);
17a52670
AS
9167 if (err)
9168 return err;
9169
9170 } else if (class == BPF_LDX) {
3df126f3 9171 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
9172
9173 /* check for reserved fields is already done */
9174
17a52670 9175 /* check src operand */
dc503a8a 9176 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9177 if (err)
9178 return err;
9179
dc503a8a 9180 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
9181 if (err)
9182 return err;
9183
725f9dcd
AS
9184 src_reg_type = regs[insn->src_reg].type;
9185
17a52670
AS
9186 /* check that memory (src_reg + off) is readable,
9187 * the state of dst_reg will be updated by this func
9188 */
c08435ec
DB
9189 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9190 insn->off, BPF_SIZE(insn->code),
9191 BPF_READ, insn->dst_reg, false);
17a52670
AS
9192 if (err)
9193 return err;
9194
c08435ec 9195 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9196
9197 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
9198 /* saw a valid insn
9199 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 9200 * save type to validate intersecting paths
9bac3d6d 9201 */
3df126f3 9202 *prev_src_type = src_reg_type;
9bac3d6d 9203
c64b7983 9204 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
9205 /* ABuser program is trying to use the same insn
9206 * dst_reg = *(u32*) (src_reg + off)
9207 * with different pointer types:
9208 * src_reg == ctx in one branch and
9209 * src_reg == stack|map in some other branch.
9210 * Reject it.
9211 */
61bd5218 9212 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
9213 return -EINVAL;
9214 }
9215
17a52670 9216 } else if (class == BPF_STX) {
3df126f3 9217 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 9218
17a52670 9219 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 9220 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
9221 if (err)
9222 return err;
c08435ec 9223 env->insn_idx++;
17a52670
AS
9224 continue;
9225 }
9226
17a52670 9227 /* check src1 operand */
dc503a8a 9228 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9229 if (err)
9230 return err;
9231 /* check src2 operand */
dc503a8a 9232 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9233 if (err)
9234 return err;
9235
d691f9e8
AS
9236 dst_reg_type = regs[insn->dst_reg].type;
9237
17a52670 9238 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9239 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9240 insn->off, BPF_SIZE(insn->code),
9241 BPF_WRITE, insn->src_reg, false);
17a52670
AS
9242 if (err)
9243 return err;
9244
c08435ec 9245 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9246
9247 if (*prev_dst_type == NOT_INIT) {
9248 *prev_dst_type = dst_reg_type;
c64b7983 9249 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 9250 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
9251 return -EINVAL;
9252 }
9253
17a52670
AS
9254 } else if (class == BPF_ST) {
9255 if (BPF_MODE(insn->code) != BPF_MEM ||
9256 insn->src_reg != BPF_REG_0) {
61bd5218 9257 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
9258 return -EINVAL;
9259 }
9260 /* check src operand */
dc503a8a 9261 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9262 if (err)
9263 return err;
9264
f37a8cb8 9265 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 9266 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
9267 insn->dst_reg,
9268 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
9269 return -EACCES;
9270 }
9271
17a52670 9272 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9273 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9274 insn->off, BPF_SIZE(insn->code),
9275 BPF_WRITE, -1, false);
17a52670
AS
9276 if (err)
9277 return err;
9278
092ed096 9279 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
9280 u8 opcode = BPF_OP(insn->code);
9281
2589726d 9282 env->jmps_processed++;
17a52670
AS
9283 if (opcode == BPF_CALL) {
9284 if (BPF_SRC(insn->code) != BPF_K ||
9285 insn->off != 0 ||
f4d7e40a
AS
9286 (insn->src_reg != BPF_REG_0 &&
9287 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
9288 insn->dst_reg != BPF_REG_0 ||
9289 class == BPF_JMP32) {
61bd5218 9290 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
9291 return -EINVAL;
9292 }
9293
d83525ca
AS
9294 if (env->cur_state->active_spin_lock &&
9295 (insn->src_reg == BPF_PSEUDO_CALL ||
9296 insn->imm != BPF_FUNC_spin_unlock)) {
9297 verbose(env, "function calls are not allowed while holding a lock\n");
9298 return -EINVAL;
9299 }
f4d7e40a 9300 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 9301 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 9302 else
c08435ec 9303 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
9304 if (err)
9305 return err;
9306
9307 } else if (opcode == BPF_JA) {
9308 if (BPF_SRC(insn->code) != BPF_K ||
9309 insn->imm != 0 ||
9310 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9311 insn->dst_reg != BPF_REG_0 ||
9312 class == BPF_JMP32) {
61bd5218 9313 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
9314 return -EINVAL;
9315 }
9316
c08435ec 9317 env->insn_idx += insn->off + 1;
17a52670
AS
9318 continue;
9319
9320 } else if (opcode == BPF_EXIT) {
9321 if (BPF_SRC(insn->code) != BPF_K ||
9322 insn->imm != 0 ||
9323 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9324 insn->dst_reg != BPF_REG_0 ||
9325 class == BPF_JMP32) {
61bd5218 9326 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
9327 return -EINVAL;
9328 }
9329
d83525ca
AS
9330 if (env->cur_state->active_spin_lock) {
9331 verbose(env, "bpf_spin_unlock is missing\n");
9332 return -EINVAL;
9333 }
9334
f4d7e40a
AS
9335 if (state->curframe) {
9336 /* exit from nested function */
c08435ec 9337 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
9338 if (err)
9339 return err;
9340 do_print_state = true;
9341 continue;
9342 }
9343
fd978bf7
JS
9344 err = check_reference_leak(env);
9345 if (err)
9346 return err;
9347
390ee7e2
AS
9348 err = check_return_code(env);
9349 if (err)
9350 return err;
f1bca824 9351process_bpf_exit:
2589726d 9352 update_branch_counts(env, env->cur_state);
b5dc0163 9353 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 9354 &env->insn_idx, pop_log);
638f5b90
AS
9355 if (err < 0) {
9356 if (err != -ENOENT)
9357 return err;
17a52670
AS
9358 break;
9359 } else {
9360 do_print_state = true;
9361 continue;
9362 }
9363 } else {
c08435ec 9364 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
9365 if (err)
9366 return err;
9367 }
9368 } else if (class == BPF_LD) {
9369 u8 mode = BPF_MODE(insn->code);
9370
9371 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
9372 err = check_ld_abs(env, insn);
9373 if (err)
9374 return err;
9375
17a52670
AS
9376 } else if (mode == BPF_IMM) {
9377 err = check_ld_imm(env, insn);
9378 if (err)
9379 return err;
9380
c08435ec 9381 env->insn_idx++;
51c39bb1 9382 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 9383 } else {
61bd5218 9384 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
9385 return -EINVAL;
9386 }
9387 } else {
61bd5218 9388 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
9389 return -EINVAL;
9390 }
9391
c08435ec 9392 env->insn_idx++;
17a52670
AS
9393 }
9394
9395 return 0;
9396}
9397
56f668df
MKL
9398static int check_map_prealloc(struct bpf_map *map)
9399{
9400 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
9401 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9402 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
9403 !(map->map_flags & BPF_F_NO_PREALLOC);
9404}
9405
d83525ca
AS
9406static bool is_tracing_prog_type(enum bpf_prog_type type)
9407{
9408 switch (type) {
9409 case BPF_PROG_TYPE_KPROBE:
9410 case BPF_PROG_TYPE_TRACEPOINT:
9411 case BPF_PROG_TYPE_PERF_EVENT:
9412 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9413 return true;
9414 default:
9415 return false;
9416 }
9417}
9418
94dacdbd
TG
9419static bool is_preallocated_map(struct bpf_map *map)
9420{
9421 if (!check_map_prealloc(map))
9422 return false;
9423 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9424 return false;
9425 return true;
9426}
9427
61bd5218
JK
9428static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9429 struct bpf_map *map,
fdc15d38
AS
9430 struct bpf_prog *prog)
9431
9432{
7e40781c 9433 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
9434 /*
9435 * Validate that trace type programs use preallocated hash maps.
9436 *
9437 * For programs attached to PERF events this is mandatory as the
9438 * perf NMI can hit any arbitrary code sequence.
9439 *
9440 * All other trace types using preallocated hash maps are unsafe as
9441 * well because tracepoint or kprobes can be inside locked regions
9442 * of the memory allocator or at a place where a recursion into the
9443 * memory allocator would see inconsistent state.
9444 *
2ed905c5
TG
9445 * On RT enabled kernels run-time allocation of all trace type
9446 * programs is strictly prohibited due to lock type constraints. On
9447 * !RT kernels it is allowed for backwards compatibility reasons for
9448 * now, but warnings are emitted so developers are made aware of
9449 * the unsafety and can fix their programs before this is enforced.
56f668df 9450 */
7e40781c
UP
9451 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9452 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 9453 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
9454 return -EINVAL;
9455 }
2ed905c5
TG
9456 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9457 verbose(env, "trace type programs can only use preallocated hash map\n");
9458 return -EINVAL;
9459 }
94dacdbd
TG
9460 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9461 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 9462 }
a3884572 9463
7e40781c
UP
9464 if ((is_tracing_prog_type(prog_type) ||
9465 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
d83525ca
AS
9466 map_value_has_spin_lock(map)) {
9467 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9468 return -EINVAL;
9469 }
9470
a3884572 9471 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 9472 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
9473 verbose(env, "offload device mismatch between prog and map\n");
9474 return -EINVAL;
9475 }
9476
85d33df3
MKL
9477 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9478 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9479 return -EINVAL;
9480 }
9481
1e6c62a8
AS
9482 if (prog->aux->sleepable)
9483 switch (map->map_type) {
9484 case BPF_MAP_TYPE_HASH:
9485 case BPF_MAP_TYPE_LRU_HASH:
9486 case BPF_MAP_TYPE_ARRAY:
9487 if (!is_preallocated_map(map)) {
9488 verbose(env,
9489 "Sleepable programs can only use preallocated hash maps\n");
9490 return -EINVAL;
9491 }
9492 break;
9493 default:
9494 verbose(env,
9495 "Sleepable programs can only use array and hash maps\n");
9496 return -EINVAL;
9497 }
9498
fdc15d38
AS
9499 return 0;
9500}
9501
b741f163
RG
9502static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9503{
9504 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9505 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9506}
9507
0246e64d
AS
9508/* look for pseudo eBPF instructions that access map FDs and
9509 * replace them with actual map pointers
9510 */
58e2af8b 9511static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
9512{
9513 struct bpf_insn *insn = env->prog->insnsi;
9514 int insn_cnt = env->prog->len;
fdc15d38 9515 int i, j, err;
0246e64d 9516
f1f7714e 9517 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
9518 if (err)
9519 return err;
9520
0246e64d 9521 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 9522 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 9523 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 9524 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
9525 return -EINVAL;
9526 }
9527
d691f9e8
AS
9528 if (BPF_CLASS(insn->code) == BPF_STX &&
9529 ((BPF_MODE(insn->code) != BPF_MEM &&
9530 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 9531 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
9532 return -EINVAL;
9533 }
9534
0246e64d 9535 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 9536 struct bpf_insn_aux_data *aux;
0246e64d
AS
9537 struct bpf_map *map;
9538 struct fd f;
d8eca5bb 9539 u64 addr;
0246e64d
AS
9540
9541 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9542 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9543 insn[1].off != 0) {
61bd5218 9544 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
9545 return -EINVAL;
9546 }
9547
d8eca5bb 9548 if (insn[0].src_reg == 0)
0246e64d
AS
9549 /* valid generic load 64-bit imm */
9550 goto next_insn;
9551
d8eca5bb
DB
9552 /* In final convert_pseudo_ld_imm64() step, this is
9553 * converted into regular 64-bit imm load insn.
9554 */
9555 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9556 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9557 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9558 insn[1].imm != 0)) {
9559 verbose(env,
9560 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
9561 return -EINVAL;
9562 }
9563
20182390 9564 f = fdget(insn[0].imm);
c2101297 9565 map = __bpf_map_get(f);
0246e64d 9566 if (IS_ERR(map)) {
61bd5218 9567 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 9568 insn[0].imm);
0246e64d
AS
9569 return PTR_ERR(map);
9570 }
9571
61bd5218 9572 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
9573 if (err) {
9574 fdput(f);
9575 return err;
9576 }
9577
d8eca5bb
DB
9578 aux = &env->insn_aux_data[i];
9579 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9580 addr = (unsigned long)map;
9581 } else {
9582 u32 off = insn[1].imm;
9583
9584 if (off >= BPF_MAX_VAR_OFF) {
9585 verbose(env, "direct value offset of %u is not allowed\n", off);
9586 fdput(f);
9587 return -EINVAL;
9588 }
9589
9590 if (!map->ops->map_direct_value_addr) {
9591 verbose(env, "no direct value access support for this map type\n");
9592 fdput(f);
9593 return -EINVAL;
9594 }
9595
9596 err = map->ops->map_direct_value_addr(map, &addr, off);
9597 if (err) {
9598 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9599 map->value_size, off);
9600 fdput(f);
9601 return err;
9602 }
9603
9604 aux->map_off = off;
9605 addr += off;
9606 }
9607
9608 insn[0].imm = (u32)addr;
9609 insn[1].imm = addr >> 32;
0246e64d
AS
9610
9611 /* check whether we recorded this map already */
d8eca5bb 9612 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 9613 if (env->used_maps[j] == map) {
d8eca5bb 9614 aux->map_index = j;
0246e64d
AS
9615 fdput(f);
9616 goto next_insn;
9617 }
d8eca5bb 9618 }
0246e64d
AS
9619
9620 if (env->used_map_cnt >= MAX_USED_MAPS) {
9621 fdput(f);
9622 return -E2BIG;
9623 }
9624
0246e64d
AS
9625 /* hold the map. If the program is rejected by verifier,
9626 * the map will be released by release_maps() or it
9627 * will be used by the valid program until it's unloaded
ab7f5bf0 9628 * and all maps are released in free_used_maps()
0246e64d 9629 */
1e0bd5a0 9630 bpf_map_inc(map);
d8eca5bb
DB
9631
9632 aux->map_index = env->used_map_cnt;
92117d84
AS
9633 env->used_maps[env->used_map_cnt++] = map;
9634
b741f163 9635 if (bpf_map_is_cgroup_storage(map) &&
e4730423 9636 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 9637 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
9638 fdput(f);
9639 return -EBUSY;
9640 }
9641
0246e64d
AS
9642 fdput(f);
9643next_insn:
9644 insn++;
9645 i++;
5e581dad
DB
9646 continue;
9647 }
9648
9649 /* Basic sanity check before we invest more work here. */
9650 if (!bpf_opcode_in_insntable(insn->code)) {
9651 verbose(env, "unknown opcode %02x\n", insn->code);
9652 return -EINVAL;
0246e64d
AS
9653 }
9654 }
9655
9656 /* now all pseudo BPF_LD_IMM64 instructions load valid
9657 * 'struct bpf_map *' into a register instead of user map_fd.
9658 * These pointers will be used later by verifier to validate map access.
9659 */
9660 return 0;
9661}
9662
9663/* drop refcnt of maps used by the rejected program */
58e2af8b 9664static void release_maps(struct bpf_verifier_env *env)
0246e64d 9665{
a2ea0746
DB
9666 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9667 env->used_map_cnt);
0246e64d
AS
9668}
9669
9670/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 9671static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
9672{
9673 struct bpf_insn *insn = env->prog->insnsi;
9674 int insn_cnt = env->prog->len;
9675 int i;
9676
9677 for (i = 0; i < insn_cnt; i++, insn++)
9678 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9679 insn->src_reg = 0;
9680}
9681
8041902d
AS
9682/* single env->prog->insni[off] instruction was replaced with the range
9683 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9684 * [0, off) and [off, end) to new locations, so the patched range stays zero
9685 */
b325fbca
JW
9686static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9687 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
9688{
9689 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
9690 struct bpf_insn *insn = new_prog->insnsi;
9691 u32 prog_len;
c131187d 9692 int i;
8041902d 9693
b325fbca
JW
9694 /* aux info at OFF always needs adjustment, no matter fast path
9695 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9696 * original insn at old prog.
9697 */
9698 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9699
8041902d
AS
9700 if (cnt == 1)
9701 return 0;
b325fbca 9702 prog_len = new_prog->len;
fad953ce
KC
9703 new_data = vzalloc(array_size(prog_len,
9704 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
9705 if (!new_data)
9706 return -ENOMEM;
9707 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9708 memcpy(new_data + off + cnt - 1, old_data + off,
9709 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 9710 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 9711 new_data[i].seen = env->pass_cnt;
b325fbca
JW
9712 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9713 }
8041902d
AS
9714 env->insn_aux_data = new_data;
9715 vfree(old_data);
9716 return 0;
9717}
9718
cc8b0b92
AS
9719static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9720{
9721 int i;
9722
9723 if (len == 1)
9724 return;
4cb3d99c
JW
9725 /* NOTE: fake 'exit' subprog should be updated as well. */
9726 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 9727 if (env->subprog_info[i].start <= off)
cc8b0b92 9728 continue;
9c8105bd 9729 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
9730 }
9731}
9732
a748c697
MF
9733static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
9734{
9735 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
9736 int i, sz = prog->aux->size_poke_tab;
9737 struct bpf_jit_poke_descriptor *desc;
9738
9739 for (i = 0; i < sz; i++) {
9740 desc = &tab[i];
9741 desc->insn_idx += len - 1;
9742 }
9743}
9744
8041902d
AS
9745static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9746 const struct bpf_insn *patch, u32 len)
9747{
9748 struct bpf_prog *new_prog;
9749
9750 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
9751 if (IS_ERR(new_prog)) {
9752 if (PTR_ERR(new_prog) == -ERANGE)
9753 verbose(env,
9754 "insn %d cannot be patched due to 16-bit range\n",
9755 env->insn_aux_data[off].orig_idx);
8041902d 9756 return NULL;
4f73379e 9757 }
b325fbca 9758 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 9759 return NULL;
cc8b0b92 9760 adjust_subprog_starts(env, off, len);
a748c697 9761 adjust_poke_descs(new_prog, len);
8041902d
AS
9762 return new_prog;
9763}
9764
52875a04
JK
9765static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9766 u32 off, u32 cnt)
9767{
9768 int i, j;
9769
9770 /* find first prog starting at or after off (first to remove) */
9771 for (i = 0; i < env->subprog_cnt; i++)
9772 if (env->subprog_info[i].start >= off)
9773 break;
9774 /* find first prog starting at or after off + cnt (first to stay) */
9775 for (j = i; j < env->subprog_cnt; j++)
9776 if (env->subprog_info[j].start >= off + cnt)
9777 break;
9778 /* if j doesn't start exactly at off + cnt, we are just removing
9779 * the front of previous prog
9780 */
9781 if (env->subprog_info[j].start != off + cnt)
9782 j--;
9783
9784 if (j > i) {
9785 struct bpf_prog_aux *aux = env->prog->aux;
9786 int move;
9787
9788 /* move fake 'exit' subprog as well */
9789 move = env->subprog_cnt + 1 - j;
9790
9791 memmove(env->subprog_info + i,
9792 env->subprog_info + j,
9793 sizeof(*env->subprog_info) * move);
9794 env->subprog_cnt -= j - i;
9795
9796 /* remove func_info */
9797 if (aux->func_info) {
9798 move = aux->func_info_cnt - j;
9799
9800 memmove(aux->func_info + i,
9801 aux->func_info + j,
9802 sizeof(*aux->func_info) * move);
9803 aux->func_info_cnt -= j - i;
9804 /* func_info->insn_off is set after all code rewrites,
9805 * in adjust_btf_func() - no need to adjust
9806 */
9807 }
9808 } else {
9809 /* convert i from "first prog to remove" to "first to adjust" */
9810 if (env->subprog_info[i].start == off)
9811 i++;
9812 }
9813
9814 /* update fake 'exit' subprog as well */
9815 for (; i <= env->subprog_cnt; i++)
9816 env->subprog_info[i].start -= cnt;
9817
9818 return 0;
9819}
9820
9821static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9822 u32 cnt)
9823{
9824 struct bpf_prog *prog = env->prog;
9825 u32 i, l_off, l_cnt, nr_linfo;
9826 struct bpf_line_info *linfo;
9827
9828 nr_linfo = prog->aux->nr_linfo;
9829 if (!nr_linfo)
9830 return 0;
9831
9832 linfo = prog->aux->linfo;
9833
9834 /* find first line info to remove, count lines to be removed */
9835 for (i = 0; i < nr_linfo; i++)
9836 if (linfo[i].insn_off >= off)
9837 break;
9838
9839 l_off = i;
9840 l_cnt = 0;
9841 for (; i < nr_linfo; i++)
9842 if (linfo[i].insn_off < off + cnt)
9843 l_cnt++;
9844 else
9845 break;
9846
9847 /* First live insn doesn't match first live linfo, it needs to "inherit"
9848 * last removed linfo. prog is already modified, so prog->len == off
9849 * means no live instructions after (tail of the program was removed).
9850 */
9851 if (prog->len != off && l_cnt &&
9852 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9853 l_cnt--;
9854 linfo[--i].insn_off = off + cnt;
9855 }
9856
9857 /* remove the line info which refer to the removed instructions */
9858 if (l_cnt) {
9859 memmove(linfo + l_off, linfo + i,
9860 sizeof(*linfo) * (nr_linfo - i));
9861
9862 prog->aux->nr_linfo -= l_cnt;
9863 nr_linfo = prog->aux->nr_linfo;
9864 }
9865
9866 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9867 for (i = l_off; i < nr_linfo; i++)
9868 linfo[i].insn_off -= cnt;
9869
9870 /* fix up all subprogs (incl. 'exit') which start >= off */
9871 for (i = 0; i <= env->subprog_cnt; i++)
9872 if (env->subprog_info[i].linfo_idx > l_off) {
9873 /* program may have started in the removed region but
9874 * may not be fully removed
9875 */
9876 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9877 env->subprog_info[i].linfo_idx -= l_cnt;
9878 else
9879 env->subprog_info[i].linfo_idx = l_off;
9880 }
9881
9882 return 0;
9883}
9884
9885static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9886{
9887 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9888 unsigned int orig_prog_len = env->prog->len;
9889 int err;
9890
08ca90af
JK
9891 if (bpf_prog_is_dev_bound(env->prog->aux))
9892 bpf_prog_offload_remove_insns(env, off, cnt);
9893
52875a04
JK
9894 err = bpf_remove_insns(env->prog, off, cnt);
9895 if (err)
9896 return err;
9897
9898 err = adjust_subprog_starts_after_remove(env, off, cnt);
9899 if (err)
9900 return err;
9901
9902 err = bpf_adj_linfo_after_remove(env, off, cnt);
9903 if (err)
9904 return err;
9905
9906 memmove(aux_data + off, aux_data + off + cnt,
9907 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9908
9909 return 0;
9910}
9911
2a5418a1
DB
9912/* The verifier does more data flow analysis than llvm and will not
9913 * explore branches that are dead at run time. Malicious programs can
9914 * have dead code too. Therefore replace all dead at-run-time code
9915 * with 'ja -1'.
9916 *
9917 * Just nops are not optimal, e.g. if they would sit at the end of the
9918 * program and through another bug we would manage to jump there, then
9919 * we'd execute beyond program memory otherwise. Returning exception
9920 * code also wouldn't work since we can have subprogs where the dead
9921 * code could be located.
c131187d
AS
9922 */
9923static void sanitize_dead_code(struct bpf_verifier_env *env)
9924{
9925 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 9926 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
9927 struct bpf_insn *insn = env->prog->insnsi;
9928 const int insn_cnt = env->prog->len;
9929 int i;
9930
9931 for (i = 0; i < insn_cnt; i++) {
9932 if (aux_data[i].seen)
9933 continue;
2a5418a1 9934 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
9935 }
9936}
9937
e2ae4ca2
JK
9938static bool insn_is_cond_jump(u8 code)
9939{
9940 u8 op;
9941
092ed096
JW
9942 if (BPF_CLASS(code) == BPF_JMP32)
9943 return true;
9944
e2ae4ca2
JK
9945 if (BPF_CLASS(code) != BPF_JMP)
9946 return false;
9947
9948 op = BPF_OP(code);
9949 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9950}
9951
9952static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9953{
9954 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9955 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9956 struct bpf_insn *insn = env->prog->insnsi;
9957 const int insn_cnt = env->prog->len;
9958 int i;
9959
9960 for (i = 0; i < insn_cnt; i++, insn++) {
9961 if (!insn_is_cond_jump(insn->code))
9962 continue;
9963
9964 if (!aux_data[i + 1].seen)
9965 ja.off = insn->off;
9966 else if (!aux_data[i + 1 + insn->off].seen)
9967 ja.off = 0;
9968 else
9969 continue;
9970
08ca90af
JK
9971 if (bpf_prog_is_dev_bound(env->prog->aux))
9972 bpf_prog_offload_replace_insn(env, i, &ja);
9973
e2ae4ca2
JK
9974 memcpy(insn, &ja, sizeof(ja));
9975 }
9976}
9977
52875a04
JK
9978static int opt_remove_dead_code(struct bpf_verifier_env *env)
9979{
9980 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9981 int insn_cnt = env->prog->len;
9982 int i, err;
9983
9984 for (i = 0; i < insn_cnt; i++) {
9985 int j;
9986
9987 j = 0;
9988 while (i + j < insn_cnt && !aux_data[i + j].seen)
9989 j++;
9990 if (!j)
9991 continue;
9992
9993 err = verifier_remove_insns(env, i, j);
9994 if (err)
9995 return err;
9996 insn_cnt = env->prog->len;
9997 }
9998
9999 return 0;
10000}
10001
a1b14abc
JK
10002static int opt_remove_nops(struct bpf_verifier_env *env)
10003{
10004 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10005 struct bpf_insn *insn = env->prog->insnsi;
10006 int insn_cnt = env->prog->len;
10007 int i, err;
10008
10009 for (i = 0; i < insn_cnt; i++) {
10010 if (memcmp(&insn[i], &ja, sizeof(ja)))
10011 continue;
10012
10013 err = verifier_remove_insns(env, i, 1);
10014 if (err)
10015 return err;
10016 insn_cnt--;
10017 i--;
10018 }
10019
10020 return 0;
10021}
10022
d6c2308c
JW
10023static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10024 const union bpf_attr *attr)
a4b1d3c1 10025{
d6c2308c 10026 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 10027 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 10028 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 10029 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 10030 struct bpf_prog *new_prog;
d6c2308c 10031 bool rnd_hi32;
a4b1d3c1 10032
d6c2308c 10033 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 10034 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
10035 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10036 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10037 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
10038 for (i = 0; i < len; i++) {
10039 int adj_idx = i + delta;
10040 struct bpf_insn insn;
10041
d6c2308c
JW
10042 insn = insns[adj_idx];
10043 if (!aux[adj_idx].zext_dst) {
10044 u8 code, class;
10045 u32 imm_rnd;
10046
10047 if (!rnd_hi32)
10048 continue;
10049
10050 code = insn.code;
10051 class = BPF_CLASS(code);
10052 if (insn_no_def(&insn))
10053 continue;
10054
10055 /* NOTE: arg "reg" (the fourth one) is only used for
10056 * BPF_STX which has been ruled out in above
10057 * check, it is safe to pass NULL here.
10058 */
10059 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10060 if (class == BPF_LD &&
10061 BPF_MODE(code) == BPF_IMM)
10062 i++;
10063 continue;
10064 }
10065
10066 /* ctx load could be transformed into wider load. */
10067 if (class == BPF_LDX &&
10068 aux[adj_idx].ptr_type == PTR_TO_CTX)
10069 continue;
10070
10071 imm_rnd = get_random_int();
10072 rnd_hi32_patch[0] = insn;
10073 rnd_hi32_patch[1].imm = imm_rnd;
10074 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10075 patch = rnd_hi32_patch;
10076 patch_len = 4;
10077 goto apply_patch_buffer;
10078 }
10079
10080 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
10081 continue;
10082
a4b1d3c1
JW
10083 zext_patch[0] = insn;
10084 zext_patch[1].dst_reg = insn.dst_reg;
10085 zext_patch[1].src_reg = insn.dst_reg;
d6c2308c
JW
10086 patch = zext_patch;
10087 patch_len = 2;
10088apply_patch_buffer:
10089 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
10090 if (!new_prog)
10091 return -ENOMEM;
10092 env->prog = new_prog;
10093 insns = new_prog->insnsi;
10094 aux = env->insn_aux_data;
d6c2308c 10095 delta += patch_len - 1;
a4b1d3c1
JW
10096 }
10097
10098 return 0;
10099}
10100
c64b7983
JS
10101/* convert load instructions that access fields of a context type into a
10102 * sequence of instructions that access fields of the underlying structure:
10103 * struct __sk_buff -> struct sk_buff
10104 * struct bpf_sock_ops -> struct sock
9bac3d6d 10105 */
58e2af8b 10106static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 10107{
00176a34 10108 const struct bpf_verifier_ops *ops = env->ops;
f96da094 10109 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 10110 const int insn_cnt = env->prog->len;
36bbef52 10111 struct bpf_insn insn_buf[16], *insn;
46f53a65 10112 u32 target_size, size_default, off;
9bac3d6d 10113 struct bpf_prog *new_prog;
d691f9e8 10114 enum bpf_access_type type;
f96da094 10115 bool is_narrower_load;
9bac3d6d 10116
b09928b9
DB
10117 if (ops->gen_prologue || env->seen_direct_write) {
10118 if (!ops->gen_prologue) {
10119 verbose(env, "bpf verifier is misconfigured\n");
10120 return -EINVAL;
10121 }
36bbef52
DB
10122 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10123 env->prog);
10124 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 10125 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
10126 return -EINVAL;
10127 } else if (cnt) {
8041902d 10128 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
10129 if (!new_prog)
10130 return -ENOMEM;
8041902d 10131
36bbef52 10132 env->prog = new_prog;
3df126f3 10133 delta += cnt - 1;
36bbef52
DB
10134 }
10135 }
10136
c64b7983 10137 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
10138 return 0;
10139
3df126f3 10140 insn = env->prog->insnsi + delta;
36bbef52 10141
9bac3d6d 10142 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
10143 bpf_convert_ctx_access_t convert_ctx_access;
10144
62c7989b
DB
10145 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10146 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10147 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 10148 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 10149 type = BPF_READ;
62c7989b
DB
10150 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10151 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10152 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 10153 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
10154 type = BPF_WRITE;
10155 else
9bac3d6d
AS
10156 continue;
10157
af86ca4e
AS
10158 if (type == BPF_WRITE &&
10159 env->insn_aux_data[i + delta].sanitize_stack_off) {
10160 struct bpf_insn patch[] = {
10161 /* Sanitize suspicious stack slot with zero.
10162 * There are no memory dependencies for this store,
10163 * since it's only using frame pointer and immediate
10164 * constant of zero
10165 */
10166 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10167 env->insn_aux_data[i + delta].sanitize_stack_off,
10168 0),
10169 /* the original STX instruction will immediately
10170 * overwrite the same stack slot with appropriate value
10171 */
10172 *insn,
10173 };
10174
10175 cnt = ARRAY_SIZE(patch);
10176 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10177 if (!new_prog)
10178 return -ENOMEM;
10179
10180 delta += cnt - 1;
10181 env->prog = new_prog;
10182 insn = new_prog->insnsi + i + delta;
10183 continue;
10184 }
10185
c64b7983
JS
10186 switch (env->insn_aux_data[i + delta].ptr_type) {
10187 case PTR_TO_CTX:
10188 if (!ops->convert_ctx_access)
10189 continue;
10190 convert_ctx_access = ops->convert_ctx_access;
10191 break;
10192 case PTR_TO_SOCKET:
46f8bc92 10193 case PTR_TO_SOCK_COMMON:
c64b7983
JS
10194 convert_ctx_access = bpf_sock_convert_ctx_access;
10195 break;
655a51e5
MKL
10196 case PTR_TO_TCP_SOCK:
10197 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10198 break;
fada7fdc
JL
10199 case PTR_TO_XDP_SOCK:
10200 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10201 break;
2a02759e 10202 case PTR_TO_BTF_ID:
27ae7997
MKL
10203 if (type == BPF_READ) {
10204 insn->code = BPF_LDX | BPF_PROBE_MEM |
10205 BPF_SIZE((insn)->code);
10206 env->prog->aux->num_exentries++;
7e40781c 10207 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
10208 verbose(env, "Writes through BTF pointers are not allowed\n");
10209 return -EINVAL;
10210 }
2a02759e 10211 continue;
c64b7983 10212 default:
9bac3d6d 10213 continue;
c64b7983 10214 }
9bac3d6d 10215
31fd8581 10216 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 10217 size = BPF_LDST_BYTES(insn);
31fd8581
YS
10218
10219 /* If the read access is a narrower load of the field,
10220 * convert to a 4/8-byte load, to minimum program type specific
10221 * convert_ctx_access changes. If conversion is successful,
10222 * we will apply proper mask to the result.
10223 */
f96da094 10224 is_narrower_load = size < ctx_field_size;
46f53a65
AI
10225 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10226 off = insn->off;
31fd8581 10227 if (is_narrower_load) {
f96da094
DB
10228 u8 size_code;
10229
10230 if (type == BPF_WRITE) {
61bd5218 10231 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
10232 return -EINVAL;
10233 }
31fd8581 10234
f96da094 10235 size_code = BPF_H;
31fd8581
YS
10236 if (ctx_field_size == 4)
10237 size_code = BPF_W;
10238 else if (ctx_field_size == 8)
10239 size_code = BPF_DW;
f96da094 10240
bc23105c 10241 insn->off = off & ~(size_default - 1);
31fd8581
YS
10242 insn->code = BPF_LDX | BPF_MEM | size_code;
10243 }
f96da094
DB
10244
10245 target_size = 0;
c64b7983
JS
10246 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10247 &target_size);
f96da094
DB
10248 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10249 (ctx_field_size && !target_size)) {
61bd5218 10250 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
10251 return -EINVAL;
10252 }
f96da094
DB
10253
10254 if (is_narrower_load && size < target_size) {
d895a0f1
IL
10255 u8 shift = bpf_ctx_narrow_access_offset(
10256 off, size, size_default) * 8;
46f53a65
AI
10257 if (ctx_field_size <= 4) {
10258 if (shift)
10259 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10260 insn->dst_reg,
10261 shift);
31fd8581 10262 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 10263 (1 << size * 8) - 1);
46f53a65
AI
10264 } else {
10265 if (shift)
10266 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10267 insn->dst_reg,
10268 shift);
31fd8581 10269 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 10270 (1ULL << size * 8) - 1);
46f53a65 10271 }
31fd8581 10272 }
9bac3d6d 10273
8041902d 10274 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
10275 if (!new_prog)
10276 return -ENOMEM;
10277
3df126f3 10278 delta += cnt - 1;
9bac3d6d
AS
10279
10280 /* keep walking new program and skip insns we just inserted */
10281 env->prog = new_prog;
3df126f3 10282 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
10283 }
10284
10285 return 0;
10286}
10287
1c2a088a
AS
10288static int jit_subprogs(struct bpf_verifier_env *env)
10289{
10290 struct bpf_prog *prog = env->prog, **func, *tmp;
10291 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 10292 struct bpf_map *map_ptr;
7105e828 10293 struct bpf_insn *insn;
1c2a088a 10294 void *old_bpf_func;
c4c0bdc0 10295 int err, num_exentries;
1c2a088a 10296
f910cefa 10297 if (env->subprog_cnt <= 1)
1c2a088a
AS
10298 return 0;
10299
7105e828 10300 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
10301 if (insn->code != (BPF_JMP | BPF_CALL) ||
10302 insn->src_reg != BPF_PSEUDO_CALL)
10303 continue;
c7a89784
DB
10304 /* Upon error here we cannot fall back to interpreter but
10305 * need a hard reject of the program. Thus -EFAULT is
10306 * propagated in any case.
10307 */
1c2a088a
AS
10308 subprog = find_subprog(env, i + insn->imm + 1);
10309 if (subprog < 0) {
10310 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10311 i + insn->imm + 1);
10312 return -EFAULT;
10313 }
10314 /* temporarily remember subprog id inside insn instead of
10315 * aux_data, since next loop will split up all insns into funcs
10316 */
f910cefa 10317 insn->off = subprog;
1c2a088a
AS
10318 /* remember original imm in case JIT fails and fallback
10319 * to interpreter will be needed
10320 */
10321 env->insn_aux_data[i].call_imm = insn->imm;
10322 /* point imm to __bpf_call_base+1 from JITs point of view */
10323 insn->imm = 1;
10324 }
10325
c454a46b
MKL
10326 err = bpf_prog_alloc_jited_linfo(prog);
10327 if (err)
10328 goto out_undo_insn;
10329
10330 err = -ENOMEM;
6396bb22 10331 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 10332 if (!func)
c7a89784 10333 goto out_undo_insn;
1c2a088a 10334
f910cefa 10335 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 10336 subprog_start = subprog_end;
4cb3d99c 10337 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
10338
10339 len = subprog_end - subprog_start;
492ecee8
AS
10340 /* BPF_PROG_RUN doesn't call subprogs directly,
10341 * hence main prog stats include the runtime of subprogs.
10342 * subprogs don't have IDs and not reachable via prog_get_next_id
10343 * func[i]->aux->stats will never be accessed and stays NULL
10344 */
10345 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
10346 if (!func[i])
10347 goto out_free;
10348 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10349 len * sizeof(struct bpf_insn));
4f74d809 10350 func[i]->type = prog->type;
1c2a088a 10351 func[i]->len = len;
4f74d809
DB
10352 if (bpf_prog_calc_tag(func[i]))
10353 goto out_free;
1c2a088a 10354 func[i]->is_func = 1;
ba64e7d8
YS
10355 func[i]->aux->func_idx = i;
10356 /* the btf and func_info will be freed only at prog->aux */
10357 func[i]->aux->btf = prog->aux->btf;
10358 func[i]->aux->func_info = prog->aux->func_info;
10359
a748c697
MF
10360 for (j = 0; j < prog->aux->size_poke_tab; j++) {
10361 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10362 int ret;
10363
10364 if (!(insn_idx >= subprog_start &&
10365 insn_idx <= subprog_end))
10366 continue;
10367
10368 ret = bpf_jit_add_poke_descriptor(func[i],
10369 &prog->aux->poke_tab[j]);
10370 if (ret < 0) {
10371 verbose(env, "adding tail call poke descriptor failed\n");
10372 goto out_free;
10373 }
10374
10375 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10376
10377 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10378 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10379 if (ret < 0) {
10380 verbose(env, "tracking tail call prog failed\n");
10381 goto out_free;
10382 }
10383 }
10384
1c2a088a
AS
10385 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10386 * Long term would need debug info to populate names
10387 */
10388 func[i]->aux->name[0] = 'F';
9c8105bd 10389 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 10390 func[i]->jit_requested = 1;
c454a46b
MKL
10391 func[i]->aux->linfo = prog->aux->linfo;
10392 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10393 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10394 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
10395 num_exentries = 0;
10396 insn = func[i]->insnsi;
10397 for (j = 0; j < func[i]->len; j++, insn++) {
10398 if (BPF_CLASS(insn->code) == BPF_LDX &&
10399 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10400 num_exentries++;
10401 }
10402 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 10403 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
10404 func[i] = bpf_int_jit_compile(func[i]);
10405 if (!func[i]->jited) {
10406 err = -ENOTSUPP;
10407 goto out_free;
10408 }
10409 cond_resched();
10410 }
a748c697
MF
10411
10412 /* Untrack main program's aux structs so that during map_poke_run()
10413 * we will not stumble upon the unfilled poke descriptors; each
10414 * of the main program's poke descs got distributed across subprogs
10415 * and got tracked onto map, so we are sure that none of them will
10416 * be missed after the operation below
10417 */
10418 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10419 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10420
10421 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10422 }
10423
1c2a088a
AS
10424 /* at this point all bpf functions were successfully JITed
10425 * now populate all bpf_calls with correct addresses and
10426 * run last pass of JIT
10427 */
f910cefa 10428 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10429 insn = func[i]->insnsi;
10430 for (j = 0; j < func[i]->len; j++, insn++) {
10431 if (insn->code != (BPF_JMP | BPF_CALL) ||
10432 insn->src_reg != BPF_PSEUDO_CALL)
10433 continue;
10434 subprog = insn->off;
0d306c31
PB
10435 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10436 __bpf_call_base;
1c2a088a 10437 }
2162fed4
SD
10438
10439 /* we use the aux data to keep a list of the start addresses
10440 * of the JITed images for each function in the program
10441 *
10442 * for some architectures, such as powerpc64, the imm field
10443 * might not be large enough to hold the offset of the start
10444 * address of the callee's JITed image from __bpf_call_base
10445 *
10446 * in such cases, we can lookup the start address of a callee
10447 * by using its subprog id, available from the off field of
10448 * the call instruction, as an index for this list
10449 */
10450 func[i]->aux->func = func;
10451 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 10452 }
f910cefa 10453 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10454 old_bpf_func = func[i]->bpf_func;
10455 tmp = bpf_int_jit_compile(func[i]);
10456 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10457 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 10458 err = -ENOTSUPP;
1c2a088a
AS
10459 goto out_free;
10460 }
10461 cond_resched();
10462 }
10463
10464 /* finally lock prog and jit images for all functions and
10465 * populate kallsysm
10466 */
f910cefa 10467 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10468 bpf_prog_lock_ro(func[i]);
10469 bpf_prog_kallsyms_add(func[i]);
10470 }
7105e828
DB
10471
10472 /* Last step: make now unused interpreter insns from main
10473 * prog consistent for later dump requests, so they can
10474 * later look the same as if they were interpreted only.
10475 */
10476 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
10477 if (insn->code != (BPF_JMP | BPF_CALL) ||
10478 insn->src_reg != BPF_PSEUDO_CALL)
10479 continue;
10480 insn->off = env->insn_aux_data[i].call_imm;
10481 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 10482 insn->imm = subprog;
7105e828
DB
10483 }
10484
1c2a088a
AS
10485 prog->jited = 1;
10486 prog->bpf_func = func[0]->bpf_func;
10487 prog->aux->func = func;
f910cefa 10488 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 10489 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
10490 return 0;
10491out_free:
a748c697
MF
10492 for (i = 0; i < env->subprog_cnt; i++) {
10493 if (!func[i])
10494 continue;
10495
10496 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10497 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10498 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10499 }
10500 bpf_jit_free(func[i]);
10501 }
1c2a088a 10502 kfree(func);
c7a89784 10503out_undo_insn:
1c2a088a
AS
10504 /* cleanup main prog to be interpreted */
10505 prog->jit_requested = 0;
10506 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10507 if (insn->code != (BPF_JMP | BPF_CALL) ||
10508 insn->src_reg != BPF_PSEUDO_CALL)
10509 continue;
10510 insn->off = 0;
10511 insn->imm = env->insn_aux_data[i].call_imm;
10512 }
c454a46b 10513 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
10514 return err;
10515}
10516
1ea47e01
AS
10517static int fixup_call_args(struct bpf_verifier_env *env)
10518{
19d28fbd 10519#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
10520 struct bpf_prog *prog = env->prog;
10521 struct bpf_insn *insn = prog->insnsi;
10522 int i, depth;
19d28fbd 10523#endif
e4052d06 10524 int err = 0;
1ea47e01 10525
e4052d06
QM
10526 if (env->prog->jit_requested &&
10527 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
10528 err = jit_subprogs(env);
10529 if (err == 0)
1c2a088a 10530 return 0;
c7a89784
DB
10531 if (err == -EFAULT)
10532 return err;
19d28fbd
DM
10533 }
10534#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
10535 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10536 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10537 * have to be rejected, since interpreter doesn't support them yet.
10538 */
10539 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10540 return -EINVAL;
10541 }
1ea47e01
AS
10542 for (i = 0; i < prog->len; i++, insn++) {
10543 if (insn->code != (BPF_JMP | BPF_CALL) ||
10544 insn->src_reg != BPF_PSEUDO_CALL)
10545 continue;
10546 depth = get_callee_stack_depth(env, insn, i);
10547 if (depth < 0)
10548 return depth;
10549 bpf_patch_call_args(insn, depth);
10550 }
19d28fbd
DM
10551 err = 0;
10552#endif
10553 return err;
1ea47e01
AS
10554}
10555
79741b3b 10556/* fixup insn->imm field of bpf_call instructions
81ed18ab 10557 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
10558 *
10559 * this function is called after eBPF program passed verification
10560 */
79741b3b 10561static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 10562{
79741b3b 10563 struct bpf_prog *prog = env->prog;
d2e4c1e6 10564 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 10565 struct bpf_insn *insn = prog->insnsi;
e245c5c6 10566 const struct bpf_func_proto *fn;
79741b3b 10567 const int insn_cnt = prog->len;
09772d92 10568 const struct bpf_map_ops *ops;
c93552c4 10569 struct bpf_insn_aux_data *aux;
81ed18ab
AS
10570 struct bpf_insn insn_buf[16];
10571 struct bpf_prog *new_prog;
10572 struct bpf_map *map_ptr;
d2e4c1e6 10573 int i, ret, cnt, delta = 0;
e245c5c6 10574
79741b3b 10575 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
10576 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10577 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10578 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 10579 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
10580 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10581 struct bpf_insn mask_and_div[] = {
10582 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10583 /* Rx div 0 -> 0 */
10584 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10585 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10586 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10587 *insn,
10588 };
10589 struct bpf_insn mask_and_mod[] = {
10590 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10591 /* Rx mod 0 -> Rx */
10592 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10593 *insn,
10594 };
10595 struct bpf_insn *patchlet;
10596
10597 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10598 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10599 patchlet = mask_and_div + (is64 ? 1 : 0);
10600 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10601 } else {
10602 patchlet = mask_and_mod + (is64 ? 1 : 0);
10603 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10604 }
10605
10606 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
10607 if (!new_prog)
10608 return -ENOMEM;
10609
10610 delta += cnt - 1;
10611 env->prog = prog = new_prog;
10612 insn = new_prog->insnsi + i + delta;
10613 continue;
10614 }
10615
e0cea7ce
DB
10616 if (BPF_CLASS(insn->code) == BPF_LD &&
10617 (BPF_MODE(insn->code) == BPF_ABS ||
10618 BPF_MODE(insn->code) == BPF_IND)) {
10619 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10620 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10621 verbose(env, "bpf verifier is misconfigured\n");
10622 return -EINVAL;
10623 }
10624
10625 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10626 if (!new_prog)
10627 return -ENOMEM;
10628
10629 delta += cnt - 1;
10630 env->prog = prog = new_prog;
10631 insn = new_prog->insnsi + i + delta;
10632 continue;
10633 }
10634
979d63d5
DB
10635 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10636 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10637 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10638 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10639 struct bpf_insn insn_buf[16];
10640 struct bpf_insn *patch = &insn_buf[0];
10641 bool issrc, isneg;
10642 u32 off_reg;
10643
10644 aux = &env->insn_aux_data[i + delta];
3612af78
DB
10645 if (!aux->alu_state ||
10646 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
10647 continue;
10648
10649 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10650 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10651 BPF_ALU_SANITIZE_SRC;
10652
10653 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10654 if (isneg)
10655 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10656 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10657 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10658 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10659 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10660 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10661 if (issrc) {
10662 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10663 off_reg);
10664 insn->src_reg = BPF_REG_AX;
10665 } else {
10666 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10667 BPF_REG_AX);
10668 }
10669 if (isneg)
10670 insn->code = insn->code == code_add ?
10671 code_sub : code_add;
10672 *patch++ = *insn;
10673 if (issrc && isneg)
10674 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10675 cnt = patch - insn_buf;
10676
10677 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10678 if (!new_prog)
10679 return -ENOMEM;
10680
10681 delta += cnt - 1;
10682 env->prog = prog = new_prog;
10683 insn = new_prog->insnsi + i + delta;
10684 continue;
10685 }
10686
79741b3b
AS
10687 if (insn->code != (BPF_JMP | BPF_CALL))
10688 continue;
cc8b0b92
AS
10689 if (insn->src_reg == BPF_PSEUDO_CALL)
10690 continue;
e245c5c6 10691
79741b3b
AS
10692 if (insn->imm == BPF_FUNC_get_route_realm)
10693 prog->dst_needed = 1;
10694 if (insn->imm == BPF_FUNC_get_prandom_u32)
10695 bpf_user_rnd_init_once();
9802d865
JB
10696 if (insn->imm == BPF_FUNC_override_return)
10697 prog->kprobe_override = 1;
79741b3b 10698 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
10699 /* If we tail call into other programs, we
10700 * cannot make any assumptions since they can
10701 * be replaced dynamically during runtime in
10702 * the program array.
10703 */
10704 prog->cb_access = 1;
e411901c
MF
10705 if (!allow_tail_call_in_subprogs(env))
10706 prog->aux->stack_depth = MAX_BPF_STACK;
10707 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 10708
79741b3b
AS
10709 /* mark bpf_tail_call as different opcode to avoid
10710 * conditional branch in the interpeter for every normal
10711 * call and to prevent accidental JITing by JIT compiler
10712 * that doesn't support bpf_tail_call yet
e245c5c6 10713 */
79741b3b 10714 insn->imm = 0;
71189fa9 10715 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 10716
c93552c4 10717 aux = &env->insn_aux_data[i + delta];
2c78ee89 10718 if (env->bpf_capable && !expect_blinding &&
cc52d914 10719 prog->jit_requested &&
d2e4c1e6
DB
10720 !bpf_map_key_poisoned(aux) &&
10721 !bpf_map_ptr_poisoned(aux) &&
10722 !bpf_map_ptr_unpriv(aux)) {
10723 struct bpf_jit_poke_descriptor desc = {
10724 .reason = BPF_POKE_REASON_TAIL_CALL,
10725 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10726 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 10727 .insn_idx = i + delta,
d2e4c1e6
DB
10728 };
10729
10730 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10731 if (ret < 0) {
10732 verbose(env, "adding tail call poke descriptor failed\n");
10733 return ret;
10734 }
10735
10736 insn->imm = ret + 1;
10737 continue;
10738 }
10739
c93552c4
DB
10740 if (!bpf_map_ptr_unpriv(aux))
10741 continue;
10742
b2157399
AS
10743 /* instead of changing every JIT dealing with tail_call
10744 * emit two extra insns:
10745 * if (index >= max_entries) goto out;
10746 * index &= array->index_mask;
10747 * to avoid out-of-bounds cpu speculation
10748 */
c93552c4 10749 if (bpf_map_ptr_poisoned(aux)) {
40950343 10750 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
10751 return -EINVAL;
10752 }
c93552c4 10753
d2e4c1e6 10754 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
10755 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10756 map_ptr->max_entries, 2);
10757 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10758 container_of(map_ptr,
10759 struct bpf_array,
10760 map)->index_mask);
10761 insn_buf[2] = *insn;
10762 cnt = 3;
10763 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10764 if (!new_prog)
10765 return -ENOMEM;
10766
10767 delta += cnt - 1;
10768 env->prog = prog = new_prog;
10769 insn = new_prog->insnsi + i + delta;
79741b3b
AS
10770 continue;
10771 }
e245c5c6 10772
89c63074 10773 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
10774 * and other inlining handlers are currently limited to 64 bit
10775 * only.
89c63074 10776 */
60b58afc 10777 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
10778 (insn->imm == BPF_FUNC_map_lookup_elem ||
10779 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
10780 insn->imm == BPF_FUNC_map_delete_elem ||
10781 insn->imm == BPF_FUNC_map_push_elem ||
10782 insn->imm == BPF_FUNC_map_pop_elem ||
10783 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
10784 aux = &env->insn_aux_data[i + delta];
10785 if (bpf_map_ptr_poisoned(aux))
10786 goto patch_call_imm;
10787
d2e4c1e6 10788 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
10789 ops = map_ptr->ops;
10790 if (insn->imm == BPF_FUNC_map_lookup_elem &&
10791 ops->map_gen_lookup) {
10792 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10793 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10794 verbose(env, "bpf verifier is misconfigured\n");
10795 return -EINVAL;
10796 }
81ed18ab 10797
09772d92
DB
10798 new_prog = bpf_patch_insn_data(env, i + delta,
10799 insn_buf, cnt);
10800 if (!new_prog)
10801 return -ENOMEM;
81ed18ab 10802
09772d92
DB
10803 delta += cnt - 1;
10804 env->prog = prog = new_prog;
10805 insn = new_prog->insnsi + i + delta;
10806 continue;
10807 }
81ed18ab 10808
09772d92
DB
10809 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10810 (void *(*)(struct bpf_map *map, void *key))NULL));
10811 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10812 (int (*)(struct bpf_map *map, void *key))NULL));
10813 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10814 (int (*)(struct bpf_map *map, void *key, void *value,
10815 u64 flags))NULL));
84430d42
DB
10816 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10817 (int (*)(struct bpf_map *map, void *value,
10818 u64 flags))NULL));
10819 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10820 (int (*)(struct bpf_map *map, void *value))NULL));
10821 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10822 (int (*)(struct bpf_map *map, void *value))NULL));
10823
09772d92
DB
10824 switch (insn->imm) {
10825 case BPF_FUNC_map_lookup_elem:
10826 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10827 __bpf_call_base;
10828 continue;
10829 case BPF_FUNC_map_update_elem:
10830 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10831 __bpf_call_base;
10832 continue;
10833 case BPF_FUNC_map_delete_elem:
10834 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10835 __bpf_call_base;
10836 continue;
84430d42
DB
10837 case BPF_FUNC_map_push_elem:
10838 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10839 __bpf_call_base;
10840 continue;
10841 case BPF_FUNC_map_pop_elem:
10842 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10843 __bpf_call_base;
10844 continue;
10845 case BPF_FUNC_map_peek_elem:
10846 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10847 __bpf_call_base;
10848 continue;
09772d92 10849 }
81ed18ab 10850
09772d92 10851 goto patch_call_imm;
81ed18ab
AS
10852 }
10853
5576b991
MKL
10854 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10855 insn->imm == BPF_FUNC_jiffies64) {
10856 struct bpf_insn ld_jiffies_addr[2] = {
10857 BPF_LD_IMM64(BPF_REG_0,
10858 (unsigned long)&jiffies),
10859 };
10860
10861 insn_buf[0] = ld_jiffies_addr[0];
10862 insn_buf[1] = ld_jiffies_addr[1];
10863 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10864 BPF_REG_0, 0);
10865 cnt = 3;
10866
10867 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10868 cnt);
10869 if (!new_prog)
10870 return -ENOMEM;
10871
10872 delta += cnt - 1;
10873 env->prog = prog = new_prog;
10874 insn = new_prog->insnsi + i + delta;
10875 continue;
10876 }
10877
81ed18ab 10878patch_call_imm:
5e43f899 10879 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
10880 /* all functions that have prototype and verifier allowed
10881 * programs to call them, must be real in-kernel functions
10882 */
10883 if (!fn->func) {
61bd5218
JK
10884 verbose(env,
10885 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
10886 func_id_name(insn->imm), insn->imm);
10887 return -EFAULT;
e245c5c6 10888 }
79741b3b 10889 insn->imm = fn->func - __bpf_call_base;
e245c5c6 10890 }
e245c5c6 10891
d2e4c1e6
DB
10892 /* Since poke tab is now finalized, publish aux to tracker. */
10893 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10894 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10895 if (!map_ptr->ops->map_poke_track ||
10896 !map_ptr->ops->map_poke_untrack ||
10897 !map_ptr->ops->map_poke_run) {
10898 verbose(env, "bpf verifier is misconfigured\n");
10899 return -EINVAL;
10900 }
10901
10902 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10903 if (ret < 0) {
10904 verbose(env, "tracking tail call prog failed\n");
10905 return ret;
10906 }
10907 }
10908
79741b3b
AS
10909 return 0;
10910}
e245c5c6 10911
58e2af8b 10912static void free_states(struct bpf_verifier_env *env)
f1bca824 10913{
58e2af8b 10914 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
10915 int i;
10916
9f4686c4
AS
10917 sl = env->free_list;
10918 while (sl) {
10919 sln = sl->next;
10920 free_verifier_state(&sl->state, false);
10921 kfree(sl);
10922 sl = sln;
10923 }
51c39bb1 10924 env->free_list = NULL;
9f4686c4 10925
f1bca824
AS
10926 if (!env->explored_states)
10927 return;
10928
dc2a4ebc 10929 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
10930 sl = env->explored_states[i];
10931
a8f500af
AS
10932 while (sl) {
10933 sln = sl->next;
10934 free_verifier_state(&sl->state, false);
10935 kfree(sl);
10936 sl = sln;
10937 }
51c39bb1 10938 env->explored_states[i] = NULL;
f1bca824 10939 }
51c39bb1 10940}
f1bca824 10941
51c39bb1
AS
10942/* The verifier is using insn_aux_data[] to store temporary data during
10943 * verification and to store information for passes that run after the
10944 * verification like dead code sanitization. do_check_common() for subprogram N
10945 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10946 * temporary data after do_check_common() finds that subprogram N cannot be
10947 * verified independently. pass_cnt counts the number of times
10948 * do_check_common() was run and insn->aux->seen tells the pass number
10949 * insn_aux_data was touched. These variables are compared to clear temporary
10950 * data from failed pass. For testing and experiments do_check_common() can be
10951 * run multiple times even when prior attempt to verify is unsuccessful.
10952 */
10953static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10954{
10955 struct bpf_insn *insn = env->prog->insnsi;
10956 struct bpf_insn_aux_data *aux;
10957 int i, class;
10958
10959 for (i = 0; i < env->prog->len; i++) {
10960 class = BPF_CLASS(insn[i].code);
10961 if (class != BPF_LDX && class != BPF_STX)
10962 continue;
10963 aux = &env->insn_aux_data[i];
10964 if (aux->seen != env->pass_cnt)
10965 continue;
10966 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10967 }
f1bca824
AS
10968}
10969
51c39bb1
AS
10970static int do_check_common(struct bpf_verifier_env *env, int subprog)
10971{
6f8a57cc 10972 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
10973 struct bpf_verifier_state *state;
10974 struct bpf_reg_state *regs;
10975 int ret, i;
10976
10977 env->prev_linfo = NULL;
10978 env->pass_cnt++;
10979
10980 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10981 if (!state)
10982 return -ENOMEM;
10983 state->curframe = 0;
10984 state->speculative = false;
10985 state->branches = 1;
10986 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10987 if (!state->frame[0]) {
10988 kfree(state);
10989 return -ENOMEM;
10990 }
10991 env->cur_state = state;
10992 init_func_state(env, state->frame[0],
10993 BPF_MAIN_FUNC /* callsite */,
10994 0 /* frameno */,
10995 subprog);
10996
10997 regs = state->frame[state->curframe]->regs;
be8704ff 10998 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
10999 ret = btf_prepare_func_args(env, subprog, regs);
11000 if (ret)
11001 goto out;
11002 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11003 if (regs[i].type == PTR_TO_CTX)
11004 mark_reg_known_zero(env, regs, i);
11005 else if (regs[i].type == SCALAR_VALUE)
11006 mark_reg_unknown(env, regs, i);
11007 }
11008 } else {
11009 /* 1st arg to a function */
11010 regs[BPF_REG_1].type = PTR_TO_CTX;
11011 mark_reg_known_zero(env, regs, BPF_REG_1);
11012 ret = btf_check_func_arg_match(env, subprog, regs);
11013 if (ret == -EFAULT)
11014 /* unlikely verifier bug. abort.
11015 * ret == 0 and ret < 0 are sadly acceptable for
11016 * main() function due to backward compatibility.
11017 * Like socket filter program may be written as:
11018 * int bpf_prog(struct pt_regs *ctx)
11019 * and never dereference that ctx in the program.
11020 * 'struct pt_regs' is a type mismatch for socket
11021 * filter that should be using 'struct __sk_buff'.
11022 */
11023 goto out;
11024 }
11025
11026 ret = do_check(env);
11027out:
f59bbfc2
AS
11028 /* check for NULL is necessary, since cur_state can be freed inside
11029 * do_check() under memory pressure.
11030 */
11031 if (env->cur_state) {
11032 free_verifier_state(env->cur_state, true);
11033 env->cur_state = NULL;
11034 }
6f8a57cc
AN
11035 while (!pop_stack(env, NULL, NULL, false));
11036 if (!ret && pop_log)
11037 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
11038 free_states(env);
11039 if (ret)
11040 /* clean aux data in case subprog was rejected */
11041 sanitize_insn_aux_data(env);
11042 return ret;
11043}
11044
11045/* Verify all global functions in a BPF program one by one based on their BTF.
11046 * All global functions must pass verification. Otherwise the whole program is rejected.
11047 * Consider:
11048 * int bar(int);
11049 * int foo(int f)
11050 * {
11051 * return bar(f);
11052 * }
11053 * int bar(int b)
11054 * {
11055 * ...
11056 * }
11057 * foo() will be verified first for R1=any_scalar_value. During verification it
11058 * will be assumed that bar() already verified successfully and call to bar()
11059 * from foo() will be checked for type match only. Later bar() will be verified
11060 * independently to check that it's safe for R1=any_scalar_value.
11061 */
11062static int do_check_subprogs(struct bpf_verifier_env *env)
11063{
11064 struct bpf_prog_aux *aux = env->prog->aux;
11065 int i, ret;
11066
11067 if (!aux->func_info)
11068 return 0;
11069
11070 for (i = 1; i < env->subprog_cnt; i++) {
11071 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11072 continue;
11073 env->insn_idx = env->subprog_info[i].start;
11074 WARN_ON_ONCE(env->insn_idx == 0);
11075 ret = do_check_common(env, i);
11076 if (ret) {
11077 return ret;
11078 } else if (env->log.level & BPF_LOG_LEVEL) {
11079 verbose(env,
11080 "Func#%d is safe for any args that match its prototype\n",
11081 i);
11082 }
11083 }
11084 return 0;
11085}
11086
11087static int do_check_main(struct bpf_verifier_env *env)
11088{
11089 int ret;
11090
11091 env->insn_idx = 0;
11092 ret = do_check_common(env, 0);
11093 if (!ret)
11094 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11095 return ret;
11096}
11097
11098
06ee7115
AS
11099static void print_verification_stats(struct bpf_verifier_env *env)
11100{
11101 int i;
11102
11103 if (env->log.level & BPF_LOG_STATS) {
11104 verbose(env, "verification time %lld usec\n",
11105 div_u64(env->verification_time, 1000));
11106 verbose(env, "stack depth ");
11107 for (i = 0; i < env->subprog_cnt; i++) {
11108 u32 depth = env->subprog_info[i].stack_depth;
11109
11110 verbose(env, "%d", depth);
11111 if (i + 1 < env->subprog_cnt)
11112 verbose(env, "+");
11113 }
11114 verbose(env, "\n");
11115 }
11116 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11117 "total_states %d peak_states %d mark_read %d\n",
11118 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11119 env->max_states_per_insn, env->total_states,
11120 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
11121}
11122
27ae7997
MKL
11123static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11124{
11125 const struct btf_type *t, *func_proto;
11126 const struct bpf_struct_ops *st_ops;
11127 const struct btf_member *member;
11128 struct bpf_prog *prog = env->prog;
11129 u32 btf_id, member_idx;
11130 const char *mname;
11131
11132 btf_id = prog->aux->attach_btf_id;
11133 st_ops = bpf_struct_ops_find(btf_id);
11134 if (!st_ops) {
11135 verbose(env, "attach_btf_id %u is not a supported struct\n",
11136 btf_id);
11137 return -ENOTSUPP;
11138 }
11139
11140 t = st_ops->type;
11141 member_idx = prog->expected_attach_type;
11142 if (member_idx >= btf_type_vlen(t)) {
11143 verbose(env, "attach to invalid member idx %u of struct %s\n",
11144 member_idx, st_ops->name);
11145 return -EINVAL;
11146 }
11147
11148 member = &btf_type_member(t)[member_idx];
11149 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11150 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11151 NULL);
11152 if (!func_proto) {
11153 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11154 mname, member_idx, st_ops->name);
11155 return -EINVAL;
11156 }
11157
11158 if (st_ops->check_member) {
11159 int err = st_ops->check_member(t, member);
11160
11161 if (err) {
11162 verbose(env, "attach to unsupported member %s of struct %s\n",
11163 mname, st_ops->name);
11164 return err;
11165 }
11166 }
11167
11168 prog->aux->attach_func_proto = func_proto;
11169 prog->aux->attach_func_name = mname;
11170 env->ops = st_ops->verifier_ops;
11171
11172 return 0;
11173}
6ba43b76
KS
11174#define SECURITY_PREFIX "security_"
11175
18644cec 11176static int check_attach_modify_return(struct bpf_prog *prog, unsigned long addr)
6ba43b76 11177{
69191754
KS
11178 if (within_error_injection_list(addr) ||
11179 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
11180 sizeof(SECURITY_PREFIX) - 1))
6ba43b76 11181 return 0;
6ba43b76 11182
6ba43b76
KS
11183 return -EINVAL;
11184}
27ae7997 11185
1e6c62a8
AS
11186/* non exhaustive list of sleepable bpf_lsm_*() functions */
11187BTF_SET_START(btf_sleepable_lsm_hooks)
11188#ifdef CONFIG_BPF_LSM
1e6c62a8 11189BTF_ID(func, bpf_lsm_bprm_committed_creds)
29523c5e
AS
11190#else
11191BTF_ID_UNUSED
1e6c62a8
AS
11192#endif
11193BTF_SET_END(btf_sleepable_lsm_hooks)
11194
11195static int check_sleepable_lsm_hook(u32 btf_id)
11196{
11197 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11198}
11199
11200/* list of non-sleepable functions that are otherwise on
11201 * ALLOW_ERROR_INJECTION list
11202 */
11203BTF_SET_START(btf_non_sleepable_error_inject)
11204/* Three functions below can be called from sleepable and non-sleepable context.
11205 * Assume non-sleepable from bpf safety point of view.
11206 */
11207BTF_ID(func, __add_to_page_cache_locked)
11208BTF_ID(func, should_fail_alloc_page)
11209BTF_ID(func, should_failslab)
11210BTF_SET_END(btf_non_sleepable_error_inject)
11211
11212static int check_non_sleepable_error_inject(u32 btf_id)
11213{
11214 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11215}
11216
38207291
MKL
11217static int check_attach_btf_id(struct bpf_verifier_env *env)
11218{
11219 struct bpf_prog *prog = env->prog;
be8704ff 11220 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
5b92a28a 11221 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
38207291 11222 u32 btf_id = prog->aux->attach_btf_id;
f1b9509c 11223 const char prefix[] = "btf_trace_";
15d83c4d 11224 struct btf_func_model fmodel;
5b92a28a 11225 int ret = 0, subprog = -1, i;
fec56f58 11226 struct bpf_trampoline *tr;
38207291 11227 const struct btf_type *t;
5b92a28a 11228 bool conservative = true;
38207291 11229 const char *tname;
5b92a28a 11230 struct btf *btf;
fec56f58 11231 long addr;
5b92a28a 11232 u64 key;
38207291 11233
1e6c62a8
AS
11234 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11235 prog->type != BPF_PROG_TYPE_LSM) {
11236 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11237 return -EINVAL;
11238 }
11239
27ae7997
MKL
11240 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11241 return check_struct_ops_btf_id(env);
11242
9e4e01df
KS
11243 if (prog->type != BPF_PROG_TYPE_TRACING &&
11244 prog->type != BPF_PROG_TYPE_LSM &&
11245 !prog_extension)
f1b9509c 11246 return 0;
38207291 11247
f1b9509c
AS
11248 if (!btf_id) {
11249 verbose(env, "Tracing programs must provide btf_id\n");
11250 return -EINVAL;
11251 }
5b92a28a
AS
11252 btf = bpf_prog_get_target_btf(prog);
11253 if (!btf) {
11254 verbose(env,
11255 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11256 return -EINVAL;
11257 }
11258 t = btf_type_by_id(btf, btf_id);
f1b9509c
AS
11259 if (!t) {
11260 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
11261 return -EINVAL;
11262 }
5b92a28a 11263 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c
AS
11264 if (!tname) {
11265 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
11266 return -EINVAL;
11267 }
5b92a28a
AS
11268 if (tgt_prog) {
11269 struct bpf_prog_aux *aux = tgt_prog->aux;
11270
11271 for (i = 0; i < aux->func_info_cnt; i++)
11272 if (aux->func_info[i].type_id == btf_id) {
11273 subprog = i;
11274 break;
11275 }
11276 if (subprog == -1) {
11277 verbose(env, "Subprog %s doesn't exist\n", tname);
11278 return -EINVAL;
11279 }
11280 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
11281 if (prog_extension) {
11282 if (conservative) {
11283 verbose(env,
11284 "Cannot replace static functions\n");
11285 return -EINVAL;
11286 }
11287 if (!prog->jit_requested) {
11288 verbose(env,
11289 "Extension programs should be JITed\n");
11290 return -EINVAL;
11291 }
11292 env->ops = bpf_verifier_ops[tgt_prog->type];
03f87c0b 11293 prog->expected_attach_type = tgt_prog->expected_attach_type;
be8704ff
AS
11294 }
11295 if (!tgt_prog->jited) {
11296 verbose(env, "Can attach to only JITed progs\n");
11297 return -EINVAL;
11298 }
11299 if (tgt_prog->type == prog->type) {
11300 /* Cannot fentry/fexit another fentry/fexit program.
11301 * Cannot attach program extension to another extension.
11302 * It's ok to attach fentry/fexit to extension program.
11303 */
11304 verbose(env, "Cannot recursively attach\n");
11305 return -EINVAL;
11306 }
11307 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11308 prog_extension &&
11309 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11310 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11311 /* Program extensions can extend all program types
11312 * except fentry/fexit. The reason is the following.
11313 * The fentry/fexit programs are used for performance
11314 * analysis, stats and can be attached to any program
11315 * type except themselves. When extension program is
11316 * replacing XDP function it is necessary to allow
11317 * performance analysis of all functions. Both original
11318 * XDP program and its program extension. Hence
11319 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11320 * allowed. If extending of fentry/fexit was allowed it
11321 * would be possible to create long call chain
11322 * fentry->extension->fentry->extension beyond
11323 * reasonable stack size. Hence extending fentry is not
11324 * allowed.
11325 */
11326 verbose(env, "Cannot extend fentry/fexit\n");
11327 return -EINVAL;
11328 }
5b92a28a
AS
11329 key = ((u64)aux->id) << 32 | btf_id;
11330 } else {
be8704ff
AS
11331 if (prog_extension) {
11332 verbose(env, "Cannot replace kernel functions\n");
11333 return -EINVAL;
11334 }
5b92a28a
AS
11335 key = btf_id;
11336 }
f1b9509c
AS
11337
11338 switch (prog->expected_attach_type) {
11339 case BPF_TRACE_RAW_TP:
5b92a28a
AS
11340 if (tgt_prog) {
11341 verbose(env,
11342 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11343 return -EINVAL;
11344 }
38207291
MKL
11345 if (!btf_type_is_typedef(t)) {
11346 verbose(env, "attach_btf_id %u is not a typedef\n",
11347 btf_id);
11348 return -EINVAL;
11349 }
f1b9509c 11350 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
38207291
MKL
11351 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
11352 btf_id, tname);
11353 return -EINVAL;
11354 }
11355 tname += sizeof(prefix) - 1;
5b92a28a 11356 t = btf_type_by_id(btf, t->type);
38207291
MKL
11357 if (!btf_type_is_ptr(t))
11358 /* should never happen in valid vmlinux build */
11359 return -EINVAL;
5b92a28a 11360 t = btf_type_by_id(btf, t->type);
38207291
MKL
11361 if (!btf_type_is_func_proto(t))
11362 /* should never happen in valid vmlinux build */
11363 return -EINVAL;
11364
11365 /* remember two read only pointers that are valid for
11366 * the life time of the kernel
11367 */
11368 prog->aux->attach_func_name = tname;
11369 prog->aux->attach_func_proto = t;
11370 prog->aux->attach_btf_trace = true;
f1b9509c 11371 return 0;
15d83c4d
YS
11372 case BPF_TRACE_ITER:
11373 if (!btf_type_is_func(t)) {
11374 verbose(env, "attach_btf_id %u is not a function\n",
11375 btf_id);
11376 return -EINVAL;
11377 }
11378 t = btf_type_by_id(btf, t->type);
11379 if (!btf_type_is_func_proto(t))
11380 return -EINVAL;
11381 prog->aux->attach_func_name = tname;
11382 prog->aux->attach_func_proto = t;
11383 if (!bpf_iter_prog_supported(prog))
11384 return -EINVAL;
11385 ret = btf_distill_func_proto(&env->log, btf, t,
11386 tname, &fmodel);
11387 return ret;
be8704ff
AS
11388 default:
11389 if (!prog_extension)
11390 return -EINVAL;
df561f66 11391 fallthrough;
ae240823 11392 case BPF_MODIFY_RETURN:
9e4e01df 11393 case BPF_LSM_MAC:
fec56f58
AS
11394 case BPF_TRACE_FENTRY:
11395 case BPF_TRACE_FEXIT:
9e4e01df
KS
11396 prog->aux->attach_func_name = tname;
11397 if (prog->type == BPF_PROG_TYPE_LSM) {
11398 ret = bpf_lsm_verify_prog(&env->log, prog);
11399 if (ret < 0)
11400 return ret;
11401 }
11402
fec56f58
AS
11403 if (!btf_type_is_func(t)) {
11404 verbose(env, "attach_btf_id %u is not a function\n",
11405 btf_id);
11406 return -EINVAL;
11407 }
be8704ff
AS
11408 if (prog_extension &&
11409 btf_check_type_match(env, prog, btf, t))
11410 return -EINVAL;
5b92a28a 11411 t = btf_type_by_id(btf, t->type);
fec56f58
AS
11412 if (!btf_type_is_func_proto(t))
11413 return -EINVAL;
5b92a28a 11414 tr = bpf_trampoline_lookup(key);
fec56f58
AS
11415 if (!tr)
11416 return -ENOMEM;
5b92a28a 11417 /* t is either vmlinux type or another program's type */
fec56f58
AS
11418 prog->aux->attach_func_proto = t;
11419 mutex_lock(&tr->mutex);
11420 if (tr->func.addr) {
11421 prog->aux->trampoline = tr;
11422 goto out;
11423 }
5b92a28a
AS
11424 if (tgt_prog && conservative) {
11425 prog->aux->attach_func_proto = NULL;
11426 t = NULL;
11427 }
11428 ret = btf_distill_func_proto(&env->log, btf, t,
fec56f58
AS
11429 tname, &tr->func.model);
11430 if (ret < 0)
11431 goto out;
5b92a28a 11432 if (tgt_prog) {
e9eeec58
YS
11433 if (subprog == 0)
11434 addr = (long) tgt_prog->bpf_func;
11435 else
11436 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
11437 } else {
11438 addr = kallsyms_lookup_name(tname);
11439 if (!addr) {
11440 verbose(env,
11441 "The address of function %s cannot be found\n",
11442 tname);
11443 ret = -ENOENT;
11444 goto out;
11445 }
fec56f58 11446 }
18644cec 11447
1e6c62a8
AS
11448 if (prog->aux->sleepable) {
11449 ret = -EINVAL;
11450 switch (prog->type) {
11451 case BPF_PROG_TYPE_TRACING:
11452 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11453 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11454 */
11455 if (!check_non_sleepable_error_inject(btf_id) &&
11456 within_error_injection_list(addr))
11457 ret = 0;
11458 break;
11459 case BPF_PROG_TYPE_LSM:
11460 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11461 * Only some of them are sleepable.
11462 */
11463 if (check_sleepable_lsm_hook(btf_id))
11464 ret = 0;
11465 break;
11466 default:
11467 break;
11468 }
11469 if (ret)
11470 verbose(env, "%s is not sleepable\n",
11471 prog->aux->attach_func_name);
11472 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
18644cec
AS
11473 ret = check_attach_modify_return(prog, addr);
11474 if (ret)
11475 verbose(env, "%s() is not modifiable\n",
11476 prog->aux->attach_func_name);
11477 }
18644cec
AS
11478 if (ret)
11479 goto out;
fec56f58
AS
11480 tr->func.addr = (void *)addr;
11481 prog->aux->trampoline = tr;
11482out:
11483 mutex_unlock(&tr->mutex);
11484 if (ret)
11485 bpf_trampoline_put(tr);
11486 return ret;
38207291 11487 }
38207291
MKL
11488}
11489
838e9690
YS
11490int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11491 union bpf_attr __user *uattr)
51580e79 11492{
06ee7115 11493 u64 start_time = ktime_get_ns();
58e2af8b 11494 struct bpf_verifier_env *env;
b9193c1b 11495 struct bpf_verifier_log *log;
9e4c24e7 11496 int i, len, ret = -EINVAL;
e2ae4ca2 11497 bool is_priv;
51580e79 11498
eba0c929
AB
11499 /* no program is valid */
11500 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11501 return -EINVAL;
11502
58e2af8b 11503 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
11504 * allocate/free it every time bpf_check() is called
11505 */
58e2af8b 11506 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
11507 if (!env)
11508 return -ENOMEM;
61bd5218 11509 log = &env->log;
cbd35700 11510
9e4c24e7 11511 len = (*prog)->len;
fad953ce 11512 env->insn_aux_data =
9e4c24e7 11513 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
11514 ret = -ENOMEM;
11515 if (!env->insn_aux_data)
11516 goto err_free_env;
9e4c24e7
JK
11517 for (i = 0; i < len; i++)
11518 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 11519 env->prog = *prog;
00176a34 11520 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 11521 is_priv = bpf_capable();
0246e64d 11522
8580ac94
AS
11523 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11524 mutex_lock(&bpf_verifier_lock);
11525 if (!btf_vmlinux)
11526 btf_vmlinux = btf_parse_vmlinux();
11527 mutex_unlock(&bpf_verifier_lock);
11528 }
11529
cbd35700 11530 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
11531 if (!is_priv)
11532 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
11533
11534 if (attr->log_level || attr->log_buf || attr->log_size) {
11535 /* user requested verbose verifier output
11536 * and supplied buffer to store the verification trace
11537 */
e7bf8249
JK
11538 log->level = attr->log_level;
11539 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11540 log->len_total = attr->log_size;
cbd35700
AS
11541
11542 ret = -EINVAL;
e7bf8249 11543 /* log attributes have to be sane */
7a9f5c65 11544 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 11545 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 11546 goto err_unlock;
cbd35700 11547 }
1ad2f583 11548
8580ac94
AS
11549 if (IS_ERR(btf_vmlinux)) {
11550 /* Either gcc or pahole or kernel are broken. */
11551 verbose(env, "in-kernel BTF is malformed\n");
11552 ret = PTR_ERR(btf_vmlinux);
38207291 11553 goto skip_full_check;
8580ac94
AS
11554 }
11555
1ad2f583
DB
11556 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11557 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 11558 env->strict_alignment = true;
e9ee9efc
DM
11559 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11560 env->strict_alignment = false;
cbd35700 11561
2c78ee89 11562 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
41c48f3a 11563 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
11564 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11565 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11566 env->bpf_capable = bpf_capable();
e2ae4ca2 11567
10d274e8
AS
11568 if (is_priv)
11569 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11570
f4e3ec0d
JK
11571 ret = replace_map_fd_with_map_ptr(env);
11572 if (ret < 0)
11573 goto skip_full_check;
11574
cae1927c 11575 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 11576 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 11577 if (ret)
f4e3ec0d 11578 goto skip_full_check;
ab3f0063
JK
11579 }
11580
dc2a4ebc 11581 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 11582 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
11583 GFP_USER);
11584 ret = -ENOMEM;
11585 if (!env->explored_states)
11586 goto skip_full_check;
11587
d9762e84 11588 ret = check_subprogs(env);
475fb78f
AS
11589 if (ret < 0)
11590 goto skip_full_check;
11591
c454a46b 11592 ret = check_btf_info(env, attr, uattr);
838e9690
YS
11593 if (ret < 0)
11594 goto skip_full_check;
11595
be8704ff
AS
11596 ret = check_attach_btf_id(env);
11597 if (ret)
11598 goto skip_full_check;
11599
d9762e84
MKL
11600 ret = check_cfg(env);
11601 if (ret < 0)
11602 goto skip_full_check;
11603
51c39bb1
AS
11604 ret = do_check_subprogs(env);
11605 ret = ret ?: do_check_main(env);
cbd35700 11606
c941ce9c
QM
11607 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11608 ret = bpf_prog_offload_finalize(env);
11609
0246e64d 11610skip_full_check:
51c39bb1 11611 kvfree(env->explored_states);
0246e64d 11612
c131187d 11613 if (ret == 0)
9b38c405 11614 ret = check_max_stack_depth(env);
c131187d 11615
9b38c405 11616 /* instruction rewrites happen after this point */
e2ae4ca2
JK
11617 if (is_priv) {
11618 if (ret == 0)
11619 opt_hard_wire_dead_code_branches(env);
52875a04
JK
11620 if (ret == 0)
11621 ret = opt_remove_dead_code(env);
a1b14abc
JK
11622 if (ret == 0)
11623 ret = opt_remove_nops(env);
52875a04
JK
11624 } else {
11625 if (ret == 0)
11626 sanitize_dead_code(env);
e2ae4ca2
JK
11627 }
11628
9bac3d6d
AS
11629 if (ret == 0)
11630 /* program is valid, convert *(u32*)(ctx + off) accesses */
11631 ret = convert_ctx_accesses(env);
11632
e245c5c6 11633 if (ret == 0)
79741b3b 11634 ret = fixup_bpf_calls(env);
e245c5c6 11635
a4b1d3c1
JW
11636 /* do 32-bit optimization after insn patching has done so those patched
11637 * insns could be handled correctly.
11638 */
d6c2308c
JW
11639 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11640 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11641 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11642 : false;
a4b1d3c1
JW
11643 }
11644
1ea47e01
AS
11645 if (ret == 0)
11646 ret = fixup_call_args(env);
11647
06ee7115
AS
11648 env->verification_time = ktime_get_ns() - start_time;
11649 print_verification_stats(env);
11650
a2a7d570 11651 if (log->level && bpf_verifier_log_full(log))
cbd35700 11652 ret = -ENOSPC;
a2a7d570 11653 if (log->level && !log->ubuf) {
cbd35700 11654 ret = -EFAULT;
a2a7d570 11655 goto err_release_maps;
cbd35700
AS
11656 }
11657
0246e64d
AS
11658 if (ret == 0 && env->used_map_cnt) {
11659 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
11660 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11661 sizeof(env->used_maps[0]),
11662 GFP_KERNEL);
0246e64d 11663
9bac3d6d 11664 if (!env->prog->aux->used_maps) {
0246e64d 11665 ret = -ENOMEM;
a2a7d570 11666 goto err_release_maps;
0246e64d
AS
11667 }
11668
9bac3d6d 11669 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 11670 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 11671 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
11672
11673 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11674 * bpf_ld_imm64 instructions
11675 */
11676 convert_pseudo_ld_imm64(env);
11677 }
cbd35700 11678
ba64e7d8
YS
11679 if (ret == 0)
11680 adjust_btf_func(env);
11681
a2a7d570 11682err_release_maps:
9bac3d6d 11683 if (!env->prog->aux->used_maps)
0246e64d 11684 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 11685 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
11686 */
11687 release_maps(env);
03f87c0b
THJ
11688
11689 /* extension progs temporarily inherit the attach_type of their targets
11690 for verification purposes, so set it back to zero before returning
11691 */
11692 if (env->prog->type == BPF_PROG_TYPE_EXT)
11693 env->prog->expected_attach_type = 0;
11694
9bac3d6d 11695 *prog = env->prog;
3df126f3 11696err_unlock:
45a73c17
AS
11697 if (!is_priv)
11698 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
11699 vfree(env->insn_aux_data);
11700err_free_env:
11701 kfree(env);
51580e79
AS
11702 return ret;
11703}