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