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