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