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