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