]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - kernel/bpf/verifier.c
bpf: allow for tailcalls in BPF subprograms for x64 JIT
[mirror_ubuntu-hirsute-kernel.git] / kernel / bpf / verifier.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
51580e79 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 3 * Copyright (c) 2016 Facebook
fd978bf7 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79 5 */
838e9690 6#include <uapi/linux/btf.h>
51580e79
AS
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
838e9690 11#include <linux/btf.h>
58e2af8b 12#include <linux/bpf_verifier.h>
51580e79
AS
13#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
ebb676da 17#include <linux/stringify.h>
cc8b0b92
AS
18#include <linux/bsearch.h>
19#include <linux/sort.h>
c195651e 20#include <linux/perf_event.h>
d9762e84 21#include <linux/ctype.h>
6ba43b76 22#include <linux/error-injection.h>
9e4e01df 23#include <linux/bpf_lsm.h>
1e6c62a8 24#include <linux/btf_ids.h>
51580e79 25
f4ac7e0b
JK
26#include "disasm.h"
27
00176a34 28static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 29#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
30 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 32#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
33#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
f2e10bff 36#undef BPF_LINK_TYPE
00176a34
JK
37};
38
51580e79
AS
39/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
eba38a96 51 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
f1174f77 79 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 80 * means the register has some value, but it's not a valid pointer.
f1174f77 81 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
82 *
83 * When verifier sees load or store instructions the type of base register
c64b7983
JS
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
51580e79
AS
86 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
162 */
163
17a52670 164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 165struct bpf_verifier_stack_elem {
17a52670
AS
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
58e2af8b 170 struct bpf_verifier_state st;
17a52670
AS
171 int insn_idx;
172 int prev_insn_idx;
58e2af8b 173 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
cbd35700
AS
176};
177
b285fcb7 178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 179#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 180
d2e4c1e6
DB
181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
c93552c4
DB
184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
d2e4c1e6 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 229}
fad73a1a 230
33ff9823
DB
231struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
435faee1 233 bool raw_mode;
36bbef52 234 bool pkt_access;
435faee1
DB
235 int regno;
236 int access_size;
457f4436 237 int mem_size;
10060503 238 u64 msize_max_value;
1b986589 239 int ref_obj_id;
d83525ca 240 int func_id;
a7658e1a 241 u32 btf_id;
33ff9823
DB
242};
243
8580ac94
AS
244struct btf *btf_vmlinux;
245
cbd35700
AS
246static DEFINE_MUTEX(bpf_verifier_lock);
247
d9762e84
MKL
248static const struct bpf_line_info *
249find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
250{
251 const struct bpf_line_info *linfo;
252 const struct bpf_prog *prog;
253 u32 i, nr_linfo;
254
255 prog = env->prog;
256 nr_linfo = prog->aux->nr_linfo;
257
258 if (!nr_linfo || insn_off >= prog->len)
259 return NULL;
260
261 linfo = prog->aux->linfo;
262 for (i = 1; i < nr_linfo; i++)
263 if (insn_off < linfo[i].insn_off)
264 break;
265
266 return &linfo[i - 1];
267}
268
77d2e05a
MKL
269void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
270 va_list args)
cbd35700 271{
a2a7d570 272 unsigned int n;
cbd35700 273
a2a7d570 274 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
275
276 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
277 "verifier log line truncated - local buffer too short\n");
278
279 n = min(log->len_total - log->len_used - 1, n);
280 log->kbuf[n] = '\0';
281
8580ac94
AS
282 if (log->level == BPF_LOG_KERNEL) {
283 pr_err("BPF:%s\n", log->kbuf);
284 return;
285 }
a2a7d570
JK
286 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
287 log->len_used += n;
288 else
289 log->ubuf = NULL;
cbd35700 290}
abe08840 291
6f8a57cc
AN
292static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
293{
294 char zero = 0;
295
296 if (!bpf_verifier_log_needed(log))
297 return;
298
299 log->len_used = new_pos;
300 if (put_user(zero, log->ubuf + new_pos))
301 log->ubuf = NULL;
302}
303
abe08840
JO
304/* log_level controls verbosity level of eBPF verifier.
305 * bpf_verifier_log_write() is used to dump the verification trace to the log,
306 * so the user can figure out what's wrong with the program
430e68d1 307 */
abe08840
JO
308__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
309 const char *fmt, ...)
310{
311 va_list args;
312
77d2e05a
MKL
313 if (!bpf_verifier_log_needed(&env->log))
314 return;
315
abe08840 316 va_start(args, fmt);
77d2e05a 317 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
318 va_end(args);
319}
320EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
321
322__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
323{
77d2e05a 324 struct bpf_verifier_env *env = private_data;
abe08840
JO
325 va_list args;
326
77d2e05a
MKL
327 if (!bpf_verifier_log_needed(&env->log))
328 return;
329
abe08840 330 va_start(args, fmt);
77d2e05a 331 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
332 va_end(args);
333}
cbd35700 334
9e15db66
AS
335__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
336 const char *fmt, ...)
337{
338 va_list args;
339
340 if (!bpf_verifier_log_needed(log))
341 return;
342
343 va_start(args, fmt);
344 bpf_verifier_vlog(log, fmt, args);
345 va_end(args);
346}
347
d9762e84
MKL
348static const char *ltrim(const char *s)
349{
350 while (isspace(*s))
351 s++;
352
353 return s;
354}
355
356__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
357 u32 insn_off,
358 const char *prefix_fmt, ...)
359{
360 const struct bpf_line_info *linfo;
361
362 if (!bpf_verifier_log_needed(&env->log))
363 return;
364
365 linfo = find_linfo(env, insn_off);
366 if (!linfo || linfo == env->prev_linfo)
367 return;
368
369 if (prefix_fmt) {
370 va_list args;
371
372 va_start(args, prefix_fmt);
373 bpf_verifier_vlog(&env->log, prefix_fmt, args);
374 va_end(args);
375 }
376
377 verbose(env, "%s\n",
378 ltrim(btf_name_by_offset(env->prog->aux->btf,
379 linfo->line_off)));
380
381 env->prev_linfo = linfo;
382}
383
de8f3a83
DB
384static bool type_is_pkt_pointer(enum bpf_reg_type type)
385{
386 return type == PTR_TO_PACKET ||
387 type == PTR_TO_PACKET_META;
388}
389
46f8bc92
MKL
390static bool type_is_sk_pointer(enum bpf_reg_type type)
391{
392 return type == PTR_TO_SOCKET ||
655a51e5 393 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
394 type == PTR_TO_TCP_SOCK ||
395 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
396}
397
cac616db
JF
398static bool reg_type_not_null(enum bpf_reg_type type)
399{
400 return type == PTR_TO_SOCKET ||
401 type == PTR_TO_TCP_SOCK ||
402 type == PTR_TO_MAP_VALUE ||
01c66c48 403 type == PTR_TO_SOCK_COMMON;
cac616db
JF
404}
405
840b9615
JS
406static bool reg_type_may_be_null(enum bpf_reg_type type)
407{
fd978bf7 408 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 409 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 410 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 411 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 412 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
413 type == PTR_TO_MEM_OR_NULL ||
414 type == PTR_TO_RDONLY_BUF_OR_NULL ||
415 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
416}
417
d83525ca
AS
418static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
419{
420 return reg->type == PTR_TO_MAP_VALUE &&
421 map_value_has_spin_lock(reg->map_ptr);
422}
423
cba368c1
MKL
424static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
425{
426 return type == PTR_TO_SOCKET ||
427 type == PTR_TO_SOCKET_OR_NULL ||
428 type == PTR_TO_TCP_SOCK ||
457f4436
AN
429 type == PTR_TO_TCP_SOCK_OR_NULL ||
430 type == PTR_TO_MEM ||
431 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
432}
433
1b986589 434static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 435{
1b986589 436 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
437}
438
439/* Determine whether the function releases some resources allocated by another
440 * function call. The first reference type argument will be assumed to be
441 * released by release_reference().
442 */
443static bool is_release_function(enum bpf_func_id func_id)
444{
457f4436
AN
445 return func_id == BPF_FUNC_sk_release ||
446 func_id == BPF_FUNC_ringbuf_submit ||
447 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
448}
449
64d85290 450static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
451{
452 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 453 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 454 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
455 func_id == BPF_FUNC_map_lookup_elem ||
456 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
457}
458
459static bool is_acquire_function(enum bpf_func_id func_id,
460 const struct bpf_map *map)
461{
462 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
463
464 if (func_id == BPF_FUNC_sk_lookup_tcp ||
465 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
466 func_id == BPF_FUNC_skc_lookup_tcp ||
467 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
468 return true;
469
470 if (func_id == BPF_FUNC_map_lookup_elem &&
471 (map_type == BPF_MAP_TYPE_SOCKMAP ||
472 map_type == BPF_MAP_TYPE_SOCKHASH))
473 return true;
474
475 return false;
46f8bc92
MKL
476}
477
1b986589
MKL
478static bool is_ptr_cast_function(enum bpf_func_id func_id)
479{
480 return func_id == BPF_FUNC_tcp_sock ||
481 func_id == BPF_FUNC_sk_fullsock;
482}
483
17a52670
AS
484/* string representation of 'enum bpf_reg_type' */
485static const char * const reg_type_str[] = {
486 [NOT_INIT] = "?",
f1174f77 487 [SCALAR_VALUE] = "inv",
17a52670
AS
488 [PTR_TO_CTX] = "ctx",
489 [CONST_PTR_TO_MAP] = "map_ptr",
490 [PTR_TO_MAP_VALUE] = "map_value",
491 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 492 [PTR_TO_STACK] = "fp",
969bf05e 493 [PTR_TO_PACKET] = "pkt",
de8f3a83 494 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 495 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 496 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
497 [PTR_TO_SOCKET] = "sock",
498 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
499 [PTR_TO_SOCK_COMMON] = "sock_common",
500 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
501 [PTR_TO_TCP_SOCK] = "tcp_sock",
502 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 503 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 504 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 505 [PTR_TO_BTF_ID] = "ptr_",
b121b341 506 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
457f4436
AN
507 [PTR_TO_MEM] = "mem",
508 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
509 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
510 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
511 [PTR_TO_RDWR_BUF] = "rdwr_buf",
512 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
17a52670
AS
513};
514
8efea21d
EC
515static char slot_type_char[] = {
516 [STACK_INVALID] = '?',
517 [STACK_SPILL] = 'r',
518 [STACK_MISC] = 'm',
519 [STACK_ZERO] = '0',
520};
521
4e92024a
AS
522static void print_liveness(struct bpf_verifier_env *env,
523 enum bpf_reg_liveness live)
524{
9242b5f5 525 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
526 verbose(env, "_");
527 if (live & REG_LIVE_READ)
528 verbose(env, "r");
529 if (live & REG_LIVE_WRITTEN)
530 verbose(env, "w");
9242b5f5
AS
531 if (live & REG_LIVE_DONE)
532 verbose(env, "D");
4e92024a
AS
533}
534
f4d7e40a
AS
535static struct bpf_func_state *func(struct bpf_verifier_env *env,
536 const struct bpf_reg_state *reg)
537{
538 struct bpf_verifier_state *cur = env->cur_state;
539
540 return cur->frame[reg->frameno];
541}
542
9e15db66
AS
543const char *kernel_type_name(u32 id)
544{
545 return btf_name_by_offset(btf_vmlinux,
546 btf_type_by_id(btf_vmlinux, id)->name_off);
547}
548
61bd5218 549static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 550 const struct bpf_func_state *state)
17a52670 551{
f4d7e40a 552 const struct bpf_reg_state *reg;
17a52670
AS
553 enum bpf_reg_type t;
554 int i;
555
f4d7e40a
AS
556 if (state->frameno)
557 verbose(env, " frame%d:", state->frameno);
17a52670 558 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
559 reg = &state->regs[i];
560 t = reg->type;
17a52670
AS
561 if (t == NOT_INIT)
562 continue;
4e92024a
AS
563 verbose(env, " R%d", i);
564 print_liveness(env, reg->live);
565 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
566 if (t == SCALAR_VALUE && reg->precise)
567 verbose(env, "P");
f1174f77
EC
568 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
569 tnum_is_const(reg->var_off)) {
570 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 571 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 572 } else {
b121b341 573 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
9e15db66 574 verbose(env, "%s", kernel_type_name(reg->btf_id));
cba368c1
MKL
575 verbose(env, "(id=%d", reg->id);
576 if (reg_type_may_be_refcounted_or_null(t))
577 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 578 if (t != SCALAR_VALUE)
61bd5218 579 verbose(env, ",off=%d", reg->off);
de8f3a83 580 if (type_is_pkt_pointer(t))
61bd5218 581 verbose(env, ",r=%d", reg->range);
f1174f77
EC
582 else if (t == CONST_PTR_TO_MAP ||
583 t == PTR_TO_MAP_VALUE ||
584 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 585 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
586 reg->map_ptr->key_size,
587 reg->map_ptr->value_size);
7d1238f2
EC
588 if (tnum_is_const(reg->var_off)) {
589 /* Typically an immediate SCALAR_VALUE, but
590 * could be a pointer whose offset is too big
591 * for reg->off
592 */
61bd5218 593 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
594 } else {
595 if (reg->smin_value != reg->umin_value &&
596 reg->smin_value != S64_MIN)
61bd5218 597 verbose(env, ",smin_value=%lld",
7d1238f2
EC
598 (long long)reg->smin_value);
599 if (reg->smax_value != reg->umax_value &&
600 reg->smax_value != S64_MAX)
61bd5218 601 verbose(env, ",smax_value=%lld",
7d1238f2
EC
602 (long long)reg->smax_value);
603 if (reg->umin_value != 0)
61bd5218 604 verbose(env, ",umin_value=%llu",
7d1238f2
EC
605 (unsigned long long)reg->umin_value);
606 if (reg->umax_value != U64_MAX)
61bd5218 607 verbose(env, ",umax_value=%llu",
7d1238f2
EC
608 (unsigned long long)reg->umax_value);
609 if (!tnum_is_unknown(reg->var_off)) {
610 char tn_buf[48];
f1174f77 611
7d1238f2 612 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 613 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 614 }
3f50f132
JF
615 if (reg->s32_min_value != reg->smin_value &&
616 reg->s32_min_value != S32_MIN)
617 verbose(env, ",s32_min_value=%d",
618 (int)(reg->s32_min_value));
619 if (reg->s32_max_value != reg->smax_value &&
620 reg->s32_max_value != S32_MAX)
621 verbose(env, ",s32_max_value=%d",
622 (int)(reg->s32_max_value));
623 if (reg->u32_min_value != reg->umin_value &&
624 reg->u32_min_value != U32_MIN)
625 verbose(env, ",u32_min_value=%d",
626 (int)(reg->u32_min_value));
627 if (reg->u32_max_value != reg->umax_value &&
628 reg->u32_max_value != U32_MAX)
629 verbose(env, ",u32_max_value=%d",
630 (int)(reg->u32_max_value));
f1174f77 631 }
61bd5218 632 verbose(env, ")");
f1174f77 633 }
17a52670 634 }
638f5b90 635 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
636 char types_buf[BPF_REG_SIZE + 1];
637 bool valid = false;
638 int j;
639
640 for (j = 0; j < BPF_REG_SIZE; j++) {
641 if (state->stack[i].slot_type[j] != STACK_INVALID)
642 valid = true;
643 types_buf[j] = slot_type_char[
644 state->stack[i].slot_type[j]];
645 }
646 types_buf[BPF_REG_SIZE] = 0;
647 if (!valid)
648 continue;
649 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
650 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
651 if (state->stack[i].slot_type[0] == STACK_SPILL) {
652 reg = &state->stack[i].spilled_ptr;
653 t = reg->type;
654 verbose(env, "=%s", reg_type_str[t]);
655 if (t == SCALAR_VALUE && reg->precise)
656 verbose(env, "P");
657 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
658 verbose(env, "%lld", reg->var_off.value + reg->off);
659 } else {
8efea21d 660 verbose(env, "=%s", types_buf);
b5dc0163 661 }
17a52670 662 }
fd978bf7
JS
663 if (state->acquired_refs && state->refs[0].id) {
664 verbose(env, " refs=%d", state->refs[0].id);
665 for (i = 1; i < state->acquired_refs; i++)
666 if (state->refs[i].id)
667 verbose(env, ",%d", state->refs[i].id);
668 }
61bd5218 669 verbose(env, "\n");
17a52670
AS
670}
671
84dbf350
JS
672#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
673static int copy_##NAME##_state(struct bpf_func_state *dst, \
674 const struct bpf_func_state *src) \
675{ \
676 if (!src->FIELD) \
677 return 0; \
678 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
679 /* internal bug, make state invalid to reject the program */ \
680 memset(dst, 0, sizeof(*dst)); \
681 return -EFAULT; \
682 } \
683 memcpy(dst->FIELD, src->FIELD, \
684 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
685 return 0; \
638f5b90 686}
fd978bf7
JS
687/* copy_reference_state() */
688COPY_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
689/* copy_stack_state() */
690COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
691#undef COPY_STATE_FN
692
693#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
694static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
695 bool copy_old) \
696{ \
697 u32 old_size = state->COUNT; \
698 struct bpf_##NAME##_state *new_##FIELD; \
699 int slot = size / SIZE; \
700 \
701 if (size <= old_size || !size) { \
702 if (copy_old) \
703 return 0; \
704 state->COUNT = slot * SIZE; \
705 if (!size && old_size) { \
706 kfree(state->FIELD); \
707 state->FIELD = NULL; \
708 } \
709 return 0; \
710 } \
711 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
712 GFP_KERNEL); \
713 if (!new_##FIELD) \
714 return -ENOMEM; \
715 if (copy_old) { \
716 if (state->FIELD) \
717 memcpy(new_##FIELD, state->FIELD, \
718 sizeof(*new_##FIELD) * (old_size / SIZE)); \
719 memset(new_##FIELD + old_size / SIZE, 0, \
720 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
721 } \
722 state->COUNT = slot * SIZE; \
723 kfree(state->FIELD); \
724 state->FIELD = new_##FIELD; \
725 return 0; \
726}
fd978bf7
JS
727/* realloc_reference_state() */
728REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
84dbf350
JS
729/* realloc_stack_state() */
730REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
731#undef REALLOC_STATE_FN
638f5b90
AS
732
733/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
734 * make it consume minimal amount of memory. check_stack_write() access from
f4d7e40a 735 * the program calls into realloc_func_state() to grow the stack size.
84dbf350
JS
736 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
737 * which realloc_stack_state() copies over. It points to previous
738 * bpf_verifier_state which is never reallocated.
638f5b90 739 */
fd978bf7
JS
740static int realloc_func_state(struct bpf_func_state *state, int stack_size,
741 int refs_size, bool copy_old)
638f5b90 742{
fd978bf7
JS
743 int err = realloc_reference_state(state, refs_size, copy_old);
744 if (err)
745 return err;
746 return realloc_stack_state(state, stack_size, copy_old);
747}
748
749/* Acquire a pointer id from the env and update the state->refs to include
750 * this new pointer reference.
751 * On success, returns a valid pointer id to associate with the register
752 * On failure, returns a negative errno.
638f5b90 753 */
fd978bf7 754static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 755{
fd978bf7
JS
756 struct bpf_func_state *state = cur_func(env);
757 int new_ofs = state->acquired_refs;
758 int id, err;
759
760 err = realloc_reference_state(state, state->acquired_refs + 1, true);
761 if (err)
762 return err;
763 id = ++env->id_gen;
764 state->refs[new_ofs].id = id;
765 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 766
fd978bf7
JS
767 return id;
768}
769
770/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 771static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
772{
773 int i, last_idx;
774
fd978bf7
JS
775 last_idx = state->acquired_refs - 1;
776 for (i = 0; i < state->acquired_refs; i++) {
777 if (state->refs[i].id == ptr_id) {
778 if (last_idx && i != last_idx)
779 memcpy(&state->refs[i], &state->refs[last_idx],
780 sizeof(*state->refs));
781 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
782 state->acquired_refs--;
638f5b90 783 return 0;
638f5b90 784 }
638f5b90 785 }
46f8bc92 786 return -EINVAL;
fd978bf7
JS
787}
788
789static int transfer_reference_state(struct bpf_func_state *dst,
790 struct bpf_func_state *src)
791{
792 int err = realloc_reference_state(dst, src->acquired_refs, false);
793 if (err)
794 return err;
795 err = copy_reference_state(dst, src);
796 if (err)
797 return err;
638f5b90
AS
798 return 0;
799}
800
f4d7e40a
AS
801static void free_func_state(struct bpf_func_state *state)
802{
5896351e
AS
803 if (!state)
804 return;
fd978bf7 805 kfree(state->refs);
f4d7e40a
AS
806 kfree(state->stack);
807 kfree(state);
808}
809
b5dc0163
AS
810static void clear_jmp_history(struct bpf_verifier_state *state)
811{
812 kfree(state->jmp_history);
813 state->jmp_history = NULL;
814 state->jmp_history_cnt = 0;
815}
816
1969db47
AS
817static void free_verifier_state(struct bpf_verifier_state *state,
818 bool free_self)
638f5b90 819{
f4d7e40a
AS
820 int i;
821
822 for (i = 0; i <= state->curframe; i++) {
823 free_func_state(state->frame[i]);
824 state->frame[i] = NULL;
825 }
b5dc0163 826 clear_jmp_history(state);
1969db47
AS
827 if (free_self)
828 kfree(state);
638f5b90
AS
829}
830
831/* copy verifier state from src to dst growing dst stack space
832 * when necessary to accommodate larger src stack
833 */
f4d7e40a
AS
834static int copy_func_state(struct bpf_func_state *dst,
835 const struct bpf_func_state *src)
638f5b90
AS
836{
837 int err;
838
fd978bf7
JS
839 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
840 false);
841 if (err)
842 return err;
843 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
844 err = copy_reference_state(dst, src);
638f5b90
AS
845 if (err)
846 return err;
638f5b90
AS
847 return copy_stack_state(dst, src);
848}
849
f4d7e40a
AS
850static int copy_verifier_state(struct bpf_verifier_state *dst_state,
851 const struct bpf_verifier_state *src)
852{
853 struct bpf_func_state *dst;
b5dc0163 854 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
f4d7e40a
AS
855 int i, err;
856
b5dc0163
AS
857 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
858 kfree(dst_state->jmp_history);
859 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
860 if (!dst_state->jmp_history)
861 return -ENOMEM;
862 }
863 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
864 dst_state->jmp_history_cnt = src->jmp_history_cnt;
865
f4d7e40a
AS
866 /* if dst has more stack frames then src frame, free them */
867 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
868 free_func_state(dst_state->frame[i]);
869 dst_state->frame[i] = NULL;
870 }
979d63d5 871 dst_state->speculative = src->speculative;
f4d7e40a 872 dst_state->curframe = src->curframe;
d83525ca 873 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
874 dst_state->branches = src->branches;
875 dst_state->parent = src->parent;
b5dc0163
AS
876 dst_state->first_insn_idx = src->first_insn_idx;
877 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
878 for (i = 0; i <= src->curframe; i++) {
879 dst = dst_state->frame[i];
880 if (!dst) {
881 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
882 if (!dst)
883 return -ENOMEM;
884 dst_state->frame[i] = dst;
885 }
886 err = copy_func_state(dst, src->frame[i]);
887 if (err)
888 return err;
889 }
890 return 0;
891}
892
2589726d
AS
893static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
894{
895 while (st) {
896 u32 br = --st->branches;
897
898 /* WARN_ON(br > 1) technically makes sense here,
899 * but see comment in push_stack(), hence:
900 */
901 WARN_ONCE((int)br < 0,
902 "BUG update_branch_counts:branches_to_explore=%d\n",
903 br);
904 if (br)
905 break;
906 st = st->parent;
907 }
908}
909
638f5b90 910static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 911 int *insn_idx, bool pop_log)
638f5b90
AS
912{
913 struct bpf_verifier_state *cur = env->cur_state;
914 struct bpf_verifier_stack_elem *elem, *head = env->head;
915 int err;
17a52670
AS
916
917 if (env->head == NULL)
638f5b90 918 return -ENOENT;
17a52670 919
638f5b90
AS
920 if (cur) {
921 err = copy_verifier_state(cur, &head->st);
922 if (err)
923 return err;
924 }
6f8a57cc
AN
925 if (pop_log)
926 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
927 if (insn_idx)
928 *insn_idx = head->insn_idx;
17a52670 929 if (prev_insn_idx)
638f5b90
AS
930 *prev_insn_idx = head->prev_insn_idx;
931 elem = head->next;
1969db47 932 free_verifier_state(&head->st, false);
638f5b90 933 kfree(head);
17a52670
AS
934 env->head = elem;
935 env->stack_size--;
638f5b90 936 return 0;
17a52670
AS
937}
938
58e2af8b 939static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
940 int insn_idx, int prev_insn_idx,
941 bool speculative)
17a52670 942{
638f5b90 943 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 944 struct bpf_verifier_stack_elem *elem;
638f5b90 945 int err;
17a52670 946
638f5b90 947 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
948 if (!elem)
949 goto err;
950
17a52670
AS
951 elem->insn_idx = insn_idx;
952 elem->prev_insn_idx = prev_insn_idx;
953 elem->next = env->head;
6f8a57cc 954 elem->log_pos = env->log.len_used;
17a52670
AS
955 env->head = elem;
956 env->stack_size++;
1969db47
AS
957 err = copy_verifier_state(&elem->st, cur);
958 if (err)
959 goto err;
979d63d5 960 elem->st.speculative |= speculative;
b285fcb7
AS
961 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
962 verbose(env, "The sequence of %d jumps is too complex.\n",
963 env->stack_size);
17a52670
AS
964 goto err;
965 }
2589726d
AS
966 if (elem->st.parent) {
967 ++elem->st.parent->branches;
968 /* WARN_ON(branches > 2) technically makes sense here,
969 * but
970 * 1. speculative states will bump 'branches' for non-branch
971 * instructions
972 * 2. is_state_visited() heuristics may decide not to create
973 * a new state for a sequence of branches and all such current
974 * and cloned states will be pointing to a single parent state
975 * which might have large 'branches' count.
976 */
977 }
17a52670
AS
978 return &elem->st;
979err:
5896351e
AS
980 free_verifier_state(env->cur_state, true);
981 env->cur_state = NULL;
17a52670 982 /* pop all elements and return */
6f8a57cc 983 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
984 return NULL;
985}
986
987#define CALLER_SAVED_REGS 6
988static const int caller_saved[CALLER_SAVED_REGS] = {
989 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
990};
991
f54c7898
DB
992static void __mark_reg_not_init(const struct bpf_verifier_env *env,
993 struct bpf_reg_state *reg);
f1174f77 994
b03c9f9f
EC
995/* Mark the unknown part of a register (variable offset or scalar value) as
996 * known to have the value @imm.
997 */
998static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
999{
a9c676bc
AS
1000 /* Clear id, off, and union(map_ptr, range) */
1001 memset(((u8 *)reg) + sizeof(reg->type), 0,
1002 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
b03c9f9f
EC
1003 reg->var_off = tnum_const(imm);
1004 reg->smin_value = (s64)imm;
1005 reg->smax_value = (s64)imm;
1006 reg->umin_value = imm;
1007 reg->umax_value = imm;
3f50f132
JF
1008
1009 reg->s32_min_value = (s32)imm;
1010 reg->s32_max_value = (s32)imm;
1011 reg->u32_min_value = (u32)imm;
1012 reg->u32_max_value = (u32)imm;
1013}
1014
1015static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1016{
1017 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1018 reg->s32_min_value = (s32)imm;
1019 reg->s32_max_value = (s32)imm;
1020 reg->u32_min_value = (u32)imm;
1021 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1022}
1023
f1174f77
EC
1024/* Mark the 'variable offset' part of a register as zero. This should be
1025 * used only on registers holding a pointer type.
1026 */
1027static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1028{
b03c9f9f 1029 __mark_reg_known(reg, 0);
f1174f77 1030}
a9789ef9 1031
cc2b14d5
AS
1032static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1033{
1034 __mark_reg_known(reg, 0);
cc2b14d5
AS
1035 reg->type = SCALAR_VALUE;
1036}
1037
61bd5218
JK
1038static void mark_reg_known_zero(struct bpf_verifier_env *env,
1039 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1040{
1041 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1042 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1043 /* Something bad happened, let's kill all regs */
1044 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1045 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1046 return;
1047 }
1048 __mark_reg_known_zero(regs + regno);
1049}
1050
de8f3a83
DB
1051static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1052{
1053 return type_is_pkt_pointer(reg->type);
1054}
1055
1056static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1057{
1058 return reg_is_pkt_pointer(reg) ||
1059 reg->type == PTR_TO_PACKET_END;
1060}
1061
1062/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1063static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1064 enum bpf_reg_type which)
1065{
1066 /* The register can already have a range from prior markings.
1067 * This is fine as long as it hasn't been advanced from its
1068 * origin.
1069 */
1070 return reg->type == which &&
1071 reg->id == 0 &&
1072 reg->off == 0 &&
1073 tnum_equals_const(reg->var_off, 0);
1074}
1075
3f50f132
JF
1076/* Reset the min/max bounds of a register */
1077static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1078{
1079 reg->smin_value = S64_MIN;
1080 reg->smax_value = S64_MAX;
1081 reg->umin_value = 0;
1082 reg->umax_value = U64_MAX;
1083
1084 reg->s32_min_value = S32_MIN;
1085 reg->s32_max_value = S32_MAX;
1086 reg->u32_min_value = 0;
1087 reg->u32_max_value = U32_MAX;
1088}
1089
1090static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1091{
1092 reg->smin_value = S64_MIN;
1093 reg->smax_value = S64_MAX;
1094 reg->umin_value = 0;
1095 reg->umax_value = U64_MAX;
1096}
1097
1098static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1099{
1100 reg->s32_min_value = S32_MIN;
1101 reg->s32_max_value = S32_MAX;
1102 reg->u32_min_value = 0;
1103 reg->u32_max_value = U32_MAX;
1104}
1105
1106static void __update_reg32_bounds(struct bpf_reg_state *reg)
1107{
1108 struct tnum var32_off = tnum_subreg(reg->var_off);
1109
1110 /* min signed is max(sign bit) | min(other bits) */
1111 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1112 var32_off.value | (var32_off.mask & S32_MIN));
1113 /* max signed is min(sign bit) | max(other bits) */
1114 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1115 var32_off.value | (var32_off.mask & S32_MAX));
1116 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1117 reg->u32_max_value = min(reg->u32_max_value,
1118 (u32)(var32_off.value | var32_off.mask));
1119}
1120
1121static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1122{
1123 /* min signed is max(sign bit) | min(other bits) */
1124 reg->smin_value = max_t(s64, reg->smin_value,
1125 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1126 /* max signed is min(sign bit) | max(other bits) */
1127 reg->smax_value = min_t(s64, reg->smax_value,
1128 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1129 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1130 reg->umax_value = min(reg->umax_value,
1131 reg->var_off.value | reg->var_off.mask);
1132}
1133
3f50f132
JF
1134static void __update_reg_bounds(struct bpf_reg_state *reg)
1135{
1136 __update_reg32_bounds(reg);
1137 __update_reg64_bounds(reg);
1138}
1139
b03c9f9f 1140/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1141static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1142{
1143 /* Learn sign from signed bounds.
1144 * If we cannot cross the sign boundary, then signed and unsigned bounds
1145 * are the same, so combine. This works even in the negative case, e.g.
1146 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1147 */
1148 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1149 reg->s32_min_value = reg->u32_min_value =
1150 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1151 reg->s32_max_value = reg->u32_max_value =
1152 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1153 return;
1154 }
1155 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1156 * boundary, so we must be careful.
1157 */
1158 if ((s32)reg->u32_max_value >= 0) {
1159 /* Positive. We can't learn anything from the smin, but smax
1160 * is positive, hence safe.
1161 */
1162 reg->s32_min_value = reg->u32_min_value;
1163 reg->s32_max_value = reg->u32_max_value =
1164 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1165 } else if ((s32)reg->u32_min_value < 0) {
1166 /* Negative. We can't learn anything from the smax, but smin
1167 * is negative, hence safe.
1168 */
1169 reg->s32_min_value = reg->u32_min_value =
1170 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1171 reg->s32_max_value = reg->u32_max_value;
1172 }
1173}
1174
1175static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1176{
1177 /* Learn sign from signed bounds.
1178 * If we cannot cross the sign boundary, then signed and unsigned bounds
1179 * are the same, so combine. This works even in the negative case, e.g.
1180 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1181 */
1182 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1183 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1184 reg->umin_value);
1185 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1186 reg->umax_value);
1187 return;
1188 }
1189 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1190 * boundary, so we must be careful.
1191 */
1192 if ((s64)reg->umax_value >= 0) {
1193 /* Positive. We can't learn anything from the smin, but smax
1194 * is positive, hence safe.
1195 */
1196 reg->smin_value = reg->umin_value;
1197 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1198 reg->umax_value);
1199 } else if ((s64)reg->umin_value < 0) {
1200 /* Negative. We can't learn anything from the smax, but smin
1201 * is negative, hence safe.
1202 */
1203 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1204 reg->umin_value);
1205 reg->smax_value = reg->umax_value;
1206 }
1207}
1208
3f50f132
JF
1209static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1210{
1211 __reg32_deduce_bounds(reg);
1212 __reg64_deduce_bounds(reg);
1213}
1214
b03c9f9f
EC
1215/* Attempts to improve var_off based on unsigned min/max information */
1216static void __reg_bound_offset(struct bpf_reg_state *reg)
1217{
3f50f132
JF
1218 struct tnum var64_off = tnum_intersect(reg->var_off,
1219 tnum_range(reg->umin_value,
1220 reg->umax_value));
1221 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1222 tnum_range(reg->u32_min_value,
1223 reg->u32_max_value));
1224
1225 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1226}
1227
3f50f132 1228static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1229{
3f50f132
JF
1230 reg->umin_value = reg->u32_min_value;
1231 reg->umax_value = reg->u32_max_value;
1232 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1233 * but must be positive otherwise set to worse case bounds
1234 * and refine later from tnum.
1235 */
3a71dc36 1236 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1237 reg->smax_value = reg->s32_max_value;
1238 else
1239 reg->smax_value = U32_MAX;
3a71dc36
JF
1240 if (reg->s32_min_value >= 0)
1241 reg->smin_value = reg->s32_min_value;
1242 else
1243 reg->smin_value = 0;
3f50f132
JF
1244}
1245
1246static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1247{
1248 /* special case when 64-bit register has upper 32-bit register
1249 * zeroed. Typically happens after zext or <<32, >>32 sequence
1250 * allowing us to use 32-bit bounds directly,
1251 */
1252 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1253 __reg_assign_32_into_64(reg);
1254 } else {
1255 /* Otherwise the best we can do is push lower 32bit known and
1256 * unknown bits into register (var_off set from jmp logic)
1257 * then learn as much as possible from the 64-bit tnum
1258 * known and unknown bits. The previous smin/smax bounds are
1259 * invalid here because of jmp32 compare so mark them unknown
1260 * so they do not impact tnum bounds calculation.
1261 */
1262 __mark_reg64_unbounded(reg);
1263 __update_reg_bounds(reg);
1264 }
1265
1266 /* Intersecting with the old var_off might have improved our bounds
1267 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1268 * then new var_off is (0; 0x7f...fc) which improves our umax.
1269 */
1270 __reg_deduce_bounds(reg);
1271 __reg_bound_offset(reg);
1272 __update_reg_bounds(reg);
1273}
1274
1275static bool __reg64_bound_s32(s64 a)
1276{
1277 if (a > S32_MIN && a < S32_MAX)
1278 return true;
1279 return false;
1280}
1281
1282static bool __reg64_bound_u32(u64 a)
1283{
1284 if (a > U32_MIN && a < U32_MAX)
1285 return true;
1286 return false;
1287}
1288
1289static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1290{
1291 __mark_reg32_unbounded(reg);
1292
1293 if (__reg64_bound_s32(reg->smin_value))
1294 reg->s32_min_value = (s32)reg->smin_value;
1295 if (__reg64_bound_s32(reg->smax_value))
1296 reg->s32_max_value = (s32)reg->smax_value;
1297 if (__reg64_bound_u32(reg->umin_value))
1298 reg->u32_min_value = (u32)reg->umin_value;
1299 if (__reg64_bound_u32(reg->umax_value))
1300 reg->u32_max_value = (u32)reg->umax_value;
1301
1302 /* Intersecting with the old var_off might have improved our bounds
1303 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1304 * then new var_off is (0; 0x7f...fc) which improves our umax.
1305 */
1306 __reg_deduce_bounds(reg);
1307 __reg_bound_offset(reg);
1308 __update_reg_bounds(reg);
b03c9f9f
EC
1309}
1310
f1174f77 1311/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1312static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1313 struct bpf_reg_state *reg)
f1174f77 1314{
a9c676bc
AS
1315 /*
1316 * Clear type, id, off, and union(map_ptr, range) and
1317 * padding between 'type' and union
1318 */
1319 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1320 reg->type = SCALAR_VALUE;
f1174f77 1321 reg->var_off = tnum_unknown;
f4d7e40a 1322 reg->frameno = 0;
2c78ee89 1323 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1324 __mark_reg_unbounded(reg);
f1174f77
EC
1325}
1326
61bd5218
JK
1327static void mark_reg_unknown(struct bpf_verifier_env *env,
1328 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1329{
1330 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1331 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1332 /* Something bad happened, let's kill all regs except FP */
1333 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1334 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1335 return;
1336 }
f54c7898 1337 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1338}
1339
f54c7898
DB
1340static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1341 struct bpf_reg_state *reg)
f1174f77 1342{
f54c7898 1343 __mark_reg_unknown(env, reg);
f1174f77
EC
1344 reg->type = NOT_INIT;
1345}
1346
61bd5218
JK
1347static void mark_reg_not_init(struct bpf_verifier_env *env,
1348 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1349{
1350 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1351 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1352 /* Something bad happened, let's kill all regs except FP */
1353 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1354 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1355 return;
1356 }
f54c7898 1357 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1358}
1359
41c48f3a
AI
1360static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1361 struct bpf_reg_state *regs, u32 regno,
1362 enum bpf_reg_type reg_type, u32 btf_id)
1363{
1364 if (reg_type == SCALAR_VALUE) {
1365 mark_reg_unknown(env, regs, regno);
1366 return;
1367 }
1368 mark_reg_known_zero(env, regs, regno);
1369 regs[regno].type = PTR_TO_BTF_ID;
1370 regs[regno].btf_id = btf_id;
1371}
1372
5327ed3d 1373#define DEF_NOT_SUBREG (0)
61bd5218 1374static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1375 struct bpf_func_state *state)
17a52670 1376{
f4d7e40a 1377 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1378 int i;
1379
dc503a8a 1380 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1381 mark_reg_not_init(env, regs, i);
dc503a8a 1382 regs[i].live = REG_LIVE_NONE;
679c782d 1383 regs[i].parent = NULL;
5327ed3d 1384 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1385 }
17a52670
AS
1386
1387 /* frame pointer */
f1174f77 1388 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1389 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1390 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1391}
1392
f4d7e40a
AS
1393#define BPF_MAIN_FUNC (-1)
1394static void init_func_state(struct bpf_verifier_env *env,
1395 struct bpf_func_state *state,
1396 int callsite, int frameno, int subprogno)
1397{
1398 state->callsite = callsite;
1399 state->frameno = frameno;
1400 state->subprogno = subprogno;
1401 init_reg_state(env, state);
1402}
1403
17a52670
AS
1404enum reg_arg_type {
1405 SRC_OP, /* register is used as source operand */
1406 DST_OP, /* register is used as destination operand */
1407 DST_OP_NO_MARK /* same as above, check only, don't mark */
1408};
1409
cc8b0b92
AS
1410static int cmp_subprogs(const void *a, const void *b)
1411{
9c8105bd
JW
1412 return ((struct bpf_subprog_info *)a)->start -
1413 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1414}
1415
1416static int find_subprog(struct bpf_verifier_env *env, int off)
1417{
9c8105bd 1418 struct bpf_subprog_info *p;
cc8b0b92 1419
9c8105bd
JW
1420 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1421 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1422 if (!p)
1423 return -ENOENT;
9c8105bd 1424 return p - env->subprog_info;
cc8b0b92
AS
1425
1426}
1427
1428static int add_subprog(struct bpf_verifier_env *env, int off)
1429{
1430 int insn_cnt = env->prog->len;
1431 int ret;
1432
1433 if (off >= insn_cnt || off < 0) {
1434 verbose(env, "call to invalid destination\n");
1435 return -EINVAL;
1436 }
1437 ret = find_subprog(env, off);
1438 if (ret >= 0)
1439 return 0;
4cb3d99c 1440 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1441 verbose(env, "too many subprograms\n");
1442 return -E2BIG;
1443 }
9c8105bd
JW
1444 env->subprog_info[env->subprog_cnt++].start = off;
1445 sort(env->subprog_info, env->subprog_cnt,
1446 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
cc8b0b92
AS
1447 return 0;
1448}
1449
1450static int check_subprogs(struct bpf_verifier_env *env)
1451{
1452 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
9c8105bd 1453 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92
AS
1454 struct bpf_insn *insn = env->prog->insnsi;
1455 int insn_cnt = env->prog->len;
1456
f910cefa
JW
1457 /* Add entry function. */
1458 ret = add_subprog(env, 0);
1459 if (ret < 0)
1460 return ret;
1461
cc8b0b92
AS
1462 /* determine subprog starts. The end is one before the next starts */
1463 for (i = 0; i < insn_cnt; i++) {
1464 if (insn[i].code != (BPF_JMP | BPF_CALL))
1465 continue;
1466 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1467 continue;
2c78ee89
AS
1468 if (!env->bpf_capable) {
1469 verbose(env,
1470 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1471 return -EPERM;
1472 }
cc8b0b92
AS
1473 ret = add_subprog(env, i + insn[i].imm + 1);
1474 if (ret < 0)
1475 return ret;
1476 }
1477
4cb3d99c
JW
1478 /* Add a fake 'exit' subprog which could simplify subprog iteration
1479 * logic. 'subprog_cnt' should not be increased.
1480 */
1481 subprog[env->subprog_cnt].start = insn_cnt;
1482
06ee7115 1483 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1484 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1485 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92
AS
1486
1487 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1488 subprog_start = subprog[cur_subprog].start;
1489 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1490 for (i = 0; i < insn_cnt; i++) {
1491 u8 code = insn[i].code;
1492
7f6e4312
MF
1493 if (code == (BPF_JMP | BPF_CALL) &&
1494 insn[i].imm == BPF_FUNC_tail_call &&
1495 insn[i].src_reg != BPF_PSEUDO_CALL)
1496 subprog[cur_subprog].has_tail_call = true;
092ed096 1497 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1498 goto next;
1499 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1500 goto next;
1501 off = i + insn[i].off + 1;
1502 if (off < subprog_start || off >= subprog_end) {
1503 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1504 return -EINVAL;
1505 }
1506next:
1507 if (i == subprog_end - 1) {
1508 /* to avoid fall-through from one subprog into another
1509 * the last insn of the subprog should be either exit
1510 * or unconditional jump back
1511 */
1512 if (code != (BPF_JMP | BPF_EXIT) &&
1513 code != (BPF_JMP | BPF_JA)) {
1514 verbose(env, "last insn is not an exit or jmp\n");
1515 return -EINVAL;
1516 }
1517 subprog_start = subprog_end;
4cb3d99c
JW
1518 cur_subprog++;
1519 if (cur_subprog < env->subprog_cnt)
9c8105bd 1520 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1521 }
1522 }
1523 return 0;
1524}
1525
679c782d
EC
1526/* Parentage chain of this register (or stack slot) should take care of all
1527 * issues like callee-saved registers, stack slot allocation time, etc.
1528 */
f4d7e40a 1529static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1530 const struct bpf_reg_state *state,
5327ed3d 1531 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1532{
1533 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1534 int cnt = 0;
dc503a8a
EC
1535
1536 while (parent) {
1537 /* if read wasn't screened by an earlier write ... */
679c782d 1538 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1539 break;
9242b5f5
AS
1540 if (parent->live & REG_LIVE_DONE) {
1541 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1542 reg_type_str[parent->type],
1543 parent->var_off.value, parent->off);
1544 return -EFAULT;
1545 }
5327ed3d
JW
1546 /* The first condition is more likely to be true than the
1547 * second, checked it first.
1548 */
1549 if ((parent->live & REG_LIVE_READ) == flag ||
1550 parent->live & REG_LIVE_READ64)
25af32da
AS
1551 /* The parentage chain never changes and
1552 * this parent was already marked as LIVE_READ.
1553 * There is no need to keep walking the chain again and
1554 * keep re-marking all parents as LIVE_READ.
1555 * This case happens when the same register is read
1556 * multiple times without writes into it in-between.
5327ed3d
JW
1557 * Also, if parent has the stronger REG_LIVE_READ64 set,
1558 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1559 */
1560 break;
dc503a8a 1561 /* ... then we depend on parent's value */
5327ed3d
JW
1562 parent->live |= flag;
1563 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1564 if (flag == REG_LIVE_READ64)
1565 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1566 state = parent;
1567 parent = state->parent;
f4d7e40a 1568 writes = true;
06ee7115 1569 cnt++;
dc503a8a 1570 }
06ee7115
AS
1571
1572 if (env->longest_mark_read_walk < cnt)
1573 env->longest_mark_read_walk = cnt;
f4d7e40a 1574 return 0;
dc503a8a
EC
1575}
1576
5327ed3d
JW
1577/* This function is supposed to be used by the following 32-bit optimization
1578 * code only. It returns TRUE if the source or destination register operates
1579 * on 64-bit, otherwise return FALSE.
1580 */
1581static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1582 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1583{
1584 u8 code, class, op;
1585
1586 code = insn->code;
1587 class = BPF_CLASS(code);
1588 op = BPF_OP(code);
1589 if (class == BPF_JMP) {
1590 /* BPF_EXIT for "main" will reach here. Return TRUE
1591 * conservatively.
1592 */
1593 if (op == BPF_EXIT)
1594 return true;
1595 if (op == BPF_CALL) {
1596 /* BPF to BPF call will reach here because of marking
1597 * caller saved clobber with DST_OP_NO_MARK for which we
1598 * don't care the register def because they are anyway
1599 * marked as NOT_INIT already.
1600 */
1601 if (insn->src_reg == BPF_PSEUDO_CALL)
1602 return false;
1603 /* Helper call will reach here because of arg type
1604 * check, conservatively return TRUE.
1605 */
1606 if (t == SRC_OP)
1607 return true;
1608
1609 return false;
1610 }
1611 }
1612
1613 if (class == BPF_ALU64 || class == BPF_JMP ||
1614 /* BPF_END always use BPF_ALU class. */
1615 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1616 return true;
1617
1618 if (class == BPF_ALU || class == BPF_JMP32)
1619 return false;
1620
1621 if (class == BPF_LDX) {
1622 if (t != SRC_OP)
1623 return BPF_SIZE(code) == BPF_DW;
1624 /* LDX source must be ptr. */
1625 return true;
1626 }
1627
1628 if (class == BPF_STX) {
1629 if (reg->type != SCALAR_VALUE)
1630 return true;
1631 return BPF_SIZE(code) == BPF_DW;
1632 }
1633
1634 if (class == BPF_LD) {
1635 u8 mode = BPF_MODE(code);
1636
1637 /* LD_IMM64 */
1638 if (mode == BPF_IMM)
1639 return true;
1640
1641 /* Both LD_IND and LD_ABS return 32-bit data. */
1642 if (t != SRC_OP)
1643 return false;
1644
1645 /* Implicit ctx ptr. */
1646 if (regno == BPF_REG_6)
1647 return true;
1648
1649 /* Explicit source could be any width. */
1650 return true;
1651 }
1652
1653 if (class == BPF_ST)
1654 /* The only source register for BPF_ST is a ptr. */
1655 return true;
1656
1657 /* Conservatively return true at default. */
1658 return true;
1659}
1660
b325fbca
JW
1661/* Return TRUE if INSN doesn't have explicit value define. */
1662static bool insn_no_def(struct bpf_insn *insn)
1663{
1664 u8 class = BPF_CLASS(insn->code);
1665
1666 return (class == BPF_JMP || class == BPF_JMP32 ||
1667 class == BPF_STX || class == BPF_ST);
1668}
1669
1670/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1671static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1672{
1673 if (insn_no_def(insn))
1674 return false;
1675
1676 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1677}
1678
5327ed3d
JW
1679static void mark_insn_zext(struct bpf_verifier_env *env,
1680 struct bpf_reg_state *reg)
1681{
1682 s32 def_idx = reg->subreg_def;
1683
1684 if (def_idx == DEF_NOT_SUBREG)
1685 return;
1686
1687 env->insn_aux_data[def_idx - 1].zext_dst = true;
1688 /* The dst will be zero extended, so won't be sub-register anymore. */
1689 reg->subreg_def = DEF_NOT_SUBREG;
1690}
1691
dc503a8a 1692static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
1693 enum reg_arg_type t)
1694{
f4d7e40a
AS
1695 struct bpf_verifier_state *vstate = env->cur_state;
1696 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 1697 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 1698 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 1699 bool rw64;
dc503a8a 1700
17a52670 1701 if (regno >= MAX_BPF_REG) {
61bd5218 1702 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
1703 return -EINVAL;
1704 }
1705
c342dc10 1706 reg = &regs[regno];
5327ed3d 1707 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
1708 if (t == SRC_OP) {
1709 /* check whether register used as source operand can be read */
c342dc10 1710 if (reg->type == NOT_INIT) {
61bd5218 1711 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
1712 return -EACCES;
1713 }
679c782d 1714 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
1715 if (regno == BPF_REG_FP)
1716 return 0;
1717
5327ed3d
JW
1718 if (rw64)
1719 mark_insn_zext(env, reg);
1720
1721 return mark_reg_read(env, reg, reg->parent,
1722 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
1723 } else {
1724 /* check whether register used as dest operand can be written to */
1725 if (regno == BPF_REG_FP) {
61bd5218 1726 verbose(env, "frame pointer is read only\n");
17a52670
AS
1727 return -EACCES;
1728 }
c342dc10 1729 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 1730 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 1731 if (t == DST_OP)
61bd5218 1732 mark_reg_unknown(env, regs, regno);
17a52670
AS
1733 }
1734 return 0;
1735}
1736
b5dc0163
AS
1737/* for any branch, call, exit record the history of jmps in the given state */
1738static int push_jmp_history(struct bpf_verifier_env *env,
1739 struct bpf_verifier_state *cur)
1740{
1741 u32 cnt = cur->jmp_history_cnt;
1742 struct bpf_idx_pair *p;
1743
1744 cnt++;
1745 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1746 if (!p)
1747 return -ENOMEM;
1748 p[cnt - 1].idx = env->insn_idx;
1749 p[cnt - 1].prev_idx = env->prev_insn_idx;
1750 cur->jmp_history = p;
1751 cur->jmp_history_cnt = cnt;
1752 return 0;
1753}
1754
1755/* Backtrack one insn at a time. If idx is not at the top of recorded
1756 * history then previous instruction came from straight line execution.
1757 */
1758static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1759 u32 *history)
1760{
1761 u32 cnt = *history;
1762
1763 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1764 i = st->jmp_history[cnt - 1].prev_idx;
1765 (*history)--;
1766 } else {
1767 i--;
1768 }
1769 return i;
1770}
1771
1772/* For given verifier state backtrack_insn() is called from the last insn to
1773 * the first insn. Its purpose is to compute a bitmask of registers and
1774 * stack slots that needs precision in the parent verifier state.
1775 */
1776static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1777 u32 *reg_mask, u64 *stack_mask)
1778{
1779 const struct bpf_insn_cbs cbs = {
1780 .cb_print = verbose,
1781 .private_data = env,
1782 };
1783 struct bpf_insn *insn = env->prog->insnsi + idx;
1784 u8 class = BPF_CLASS(insn->code);
1785 u8 opcode = BPF_OP(insn->code);
1786 u8 mode = BPF_MODE(insn->code);
1787 u32 dreg = 1u << insn->dst_reg;
1788 u32 sreg = 1u << insn->src_reg;
1789 u32 spi;
1790
1791 if (insn->code == 0)
1792 return 0;
1793 if (env->log.level & BPF_LOG_LEVEL) {
1794 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1795 verbose(env, "%d: ", idx);
1796 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1797 }
1798
1799 if (class == BPF_ALU || class == BPF_ALU64) {
1800 if (!(*reg_mask & dreg))
1801 return 0;
1802 if (opcode == BPF_MOV) {
1803 if (BPF_SRC(insn->code) == BPF_X) {
1804 /* dreg = sreg
1805 * dreg needs precision after this insn
1806 * sreg needs precision before this insn
1807 */
1808 *reg_mask &= ~dreg;
1809 *reg_mask |= sreg;
1810 } else {
1811 /* dreg = K
1812 * dreg needs precision after this insn.
1813 * Corresponding register is already marked
1814 * as precise=true in this verifier state.
1815 * No further markings in parent are necessary
1816 */
1817 *reg_mask &= ~dreg;
1818 }
1819 } else {
1820 if (BPF_SRC(insn->code) == BPF_X) {
1821 /* dreg += sreg
1822 * both dreg and sreg need precision
1823 * before this insn
1824 */
1825 *reg_mask |= sreg;
1826 } /* else dreg += K
1827 * dreg still needs precision before this insn
1828 */
1829 }
1830 } else if (class == BPF_LDX) {
1831 if (!(*reg_mask & dreg))
1832 return 0;
1833 *reg_mask &= ~dreg;
1834
1835 /* scalars can only be spilled into stack w/o losing precision.
1836 * Load from any other memory can be zero extended.
1837 * The desire to keep that precision is already indicated
1838 * by 'precise' mark in corresponding register of this state.
1839 * No further tracking necessary.
1840 */
1841 if (insn->src_reg != BPF_REG_FP)
1842 return 0;
1843 if (BPF_SIZE(insn->code) != BPF_DW)
1844 return 0;
1845
1846 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1847 * that [fp - off] slot contains scalar that needs to be
1848 * tracked with precision
1849 */
1850 spi = (-insn->off - 1) / BPF_REG_SIZE;
1851 if (spi >= 64) {
1852 verbose(env, "BUG spi %d\n", spi);
1853 WARN_ONCE(1, "verifier backtracking bug");
1854 return -EFAULT;
1855 }
1856 *stack_mask |= 1ull << spi;
b3b50f05 1857 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 1858 if (*reg_mask & dreg)
b3b50f05 1859 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
1860 * to access memory. It means backtracking
1861 * encountered a case of pointer subtraction.
1862 */
1863 return -ENOTSUPP;
1864 /* scalars can only be spilled into stack */
1865 if (insn->dst_reg != BPF_REG_FP)
1866 return 0;
1867 if (BPF_SIZE(insn->code) != BPF_DW)
1868 return 0;
1869 spi = (-insn->off - 1) / BPF_REG_SIZE;
1870 if (spi >= 64) {
1871 verbose(env, "BUG spi %d\n", spi);
1872 WARN_ONCE(1, "verifier backtracking bug");
1873 return -EFAULT;
1874 }
1875 if (!(*stack_mask & (1ull << spi)))
1876 return 0;
1877 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
1878 if (class == BPF_STX)
1879 *reg_mask |= sreg;
b5dc0163
AS
1880 } else if (class == BPF_JMP || class == BPF_JMP32) {
1881 if (opcode == BPF_CALL) {
1882 if (insn->src_reg == BPF_PSEUDO_CALL)
1883 return -ENOTSUPP;
1884 /* regular helper call sets R0 */
1885 *reg_mask &= ~1;
1886 if (*reg_mask & 0x3f) {
1887 /* if backtracing was looking for registers R1-R5
1888 * they should have been found already.
1889 */
1890 verbose(env, "BUG regs %x\n", *reg_mask);
1891 WARN_ONCE(1, "verifier backtracking bug");
1892 return -EFAULT;
1893 }
1894 } else if (opcode == BPF_EXIT) {
1895 return -ENOTSUPP;
1896 }
1897 } else if (class == BPF_LD) {
1898 if (!(*reg_mask & dreg))
1899 return 0;
1900 *reg_mask &= ~dreg;
1901 /* It's ld_imm64 or ld_abs or ld_ind.
1902 * For ld_imm64 no further tracking of precision
1903 * into parent is necessary
1904 */
1905 if (mode == BPF_IND || mode == BPF_ABS)
1906 /* to be analyzed */
1907 return -ENOTSUPP;
b5dc0163
AS
1908 }
1909 return 0;
1910}
1911
1912/* the scalar precision tracking algorithm:
1913 * . at the start all registers have precise=false.
1914 * . scalar ranges are tracked as normal through alu and jmp insns.
1915 * . once precise value of the scalar register is used in:
1916 * . ptr + scalar alu
1917 * . if (scalar cond K|scalar)
1918 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1919 * backtrack through the verifier states and mark all registers and
1920 * stack slots with spilled constants that these scalar regisers
1921 * should be precise.
1922 * . during state pruning two registers (or spilled stack slots)
1923 * are equivalent if both are not precise.
1924 *
1925 * Note the verifier cannot simply walk register parentage chain,
1926 * since many different registers and stack slots could have been
1927 * used to compute single precise scalar.
1928 *
1929 * The approach of starting with precise=true for all registers and then
1930 * backtrack to mark a register as not precise when the verifier detects
1931 * that program doesn't care about specific value (e.g., when helper
1932 * takes register as ARG_ANYTHING parameter) is not safe.
1933 *
1934 * It's ok to walk single parentage chain of the verifier states.
1935 * It's possible that this backtracking will go all the way till 1st insn.
1936 * All other branches will be explored for needing precision later.
1937 *
1938 * The backtracking needs to deal with cases like:
1939 * 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)
1940 * r9 -= r8
1941 * r5 = r9
1942 * if r5 > 0x79f goto pc+7
1943 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1944 * r5 += 1
1945 * ...
1946 * call bpf_perf_event_output#25
1947 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1948 *
1949 * and this case:
1950 * r6 = 1
1951 * call foo // uses callee's r6 inside to compute r0
1952 * r0 += r6
1953 * if r0 == 0 goto
1954 *
1955 * to track above reg_mask/stack_mask needs to be independent for each frame.
1956 *
1957 * Also if parent's curframe > frame where backtracking started,
1958 * the verifier need to mark registers in both frames, otherwise callees
1959 * may incorrectly prune callers. This is similar to
1960 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1961 *
1962 * For now backtracking falls back into conservative marking.
1963 */
1964static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1965 struct bpf_verifier_state *st)
1966{
1967 struct bpf_func_state *func;
1968 struct bpf_reg_state *reg;
1969 int i, j;
1970
1971 /* big hammer: mark all scalars precise in this path.
1972 * pop_stack may still get !precise scalars.
1973 */
1974 for (; st; st = st->parent)
1975 for (i = 0; i <= st->curframe; i++) {
1976 func = st->frame[i];
1977 for (j = 0; j < BPF_REG_FP; j++) {
1978 reg = &func->regs[j];
1979 if (reg->type != SCALAR_VALUE)
1980 continue;
1981 reg->precise = true;
1982 }
1983 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1984 if (func->stack[j].slot_type[0] != STACK_SPILL)
1985 continue;
1986 reg = &func->stack[j].spilled_ptr;
1987 if (reg->type != SCALAR_VALUE)
1988 continue;
1989 reg->precise = true;
1990 }
1991 }
1992}
1993
a3ce685d
AS
1994static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1995 int spi)
b5dc0163
AS
1996{
1997 struct bpf_verifier_state *st = env->cur_state;
1998 int first_idx = st->first_insn_idx;
1999 int last_idx = env->insn_idx;
2000 struct bpf_func_state *func;
2001 struct bpf_reg_state *reg;
a3ce685d
AS
2002 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2003 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2004 bool skip_first = true;
a3ce685d 2005 bool new_marks = false;
b5dc0163
AS
2006 int i, err;
2007
2c78ee89 2008 if (!env->bpf_capable)
b5dc0163
AS
2009 return 0;
2010
2011 func = st->frame[st->curframe];
a3ce685d
AS
2012 if (regno >= 0) {
2013 reg = &func->regs[regno];
2014 if (reg->type != SCALAR_VALUE) {
2015 WARN_ONCE(1, "backtracing misuse");
2016 return -EFAULT;
2017 }
2018 if (!reg->precise)
2019 new_marks = true;
2020 else
2021 reg_mask = 0;
2022 reg->precise = true;
b5dc0163 2023 }
b5dc0163 2024
a3ce685d
AS
2025 while (spi >= 0) {
2026 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2027 stack_mask = 0;
2028 break;
2029 }
2030 reg = &func->stack[spi].spilled_ptr;
2031 if (reg->type != SCALAR_VALUE) {
2032 stack_mask = 0;
2033 break;
2034 }
2035 if (!reg->precise)
2036 new_marks = true;
2037 else
2038 stack_mask = 0;
2039 reg->precise = true;
2040 break;
2041 }
2042
2043 if (!new_marks)
2044 return 0;
2045 if (!reg_mask && !stack_mask)
2046 return 0;
b5dc0163
AS
2047 for (;;) {
2048 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2049 u32 history = st->jmp_history_cnt;
2050
2051 if (env->log.level & BPF_LOG_LEVEL)
2052 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2053 for (i = last_idx;;) {
2054 if (skip_first) {
2055 err = 0;
2056 skip_first = false;
2057 } else {
2058 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2059 }
2060 if (err == -ENOTSUPP) {
2061 mark_all_scalars_precise(env, st);
2062 return 0;
2063 } else if (err) {
2064 return err;
2065 }
2066 if (!reg_mask && !stack_mask)
2067 /* Found assignment(s) into tracked register in this state.
2068 * Since this state is already marked, just return.
2069 * Nothing to be tracked further in the parent state.
2070 */
2071 return 0;
2072 if (i == first_idx)
2073 break;
2074 i = get_prev_insn_idx(st, i, &history);
2075 if (i >= env->prog->len) {
2076 /* This can happen if backtracking reached insn 0
2077 * and there are still reg_mask or stack_mask
2078 * to backtrack.
2079 * It means the backtracking missed the spot where
2080 * particular register was initialized with a constant.
2081 */
2082 verbose(env, "BUG backtracking idx %d\n", i);
2083 WARN_ONCE(1, "verifier backtracking bug");
2084 return -EFAULT;
2085 }
2086 }
2087 st = st->parent;
2088 if (!st)
2089 break;
2090
a3ce685d 2091 new_marks = false;
b5dc0163
AS
2092 func = st->frame[st->curframe];
2093 bitmap_from_u64(mask, reg_mask);
2094 for_each_set_bit(i, mask, 32) {
2095 reg = &func->regs[i];
a3ce685d
AS
2096 if (reg->type != SCALAR_VALUE) {
2097 reg_mask &= ~(1u << i);
b5dc0163 2098 continue;
a3ce685d 2099 }
b5dc0163
AS
2100 if (!reg->precise)
2101 new_marks = true;
2102 reg->precise = true;
2103 }
2104
2105 bitmap_from_u64(mask, stack_mask);
2106 for_each_set_bit(i, mask, 64) {
2107 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2108 /* the sequence of instructions:
2109 * 2: (bf) r3 = r10
2110 * 3: (7b) *(u64 *)(r3 -8) = r0
2111 * 4: (79) r4 = *(u64 *)(r10 -8)
2112 * doesn't contain jmps. It's backtracked
2113 * as a single block.
2114 * During backtracking insn 3 is not recognized as
2115 * stack access, so at the end of backtracking
2116 * stack slot fp-8 is still marked in stack_mask.
2117 * However the parent state may not have accessed
2118 * fp-8 and it's "unallocated" stack space.
2119 * In such case fallback to conservative.
b5dc0163 2120 */
2339cd6c
AS
2121 mark_all_scalars_precise(env, st);
2122 return 0;
b5dc0163
AS
2123 }
2124
a3ce685d
AS
2125 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2126 stack_mask &= ~(1ull << i);
b5dc0163 2127 continue;
a3ce685d 2128 }
b5dc0163 2129 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2130 if (reg->type != SCALAR_VALUE) {
2131 stack_mask &= ~(1ull << i);
b5dc0163 2132 continue;
a3ce685d 2133 }
b5dc0163
AS
2134 if (!reg->precise)
2135 new_marks = true;
2136 reg->precise = true;
2137 }
2138 if (env->log.level & BPF_LOG_LEVEL) {
2139 print_verifier_state(env, func);
2140 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2141 new_marks ? "didn't have" : "already had",
2142 reg_mask, stack_mask);
2143 }
2144
a3ce685d
AS
2145 if (!reg_mask && !stack_mask)
2146 break;
b5dc0163
AS
2147 if (!new_marks)
2148 break;
2149
2150 last_idx = st->last_insn_idx;
2151 first_idx = st->first_insn_idx;
2152 }
2153 return 0;
2154}
2155
a3ce685d
AS
2156static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2157{
2158 return __mark_chain_precision(env, regno, -1);
2159}
2160
2161static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2162{
2163 return __mark_chain_precision(env, -1, spi);
2164}
b5dc0163 2165
1be7f75d
AS
2166static bool is_spillable_regtype(enum bpf_reg_type type)
2167{
2168 switch (type) {
2169 case PTR_TO_MAP_VALUE:
2170 case PTR_TO_MAP_VALUE_OR_NULL:
2171 case PTR_TO_STACK:
2172 case PTR_TO_CTX:
969bf05e 2173 case PTR_TO_PACKET:
de8f3a83 2174 case PTR_TO_PACKET_META:
969bf05e 2175 case PTR_TO_PACKET_END:
d58e468b 2176 case PTR_TO_FLOW_KEYS:
1be7f75d 2177 case CONST_PTR_TO_MAP:
c64b7983
JS
2178 case PTR_TO_SOCKET:
2179 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2180 case PTR_TO_SOCK_COMMON:
2181 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2182 case PTR_TO_TCP_SOCK:
2183 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2184 case PTR_TO_XDP_SOCK:
65726b5b 2185 case PTR_TO_BTF_ID:
b121b341 2186 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2187 case PTR_TO_RDONLY_BUF:
2188 case PTR_TO_RDONLY_BUF_OR_NULL:
2189 case PTR_TO_RDWR_BUF:
2190 case PTR_TO_RDWR_BUF_OR_NULL:
1be7f75d
AS
2191 return true;
2192 default:
2193 return false;
2194 }
2195}
2196
cc2b14d5
AS
2197/* Does this register contain a constant zero? */
2198static bool register_is_null(struct bpf_reg_state *reg)
2199{
2200 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2201}
2202
f7cf25b2
AS
2203static bool register_is_const(struct bpf_reg_state *reg)
2204{
2205 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2206}
2207
6e7e63cb
JH
2208static bool __is_pointer_value(bool allow_ptr_leaks,
2209 const struct bpf_reg_state *reg)
2210{
2211 if (allow_ptr_leaks)
2212 return false;
2213
2214 return reg->type != SCALAR_VALUE;
2215}
2216
f7cf25b2
AS
2217static void save_register_state(struct bpf_func_state *state,
2218 int spi, struct bpf_reg_state *reg)
2219{
2220 int i;
2221
2222 state->stack[spi].spilled_ptr = *reg;
2223 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2224
2225 for (i = 0; i < BPF_REG_SIZE; i++)
2226 state->stack[spi].slot_type[i] = STACK_SPILL;
2227}
2228
17a52670
AS
2229/* check_stack_read/write functions track spill/fill of registers,
2230 * stack boundary and alignment are checked in check_mem_access()
2231 */
61bd5218 2232static int check_stack_write(struct bpf_verifier_env *env,
f4d7e40a 2233 struct bpf_func_state *state, /* func where register points to */
af86ca4e 2234 int off, int size, int value_regno, int insn_idx)
17a52670 2235{
f4d7e40a 2236 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2237 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2238 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2239 struct bpf_reg_state *reg = NULL;
638f5b90 2240
f4d7e40a 2241 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
fd978bf7 2242 state->acquired_refs, true);
638f5b90
AS
2243 if (err)
2244 return err;
9c399760
AS
2245 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2246 * so it's aligned access and [off, off + size) are within stack limits
2247 */
638f5b90
AS
2248 if (!env->allow_ptr_leaks &&
2249 state->stack[spi].slot_type[0] == STACK_SPILL &&
2250 size != BPF_REG_SIZE) {
2251 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2252 return -EACCES;
2253 }
17a52670 2254
f4d7e40a 2255 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2256 if (value_regno >= 0)
2257 reg = &cur->regs[value_regno];
17a52670 2258
f7cf25b2 2259 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
2c78ee89 2260 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2261 if (dst_reg != BPF_REG_FP) {
2262 /* The backtracking logic can only recognize explicit
2263 * stack slot address like [fp - 8]. Other spill of
2264 * scalar via different register has to be conervative.
2265 * Backtrack from here and mark all registers as precise
2266 * that contributed into 'reg' being a constant.
2267 */
2268 err = mark_chain_precision(env, value_regno);
2269 if (err)
2270 return err;
2271 }
f7cf25b2
AS
2272 save_register_state(state, spi, reg);
2273 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2274 /* register containing pointer is being spilled into stack */
9c399760 2275 if (size != BPF_REG_SIZE) {
f7cf25b2 2276 verbose_linfo(env, insn_idx, "; ");
61bd5218 2277 verbose(env, "invalid size of register spill\n");
17a52670
AS
2278 return -EACCES;
2279 }
2280
f7cf25b2 2281 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2282 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2283 return -EINVAL;
2284 }
2285
2c78ee89 2286 if (!env->bypass_spec_v4) {
f7cf25b2 2287 bool sanitize = false;
17a52670 2288
f7cf25b2
AS
2289 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2290 register_is_const(&state->stack[spi].spilled_ptr))
2291 sanitize = true;
2292 for (i = 0; i < BPF_REG_SIZE; i++)
2293 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2294 sanitize = true;
2295 break;
2296 }
2297 if (sanitize) {
af86ca4e
AS
2298 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2299 int soff = (-spi - 1) * BPF_REG_SIZE;
2300
2301 /* detected reuse of integer stack slot with a pointer
2302 * which means either llvm is reusing stack slot or
2303 * an attacker is trying to exploit CVE-2018-3639
2304 * (speculative store bypass)
2305 * Have to sanitize that slot with preemptive
2306 * store of zero.
2307 */
2308 if (*poff && *poff != soff) {
2309 /* disallow programs where single insn stores
2310 * into two different stack slots, since verifier
2311 * cannot sanitize them
2312 */
2313 verbose(env,
2314 "insn %d cannot access two stack slots fp%d and fp%d",
2315 insn_idx, *poff, soff);
2316 return -EINVAL;
2317 }
2318 *poff = soff;
2319 }
af86ca4e 2320 }
f7cf25b2 2321 save_register_state(state, spi, reg);
9c399760 2322 } else {
cc2b14d5
AS
2323 u8 type = STACK_MISC;
2324
679c782d
EC
2325 /* regular write of data into stack destroys any spilled ptr */
2326 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2327 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2328 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2329 for (i = 0; i < BPF_REG_SIZE; i++)
2330 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2331
cc2b14d5
AS
2332 /* only mark the slot as written if all 8 bytes were written
2333 * otherwise read propagation may incorrectly stop too soon
2334 * when stack slots are partially written.
2335 * This heuristic means that read propagation will be
2336 * conservative, since it will add reg_live_read marks
2337 * to stack slots all the way to first state when programs
2338 * writes+reads less than 8 bytes
2339 */
2340 if (size == BPF_REG_SIZE)
2341 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2342
2343 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2344 if (reg && register_is_null(reg)) {
2345 /* backtracking doesn't work for STACK_ZERO yet. */
2346 err = mark_chain_precision(env, value_regno);
2347 if (err)
2348 return err;
cc2b14d5 2349 type = STACK_ZERO;
b5dc0163 2350 }
cc2b14d5 2351
0bae2d4d 2352 /* Mark slots affected by this stack write. */
9c399760 2353 for (i = 0; i < size; i++)
638f5b90 2354 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2355 type;
17a52670
AS
2356 }
2357 return 0;
2358}
2359
61bd5218 2360static int check_stack_read(struct bpf_verifier_env *env,
f4d7e40a
AS
2361 struct bpf_func_state *reg_state /* func where register points to */,
2362 int off, int size, int value_regno)
17a52670 2363{
f4d7e40a
AS
2364 struct bpf_verifier_state *vstate = env->cur_state;
2365 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2366 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2367 struct bpf_reg_state *reg;
638f5b90 2368 u8 *stype;
17a52670 2369
f4d7e40a 2370 if (reg_state->allocated_stack <= slot) {
638f5b90
AS
2371 verbose(env, "invalid read from stack off %d+0 size %d\n",
2372 off, size);
2373 return -EACCES;
2374 }
f4d7e40a 2375 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2376 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2377
638f5b90 2378 if (stype[0] == STACK_SPILL) {
9c399760 2379 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2380 if (reg->type != SCALAR_VALUE) {
2381 verbose_linfo(env, env->insn_idx, "; ");
2382 verbose(env, "invalid size of register fill\n");
2383 return -EACCES;
2384 }
2385 if (value_regno >= 0) {
2386 mark_reg_unknown(env, state->regs, value_regno);
2387 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2388 }
2389 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2390 return 0;
17a52670 2391 }
9c399760 2392 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2393 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2394 verbose(env, "corrupted spill memory\n");
17a52670
AS
2395 return -EACCES;
2396 }
2397 }
2398
dc503a8a 2399 if (value_regno >= 0) {
17a52670 2400 /* restore register state from stack */
f7cf25b2 2401 state->regs[value_regno] = *reg;
2f18f62e
AS
2402 /* mark reg as written since spilled pointer state likely
2403 * has its liveness marks cleared by is_state_visited()
2404 * which resets stack/reg liveness for state transitions
2405 */
2406 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb
JH
2407 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2408 /* If value_regno==-1, the caller is asking us whether
2409 * it is acceptable to use this value as a SCALAR_VALUE
2410 * (e.g. for XADD).
2411 * We must not allow unprivileged callers to do that
2412 * with spilled pointers.
2413 */
2414 verbose(env, "leaking pointer from stack off %d\n",
2415 off);
2416 return -EACCES;
dc503a8a 2417 }
f7cf25b2 2418 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2419 } else {
cc2b14d5
AS
2420 int zeros = 0;
2421
17a52670 2422 for (i = 0; i < size; i++) {
cc2b14d5
AS
2423 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2424 continue;
2425 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2426 zeros++;
2427 continue;
17a52670 2428 }
cc2b14d5
AS
2429 verbose(env, "invalid read from stack off %d+%d size %d\n",
2430 off, i, size);
2431 return -EACCES;
2432 }
f7cf25b2 2433 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
cc2b14d5
AS
2434 if (value_regno >= 0) {
2435 if (zeros == size) {
2436 /* any size read into register is zero extended,
2437 * so the whole register == const_zero
2438 */
2439 __mark_reg_const_zero(&state->regs[value_regno]);
b5dc0163
AS
2440 /* backtracking doesn't support STACK_ZERO yet,
2441 * so mark it precise here, so that later
2442 * backtracking can stop here.
2443 * Backtracking may not need this if this register
2444 * doesn't participate in pointer adjustment.
2445 * Forward propagation of precise flag is not
2446 * necessary either. This mark is only to stop
2447 * backtracking. Any register that contributed
2448 * to const 0 was marked precise before spill.
2449 */
2450 state->regs[value_regno].precise = true;
cc2b14d5
AS
2451 } else {
2452 /* have read misc data from the stack */
2453 mark_reg_unknown(env, state->regs, value_regno);
2454 }
2455 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
17a52670 2456 }
17a52670 2457 }
f7cf25b2 2458 return 0;
17a52670
AS
2459}
2460
e4298d25
DB
2461static int check_stack_access(struct bpf_verifier_env *env,
2462 const struct bpf_reg_state *reg,
2463 int off, int size)
2464{
2465 /* Stack accesses must be at a fixed offset, so that we
2466 * can determine what type of data were returned. See
2467 * check_stack_read().
2468 */
2469 if (!tnum_is_const(reg->var_off)) {
2470 char tn_buf[48];
2471
2472 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1fbd20f8 2473 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
e4298d25
DB
2474 tn_buf, off, size);
2475 return -EACCES;
2476 }
2477
2478 if (off >= 0 || off < -MAX_BPF_STACK) {
2479 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2480 return -EACCES;
2481 }
2482
2483 return 0;
2484}
2485
591fe988
DB
2486static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2487 int off, int size, enum bpf_access_type type)
2488{
2489 struct bpf_reg_state *regs = cur_regs(env);
2490 struct bpf_map *map = regs[regno].map_ptr;
2491 u32 cap = bpf_map_flags_to_cap(map);
2492
2493 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2494 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2495 map->value_size, off, size);
2496 return -EACCES;
2497 }
2498
2499 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2500 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2501 map->value_size, off, size);
2502 return -EACCES;
2503 }
2504
2505 return 0;
2506}
2507
457f4436
AN
2508/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2509static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2510 int off, int size, u32 mem_size,
2511 bool zero_size_allowed)
17a52670 2512{
457f4436
AN
2513 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2514 struct bpf_reg_state *reg;
2515
2516 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2517 return 0;
17a52670 2518
457f4436
AN
2519 reg = &cur_regs(env)[regno];
2520 switch (reg->type) {
2521 case PTR_TO_MAP_VALUE:
61bd5218 2522 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
2523 mem_size, off, size);
2524 break;
2525 case PTR_TO_PACKET:
2526 case PTR_TO_PACKET_META:
2527 case PTR_TO_PACKET_END:
2528 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2529 off, size, regno, reg->id, off, mem_size);
2530 break;
2531 case PTR_TO_MEM:
2532 default:
2533 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2534 mem_size, off, size);
17a52670 2535 }
457f4436
AN
2536
2537 return -EACCES;
17a52670
AS
2538}
2539
457f4436
AN
2540/* check read/write into a memory region with possible variable offset */
2541static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2542 int off, int size, u32 mem_size,
2543 bool zero_size_allowed)
dbcfe5f7 2544{
f4d7e40a
AS
2545 struct bpf_verifier_state *vstate = env->cur_state;
2546 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
2547 struct bpf_reg_state *reg = &state->regs[regno];
2548 int err;
2549
457f4436 2550 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
2551 * need to try adding each of min_value and max_value to off
2552 * to make sure our theoretical access will be safe.
dbcfe5f7 2553 */
06ee7115 2554 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 2555 print_verifier_state(env, state);
b7137c4e 2556
dbcfe5f7
GB
2557 /* The minimum value is only important with signed
2558 * comparisons where we can't assume the floor of a
2559 * value is 0. If we are using signed variables for our
2560 * index'es we need to make sure that whatever we use
2561 * will have a set floor within our range.
2562 */
b7137c4e
DB
2563 if (reg->smin_value < 0 &&
2564 (reg->smin_value == S64_MIN ||
2565 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2566 reg->smin_value + off < 0)) {
61bd5218 2567 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
2568 regno);
2569 return -EACCES;
2570 }
457f4436
AN
2571 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2572 mem_size, zero_size_allowed);
dbcfe5f7 2573 if (err) {
457f4436 2574 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 2575 regno);
dbcfe5f7
GB
2576 return err;
2577 }
2578
b03c9f9f
EC
2579 /* If we haven't set a max value then we need to bail since we can't be
2580 * sure we won't do bad things.
2581 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 2582 */
b03c9f9f 2583 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 2584 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
2585 regno);
2586 return -EACCES;
2587 }
457f4436
AN
2588 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2589 mem_size, zero_size_allowed);
2590 if (err) {
2591 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 2592 regno);
457f4436
AN
2593 return err;
2594 }
2595
2596 return 0;
2597}
d83525ca 2598
457f4436
AN
2599/* check read/write into a map element with possible variable offset */
2600static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2601 int off, int size, bool zero_size_allowed)
2602{
2603 struct bpf_verifier_state *vstate = env->cur_state;
2604 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2605 struct bpf_reg_state *reg = &state->regs[regno];
2606 struct bpf_map *map = reg->map_ptr;
2607 int err;
2608
2609 err = check_mem_region_access(env, regno, off, size, map->value_size,
2610 zero_size_allowed);
2611 if (err)
2612 return err;
2613
2614 if (map_value_has_spin_lock(map)) {
2615 u32 lock = map->spin_lock_off;
d83525ca
AS
2616
2617 /* if any part of struct bpf_spin_lock can be touched by
2618 * load/store reject this program.
2619 * To check that [x1, x2) overlaps with [y1, y2)
2620 * it is sufficient to check x1 < y2 && y1 < x2.
2621 */
2622 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2623 lock < reg->umax_value + off + size) {
2624 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2625 return -EACCES;
2626 }
2627 }
f1174f77 2628 return err;
dbcfe5f7
GB
2629}
2630
969bf05e
AS
2631#define MAX_PACKET_OFF 0xffff
2632
7e40781c
UP
2633static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2634{
2635 return prog->aux->linked_prog ? prog->aux->linked_prog->type
2636 : prog->type;
2637}
2638
58e2af8b 2639static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
2640 const struct bpf_call_arg_meta *meta,
2641 enum bpf_access_type t)
4acf6c0b 2642{
7e40781c
UP
2643 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2644
2645 switch (prog_type) {
5d66fa7d 2646 /* Program types only with direct read access go here! */
3a0af8fd
TG
2647 case BPF_PROG_TYPE_LWT_IN:
2648 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 2649 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 2650 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 2651 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 2652 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
2653 if (t == BPF_WRITE)
2654 return false;
7e57fbb2 2655 /* fallthrough */
5d66fa7d
DB
2656
2657 /* Program types with direct read + write access go here! */
36bbef52
DB
2658 case BPF_PROG_TYPE_SCHED_CLS:
2659 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 2660 case BPF_PROG_TYPE_XDP:
3a0af8fd 2661 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 2662 case BPF_PROG_TYPE_SK_SKB:
4f738adb 2663 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
2664 if (meta)
2665 return meta->pkt_access;
2666
2667 env->seen_direct_write = true;
4acf6c0b 2668 return true;
0d01da6a
SF
2669
2670 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2671 if (t == BPF_WRITE)
2672 env->seen_direct_write = true;
2673
2674 return true;
2675
4acf6c0b
BB
2676 default:
2677 return false;
2678 }
2679}
2680
f1174f77 2681static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 2682 int size, bool zero_size_allowed)
f1174f77 2683{
638f5b90 2684 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
2685 struct bpf_reg_state *reg = &regs[regno];
2686 int err;
2687
2688 /* We may have added a variable offset to the packet pointer; but any
2689 * reg->range we have comes after that. We are only checking the fixed
2690 * offset.
2691 */
2692
2693 /* We don't allow negative numbers, because we aren't tracking enough
2694 * detail to prove they're safe.
2695 */
b03c9f9f 2696 if (reg->smin_value < 0) {
61bd5218 2697 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
2698 regno);
2699 return -EACCES;
2700 }
457f4436
AN
2701 err = __check_mem_access(env, regno, off, size, reg->range,
2702 zero_size_allowed);
f1174f77 2703 if (err) {
61bd5218 2704 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
2705 return err;
2706 }
e647815a 2707
457f4436 2708 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
2709 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2710 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 2711 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
2712 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2713 */
2714 env->prog->aux->max_pkt_offset =
2715 max_t(u32, env->prog->aux->max_pkt_offset,
2716 off + reg->umax_value + size - 1);
2717
f1174f77
EC
2718 return err;
2719}
2720
2721/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 2722static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66
AS
2723 enum bpf_access_type t, enum bpf_reg_type *reg_type,
2724 u32 *btf_id)
17a52670 2725{
f96da094
DB
2726 struct bpf_insn_access_aux info = {
2727 .reg_type = *reg_type,
9e15db66 2728 .log = &env->log,
f96da094 2729 };
31fd8581 2730
4f9218aa 2731 if (env->ops->is_valid_access &&
5e43f899 2732 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
2733 /* A non zero info.ctx_field_size indicates that this field is a
2734 * candidate for later verifier transformation to load the whole
2735 * field and then apply a mask when accessed with a narrower
2736 * access than actual ctx access size. A zero info.ctx_field_size
2737 * will only allow for whole field access and rejects any other
2738 * type of narrower access.
31fd8581 2739 */
23994631 2740 *reg_type = info.reg_type;
31fd8581 2741
b121b341 2742 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66
AS
2743 *btf_id = info.btf_id;
2744 else
2745 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
32bbe007
AS
2746 /* remember the offset of last byte accessed in ctx */
2747 if (env->prog->aux->max_ctx_offset < off + size)
2748 env->prog->aux->max_ctx_offset = off + size;
17a52670 2749 return 0;
32bbe007 2750 }
17a52670 2751
61bd5218 2752 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
2753 return -EACCES;
2754}
2755
d58e468b
PP
2756static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2757 int size)
2758{
2759 if (size < 0 || off < 0 ||
2760 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2761 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2762 off, size);
2763 return -EACCES;
2764 }
2765 return 0;
2766}
2767
5f456649
MKL
2768static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2769 u32 regno, int off, int size,
2770 enum bpf_access_type t)
c64b7983
JS
2771{
2772 struct bpf_reg_state *regs = cur_regs(env);
2773 struct bpf_reg_state *reg = &regs[regno];
5f456649 2774 struct bpf_insn_access_aux info = {};
46f8bc92 2775 bool valid;
c64b7983
JS
2776
2777 if (reg->smin_value < 0) {
2778 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2779 regno);
2780 return -EACCES;
2781 }
2782
46f8bc92
MKL
2783 switch (reg->type) {
2784 case PTR_TO_SOCK_COMMON:
2785 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2786 break;
2787 case PTR_TO_SOCKET:
2788 valid = bpf_sock_is_valid_access(off, size, t, &info);
2789 break;
655a51e5
MKL
2790 case PTR_TO_TCP_SOCK:
2791 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2792 break;
fada7fdc
JL
2793 case PTR_TO_XDP_SOCK:
2794 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2795 break;
46f8bc92
MKL
2796 default:
2797 valid = false;
c64b7983
JS
2798 }
2799
5f456649 2800
46f8bc92
MKL
2801 if (valid) {
2802 env->insn_aux_data[insn_idx].ctx_field_size =
2803 info.ctx_field_size;
2804 return 0;
2805 }
2806
2807 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2808 regno, reg_type_str[reg->type], off, size);
2809
2810 return -EACCES;
c64b7983
JS
2811}
2812
2a159c6f
DB
2813static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2814{
2815 return cur_regs(env) + regno;
2816}
2817
4cabc5b1
DB
2818static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2819{
2a159c6f 2820 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
2821}
2822
f37a8cb8
DB
2823static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2824{
2a159c6f 2825 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 2826
46f8bc92
MKL
2827 return reg->type == PTR_TO_CTX;
2828}
2829
2830static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2831{
2832 const struct bpf_reg_state *reg = reg_state(env, regno);
2833
2834 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
2835}
2836
ca369602
DB
2837static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2838{
2a159c6f 2839 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
2840
2841 return type_is_pkt_pointer(reg->type);
2842}
2843
4b5defde
DB
2844static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2845{
2846 const struct bpf_reg_state *reg = reg_state(env, regno);
2847
2848 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2849 return reg->type == PTR_TO_FLOW_KEYS;
2850}
2851
61bd5218
JK
2852static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2853 const struct bpf_reg_state *reg,
d1174416 2854 int off, int size, bool strict)
969bf05e 2855{
f1174f77 2856 struct tnum reg_off;
e07b98d9 2857 int ip_align;
d1174416
DM
2858
2859 /* Byte size accesses are always allowed. */
2860 if (!strict || size == 1)
2861 return 0;
2862
e4eda884
DM
2863 /* For platforms that do not have a Kconfig enabling
2864 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2865 * NET_IP_ALIGN is universally set to '2'. And on platforms
2866 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2867 * to this code only in strict mode where we want to emulate
2868 * the NET_IP_ALIGN==2 checking. Therefore use an
2869 * unconditional IP align value of '2'.
e07b98d9 2870 */
e4eda884 2871 ip_align = 2;
f1174f77
EC
2872
2873 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2874 if (!tnum_is_aligned(reg_off, size)) {
2875 char tn_buf[48];
2876
2877 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
2878 verbose(env,
2879 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 2880 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
2881 return -EACCES;
2882 }
79adffcd 2883
969bf05e
AS
2884 return 0;
2885}
2886
61bd5218
JK
2887static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2888 const struct bpf_reg_state *reg,
f1174f77
EC
2889 const char *pointer_desc,
2890 int off, int size, bool strict)
79adffcd 2891{
f1174f77
EC
2892 struct tnum reg_off;
2893
2894 /* Byte size accesses are always allowed. */
2895 if (!strict || size == 1)
2896 return 0;
2897
2898 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2899 if (!tnum_is_aligned(reg_off, size)) {
2900 char tn_buf[48];
2901
2902 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 2903 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 2904 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
2905 return -EACCES;
2906 }
2907
969bf05e
AS
2908 return 0;
2909}
2910
e07b98d9 2911static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
2912 const struct bpf_reg_state *reg, int off,
2913 int size, bool strict_alignment_once)
79adffcd 2914{
ca369602 2915 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 2916 const char *pointer_desc = "";
d1174416 2917
79adffcd
DB
2918 switch (reg->type) {
2919 case PTR_TO_PACKET:
de8f3a83
DB
2920 case PTR_TO_PACKET_META:
2921 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2922 * right in front, treat it the very same way.
2923 */
61bd5218 2924 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
2925 case PTR_TO_FLOW_KEYS:
2926 pointer_desc = "flow keys ";
2927 break;
f1174f77
EC
2928 case PTR_TO_MAP_VALUE:
2929 pointer_desc = "value ";
2930 break;
2931 case PTR_TO_CTX:
2932 pointer_desc = "context ";
2933 break;
2934 case PTR_TO_STACK:
2935 pointer_desc = "stack ";
a5ec6ae1
JH
2936 /* The stack spill tracking logic in check_stack_write()
2937 * and check_stack_read() relies on stack accesses being
2938 * aligned.
2939 */
2940 strict = true;
f1174f77 2941 break;
c64b7983
JS
2942 case PTR_TO_SOCKET:
2943 pointer_desc = "sock ";
2944 break;
46f8bc92
MKL
2945 case PTR_TO_SOCK_COMMON:
2946 pointer_desc = "sock_common ";
2947 break;
655a51e5
MKL
2948 case PTR_TO_TCP_SOCK:
2949 pointer_desc = "tcp_sock ";
2950 break;
fada7fdc
JL
2951 case PTR_TO_XDP_SOCK:
2952 pointer_desc = "xdp_sock ";
2953 break;
79adffcd 2954 default:
f1174f77 2955 break;
79adffcd 2956 }
61bd5218
JK
2957 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2958 strict);
79adffcd
DB
2959}
2960
f4d7e40a
AS
2961static int update_stack_depth(struct bpf_verifier_env *env,
2962 const struct bpf_func_state *func,
2963 int off)
2964{
9c8105bd 2965 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
2966
2967 if (stack >= -off)
2968 return 0;
2969
2970 /* update known max for given subprogram */
9c8105bd 2971 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
2972 return 0;
2973}
f4d7e40a 2974
70a87ffe
AS
2975/* starting from main bpf function walk all instructions of the function
2976 * and recursively walk all callees that given function can call.
2977 * Ignore jump and exit insns.
2978 * Since recursion is prevented by check_cfg() this algorithm
2979 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2980 */
2981static int check_max_stack_depth(struct bpf_verifier_env *env)
2982{
9c8105bd
JW
2983 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2984 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 2985 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 2986 bool tail_call_reachable = false;
70a87ffe
AS
2987 int ret_insn[MAX_CALL_FRAMES];
2988 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 2989 int j;
f4d7e40a 2990
70a87ffe 2991process_func:
7f6e4312
MF
2992 /* protect against potential stack overflow that might happen when
2993 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
2994 * depth for such case down to 256 so that the worst case scenario
2995 * would result in 8k stack size (32 which is tailcall limit * 256 =
2996 * 8k).
2997 *
2998 * To get the idea what might happen, see an example:
2999 * func1 -> sub rsp, 128
3000 * subfunc1 -> sub rsp, 256
3001 * tailcall1 -> add rsp, 256
3002 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3003 * subfunc2 -> sub rsp, 64
3004 * subfunc22 -> sub rsp, 128
3005 * tailcall2 -> add rsp, 128
3006 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3007 *
3008 * tailcall will unwind the current stack frame but it will not get rid
3009 * of caller's stack as shown on the example above.
3010 */
3011 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3012 verbose(env,
3013 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3014 depth);
3015 return -EACCES;
3016 }
70a87ffe
AS
3017 /* round up to 32-bytes, since this is granularity
3018 * of interpreter stack size
3019 */
9c8105bd 3020 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3021 if (depth > MAX_BPF_STACK) {
f4d7e40a 3022 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3023 frame + 1, depth);
f4d7e40a
AS
3024 return -EACCES;
3025 }
70a87ffe 3026continue_func:
4cb3d99c 3027 subprog_end = subprog[idx + 1].start;
70a87ffe
AS
3028 for (; i < subprog_end; i++) {
3029 if (insn[i].code != (BPF_JMP | BPF_CALL))
3030 continue;
3031 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3032 continue;
3033 /* remember insn and function to return to */
3034 ret_insn[frame] = i + 1;
9c8105bd 3035 ret_prog[frame] = idx;
70a87ffe
AS
3036
3037 /* find the callee */
3038 i = i + insn[i].imm + 1;
9c8105bd
JW
3039 idx = find_subprog(env, i);
3040 if (idx < 0) {
70a87ffe
AS
3041 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3042 i);
3043 return -EFAULT;
3044 }
ebf7d1f5
MF
3045
3046 if (subprog[idx].has_tail_call)
3047 tail_call_reachable = true;
3048
70a87ffe
AS
3049 frame++;
3050 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3051 verbose(env, "the call stack of %d frames is too deep !\n",
3052 frame);
3053 return -E2BIG;
70a87ffe
AS
3054 }
3055 goto process_func;
3056 }
ebf7d1f5
MF
3057 /* if tail call got detected across bpf2bpf calls then mark each of the
3058 * currently present subprog frames as tail call reachable subprogs;
3059 * this info will be utilized by JIT so that we will be preserving the
3060 * tail call counter throughout bpf2bpf calls combined with tailcalls
3061 */
3062 if (tail_call_reachable)
3063 for (j = 0; j < frame; j++)
3064 subprog[ret_prog[j]].tail_call_reachable = true;
3065
70a87ffe
AS
3066 /* end of for() loop means the last insn of the 'subprog'
3067 * was reached. Doesn't matter whether it was JA or EXIT
3068 */
3069 if (frame == 0)
3070 return 0;
9c8105bd 3071 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3072 frame--;
3073 i = ret_insn[frame];
9c8105bd 3074 idx = ret_prog[frame];
70a87ffe 3075 goto continue_func;
f4d7e40a
AS
3076}
3077
19d28fbd 3078#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3079static int get_callee_stack_depth(struct bpf_verifier_env *env,
3080 const struct bpf_insn *insn, int idx)
3081{
3082 int start = idx + insn->imm + 1, subprog;
3083
3084 subprog = find_subprog(env, start);
3085 if (subprog < 0) {
3086 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3087 start);
3088 return -EFAULT;
3089 }
9c8105bd 3090 return env->subprog_info[subprog].stack_depth;
1ea47e01 3091}
19d28fbd 3092#endif
1ea47e01 3093
51c39bb1
AS
3094int check_ctx_reg(struct bpf_verifier_env *env,
3095 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3096{
3097 /* Access to ctx or passing it to a helper is only allowed in
3098 * its original, unmodified form.
3099 */
3100
3101 if (reg->off) {
3102 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3103 regno, reg->off);
3104 return -EACCES;
3105 }
3106
3107 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3108 char tn_buf[48];
3109
3110 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3111 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3112 return -EACCES;
3113 }
3114
3115 return 0;
3116}
3117
afbf21dc
YS
3118static int __check_buffer_access(struct bpf_verifier_env *env,
3119 const char *buf_info,
3120 const struct bpf_reg_state *reg,
3121 int regno, int off, int size)
9df1c28b
MM
3122{
3123 if (off < 0) {
3124 verbose(env,
4fc00b79 3125 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3126 regno, buf_info, off, size);
9df1c28b
MM
3127 return -EACCES;
3128 }
3129 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3130 char tn_buf[48];
3131
3132 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3133 verbose(env,
4fc00b79 3134 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3135 regno, off, tn_buf);
3136 return -EACCES;
3137 }
afbf21dc
YS
3138
3139 return 0;
3140}
3141
3142static int check_tp_buffer_access(struct bpf_verifier_env *env,
3143 const struct bpf_reg_state *reg,
3144 int regno, int off, int size)
3145{
3146 int err;
3147
3148 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3149 if (err)
3150 return err;
3151
9df1c28b
MM
3152 if (off + size > env->prog->aux->max_tp_access)
3153 env->prog->aux->max_tp_access = off + size;
3154
3155 return 0;
3156}
3157
afbf21dc
YS
3158static int check_buffer_access(struct bpf_verifier_env *env,
3159 const struct bpf_reg_state *reg,
3160 int regno, int off, int size,
3161 bool zero_size_allowed,
3162 const char *buf_info,
3163 u32 *max_access)
3164{
3165 int err;
3166
3167 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3168 if (err)
3169 return err;
3170
3171 if (off + size > *max_access)
3172 *max_access = off + size;
3173
3174 return 0;
3175}
3176
3f50f132
JF
3177/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3178static void zext_32_to_64(struct bpf_reg_state *reg)
3179{
3180 reg->var_off = tnum_subreg(reg->var_off);
3181 __reg_assign_32_into_64(reg);
3182}
9df1c28b 3183
0c17d1d2
JH
3184/* truncate register to smaller size (in bytes)
3185 * must be called with size < BPF_REG_SIZE
3186 */
3187static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3188{
3189 u64 mask;
3190
3191 /* clear high bits in bit representation */
3192 reg->var_off = tnum_cast(reg->var_off, size);
3193
3194 /* fix arithmetic bounds */
3195 mask = ((u64)1 << (size * 8)) - 1;
3196 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3197 reg->umin_value &= mask;
3198 reg->umax_value &= mask;
3199 } else {
3200 reg->umin_value = 0;
3201 reg->umax_value = mask;
3202 }
3203 reg->smin_value = reg->umin_value;
3204 reg->smax_value = reg->umax_value;
3f50f132
JF
3205
3206 /* If size is smaller than 32bit register the 32bit register
3207 * values are also truncated so we push 64-bit bounds into
3208 * 32-bit bounds. Above were truncated < 32-bits already.
3209 */
3210 if (size >= 4)
3211 return;
3212 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3213}
3214
a23740ec
AN
3215static bool bpf_map_is_rdonly(const struct bpf_map *map)
3216{
3217 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3218}
3219
3220static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3221{
3222 void *ptr;
3223 u64 addr;
3224 int err;
3225
3226 err = map->ops->map_direct_value_addr(map, &addr, off);
3227 if (err)
3228 return err;
2dedd7d2 3229 ptr = (void *)(long)addr + off;
a23740ec
AN
3230
3231 switch (size) {
3232 case sizeof(u8):
3233 *val = (u64)*(u8 *)ptr;
3234 break;
3235 case sizeof(u16):
3236 *val = (u64)*(u16 *)ptr;
3237 break;
3238 case sizeof(u32):
3239 *val = (u64)*(u32 *)ptr;
3240 break;
3241 case sizeof(u64):
3242 *val = *(u64 *)ptr;
3243 break;
3244 default:
3245 return -EINVAL;
3246 }
3247 return 0;
3248}
3249
9e15db66
AS
3250static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3251 struct bpf_reg_state *regs,
3252 int regno, int off, int size,
3253 enum bpf_access_type atype,
3254 int value_regno)
3255{
3256 struct bpf_reg_state *reg = regs + regno;
3257 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3258 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3259 u32 btf_id;
3260 int ret;
3261
9e15db66
AS
3262 if (off < 0) {
3263 verbose(env,
3264 "R%d is ptr_%s invalid negative access: off=%d\n",
3265 regno, tname, off);
3266 return -EACCES;
3267 }
3268 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3269 char tn_buf[48];
3270
3271 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3272 verbose(env,
3273 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3274 regno, tname, off, tn_buf);
3275 return -EACCES;
3276 }
3277
27ae7997
MKL
3278 if (env->ops->btf_struct_access) {
3279 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3280 atype, &btf_id);
3281 } else {
3282 if (atype != BPF_READ) {
3283 verbose(env, "only read is supported\n");
3284 return -EACCES;
3285 }
3286
3287 ret = btf_struct_access(&env->log, t, off, size, atype,
3288 &btf_id);
3289 }
3290
9e15db66
AS
3291 if (ret < 0)
3292 return ret;
3293
41c48f3a
AI
3294 if (atype == BPF_READ && value_regno >= 0)
3295 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3296
3297 return 0;
3298}
3299
3300static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3301 struct bpf_reg_state *regs,
3302 int regno, int off, int size,
3303 enum bpf_access_type atype,
3304 int value_regno)
3305{
3306 struct bpf_reg_state *reg = regs + regno;
3307 struct bpf_map *map = reg->map_ptr;
3308 const struct btf_type *t;
3309 const char *tname;
3310 u32 btf_id;
3311 int ret;
3312
3313 if (!btf_vmlinux) {
3314 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3315 return -ENOTSUPP;
3316 }
3317
3318 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3319 verbose(env, "map_ptr access not supported for map type %d\n",
3320 map->map_type);
3321 return -ENOTSUPP;
3322 }
3323
3324 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3325 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3326
3327 if (!env->allow_ptr_to_map_access) {
3328 verbose(env,
3329 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3330 tname);
3331 return -EPERM;
9e15db66 3332 }
27ae7997 3333
41c48f3a
AI
3334 if (off < 0) {
3335 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3336 regno, tname, off);
3337 return -EACCES;
3338 }
3339
3340 if (atype != BPF_READ) {
3341 verbose(env, "only read from %s is supported\n", tname);
3342 return -EACCES;
3343 }
3344
3345 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3346 if (ret < 0)
3347 return ret;
3348
3349 if (value_regno >= 0)
3350 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3351
9e15db66
AS
3352 return 0;
3353}
3354
41c48f3a 3355
17a52670
AS
3356/* check whether memory at (regno + off) is accessible for t = (read | write)
3357 * if t==write, value_regno is a register which value is stored into memory
3358 * if t==read, value_regno is a register which will receive the value from memory
3359 * if t==write && value_regno==-1, some unknown value is stored into memory
3360 * if t==read && value_regno==-1, don't care what we read from memory
3361 */
ca369602
DB
3362static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3363 int off, int bpf_size, enum bpf_access_type t,
3364 int value_regno, bool strict_alignment_once)
17a52670 3365{
638f5b90
AS
3366 struct bpf_reg_state *regs = cur_regs(env);
3367 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 3368 struct bpf_func_state *state;
17a52670
AS
3369 int size, err = 0;
3370
3371 size = bpf_size_to_bytes(bpf_size);
3372 if (size < 0)
3373 return size;
3374
f1174f77 3375 /* alignment checks will add in reg->off themselves */
ca369602 3376 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
3377 if (err)
3378 return err;
17a52670 3379
f1174f77
EC
3380 /* for access checks, reg->off is just part of off */
3381 off += reg->off;
3382
3383 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
3384 if (t == BPF_WRITE && value_regno >= 0 &&
3385 is_pointer_value(env, value_regno)) {
61bd5218 3386 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
3387 return -EACCES;
3388 }
591fe988
DB
3389 err = check_map_access_type(env, regno, off, size, t);
3390 if (err)
3391 return err;
9fd29c08 3392 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
3393 if (!err && t == BPF_READ && value_regno >= 0) {
3394 struct bpf_map *map = reg->map_ptr;
3395
3396 /* if map is read-only, track its contents as scalars */
3397 if (tnum_is_const(reg->var_off) &&
3398 bpf_map_is_rdonly(map) &&
3399 map->ops->map_direct_value_addr) {
3400 int map_off = off + reg->var_off.value;
3401 u64 val = 0;
3402
3403 err = bpf_map_direct_read(map, map_off, size,
3404 &val);
3405 if (err)
3406 return err;
3407
3408 regs[value_regno].type = SCALAR_VALUE;
3409 __mark_reg_known(&regs[value_regno], val);
3410 } else {
3411 mark_reg_unknown(env, regs, value_regno);
3412 }
3413 }
457f4436
AN
3414 } else if (reg->type == PTR_TO_MEM) {
3415 if (t == BPF_WRITE && value_regno >= 0 &&
3416 is_pointer_value(env, value_regno)) {
3417 verbose(env, "R%d leaks addr into mem\n", value_regno);
3418 return -EACCES;
3419 }
3420 err = check_mem_region_access(env, regno, off, size,
3421 reg->mem_size, false);
3422 if (!err && t == BPF_READ && value_regno >= 0)
3423 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 3424 } else if (reg->type == PTR_TO_CTX) {
f1174f77 3425 enum bpf_reg_type reg_type = SCALAR_VALUE;
9e15db66 3426 u32 btf_id = 0;
19de99f7 3427
1be7f75d
AS
3428 if (t == BPF_WRITE && value_regno >= 0 &&
3429 is_pointer_value(env, value_regno)) {
61bd5218 3430 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
3431 return -EACCES;
3432 }
f1174f77 3433
58990d1f
DB
3434 err = check_ctx_reg(env, reg, regno);
3435 if (err < 0)
3436 return err;
3437
9e15db66
AS
3438 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3439 if (err)
3440 verbose_linfo(env, insn_idx, "; ");
969bf05e 3441 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 3442 /* ctx access returns either a scalar, or a
de8f3a83
DB
3443 * PTR_TO_PACKET[_META,_END]. In the latter
3444 * case, we know the offset is zero.
f1174f77 3445 */
46f8bc92 3446 if (reg_type == SCALAR_VALUE) {
638f5b90 3447 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3448 } else {
638f5b90 3449 mark_reg_known_zero(env, regs,
61bd5218 3450 value_regno);
46f8bc92
MKL
3451 if (reg_type_may_be_null(reg_type))
3452 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
3453 /* A load of ctx field could have different
3454 * actual load size with the one encoded in the
3455 * insn. When the dst is PTR, it is for sure not
3456 * a sub-register.
3457 */
3458 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341
YS
3459 if (reg_type == PTR_TO_BTF_ID ||
3460 reg_type == PTR_TO_BTF_ID_OR_NULL)
9e15db66 3461 regs[value_regno].btf_id = btf_id;
46f8bc92 3462 }
638f5b90 3463 regs[value_regno].type = reg_type;
969bf05e 3464 }
17a52670 3465
f1174f77 3466 } else if (reg->type == PTR_TO_STACK) {
f1174f77 3467 off += reg->var_off.value;
e4298d25
DB
3468 err = check_stack_access(env, reg, off, size);
3469 if (err)
3470 return err;
8726679a 3471
f4d7e40a
AS
3472 state = func(env, reg);
3473 err = update_stack_depth(env, state, off);
3474 if (err)
3475 return err;
8726679a 3476
638f5b90 3477 if (t == BPF_WRITE)
61bd5218 3478 err = check_stack_write(env, state, off, size,
af86ca4e 3479 value_regno, insn_idx);
638f5b90 3480 else
61bd5218
JK
3481 err = check_stack_read(env, state, off, size,
3482 value_regno);
de8f3a83 3483 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 3484 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 3485 verbose(env, "cannot write into packet\n");
969bf05e
AS
3486 return -EACCES;
3487 }
4acf6c0b
BB
3488 if (t == BPF_WRITE && value_regno >= 0 &&
3489 is_pointer_value(env, value_regno)) {
61bd5218
JK
3490 verbose(env, "R%d leaks addr into packet\n",
3491 value_regno);
4acf6c0b
BB
3492 return -EACCES;
3493 }
9fd29c08 3494 err = check_packet_access(env, regno, off, size, false);
969bf05e 3495 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 3496 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
3497 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3498 if (t == BPF_WRITE && value_regno >= 0 &&
3499 is_pointer_value(env, value_regno)) {
3500 verbose(env, "R%d leaks addr into flow keys\n",
3501 value_regno);
3502 return -EACCES;
3503 }
3504
3505 err = check_flow_keys_access(env, off, size);
3506 if (!err && t == BPF_READ && value_regno >= 0)
3507 mark_reg_unknown(env, regs, value_regno);
46f8bc92 3508 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 3509 if (t == BPF_WRITE) {
46f8bc92
MKL
3510 verbose(env, "R%d cannot write into %s\n",
3511 regno, reg_type_str[reg->type]);
c64b7983
JS
3512 return -EACCES;
3513 }
5f456649 3514 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
3515 if (!err && value_regno >= 0)
3516 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
3517 } else if (reg->type == PTR_TO_TP_BUFFER) {
3518 err = check_tp_buffer_access(env, reg, regno, off, size);
3519 if (!err && t == BPF_READ && value_regno >= 0)
3520 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
3521 } else if (reg->type == PTR_TO_BTF_ID) {
3522 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3523 value_regno);
41c48f3a
AI
3524 } else if (reg->type == CONST_PTR_TO_MAP) {
3525 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3526 value_regno);
afbf21dc
YS
3527 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3528 if (t == BPF_WRITE) {
3529 verbose(env, "R%d cannot write into %s\n",
3530 regno, reg_type_str[reg->type]);
3531 return -EACCES;
3532 }
f6dfbe31
CIK
3533 err = check_buffer_access(env, reg, regno, off, size, false,
3534 "rdonly",
afbf21dc
YS
3535 &env->prog->aux->max_rdonly_access);
3536 if (!err && value_regno >= 0)
3537 mark_reg_unknown(env, regs, value_regno);
3538 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
3539 err = check_buffer_access(env, reg, regno, off, size, false,
3540 "rdwr",
afbf21dc
YS
3541 &env->prog->aux->max_rdwr_access);
3542 if (!err && t == BPF_READ && value_regno >= 0)
3543 mark_reg_unknown(env, regs, value_regno);
17a52670 3544 } else {
61bd5218
JK
3545 verbose(env, "R%d invalid mem access '%s'\n", regno,
3546 reg_type_str[reg->type]);
17a52670
AS
3547 return -EACCES;
3548 }
969bf05e 3549
f1174f77 3550 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 3551 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 3552 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 3553 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 3554 }
17a52670
AS
3555 return err;
3556}
3557
31fd8581 3558static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 3559{
17a52670
AS
3560 int err;
3561
3562 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3563 insn->imm != 0) {
61bd5218 3564 verbose(env, "BPF_XADD uses reserved fields\n");
17a52670
AS
3565 return -EINVAL;
3566 }
3567
3568 /* check src1 operand */
dc503a8a 3569 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
3570 if (err)
3571 return err;
3572
3573 /* check src2 operand */
dc503a8a 3574 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
3575 if (err)
3576 return err;
3577
6bdf6abc 3578 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 3579 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
3580 return -EACCES;
3581 }
3582
ca369602 3583 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 3584 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
3585 is_flow_key_reg(env, insn->dst_reg) ||
3586 is_sk_reg(env, insn->dst_reg)) {
ca369602 3587 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
2a159c6f
DB
3588 insn->dst_reg,
3589 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
3590 return -EACCES;
3591 }
3592
17a52670 3593 /* check whether atomic_add can read the memory */
31fd8581 3594 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3595 BPF_SIZE(insn->code), BPF_READ, -1, true);
17a52670
AS
3596 if (err)
3597 return err;
3598
3599 /* check whether atomic_add can write into the same memory */
31fd8581 3600 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
ca369602 3601 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
17a52670
AS
3602}
3603
2011fccf
AI
3604static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3605 int off, int access_size,
3606 bool zero_size_allowed)
3607{
3608 struct bpf_reg_state *reg = reg_state(env, regno);
3609
3610 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3611 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3612 if (tnum_is_const(reg->var_off)) {
3613 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3614 regno, off, access_size);
3615 } else {
3616 char tn_buf[48];
3617
3618 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3619 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3620 regno, tn_buf, access_size);
3621 }
3622 return -EACCES;
3623 }
3624 return 0;
3625}
3626
17a52670
AS
3627/* when register 'regno' is passed into function that will read 'access_size'
3628 * bytes from that pointer, make sure that it's within stack boundary
f1174f77
EC
3629 * and all elements of stack are initialized.
3630 * Unlike most pointer bounds-checking functions, this one doesn't take an
3631 * 'off' argument, so it has to add in reg->off itself.
17a52670 3632 */
58e2af8b 3633static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
3634 int access_size, bool zero_size_allowed,
3635 struct bpf_call_arg_meta *meta)
17a52670 3636{
2a159c6f 3637 struct bpf_reg_state *reg = reg_state(env, regno);
f4d7e40a 3638 struct bpf_func_state *state = func(env, reg);
f7cf25b2 3639 int err, min_off, max_off, i, j, slot, spi;
17a52670 3640
914cb781 3641 if (reg->type != PTR_TO_STACK) {
f1174f77 3642 /* Allow zero-byte read from NULL, regardless of pointer type */
8e2fe1d9 3643 if (zero_size_allowed && access_size == 0 &&
914cb781 3644 register_is_null(reg))
8e2fe1d9
DB
3645 return 0;
3646
61bd5218 3647 verbose(env, "R%d type=%s expected=%s\n", regno,
914cb781 3648 reg_type_str[reg->type],
8e2fe1d9 3649 reg_type_str[PTR_TO_STACK]);
17a52670 3650 return -EACCES;
8e2fe1d9 3651 }
17a52670 3652
2011fccf
AI
3653 if (tnum_is_const(reg->var_off)) {
3654 min_off = max_off = reg->var_off.value + reg->off;
3655 err = __check_stack_boundary(env, regno, min_off, access_size,
3656 zero_size_allowed);
3657 if (err)
3658 return err;
3659 } else {
088ec26d
AI
3660 /* Variable offset is prohibited for unprivileged mode for
3661 * simplicity since it requires corresponding support in
3662 * Spectre masking for stack ALU.
3663 * See also retrieve_ptr_limit().
3664 */
2c78ee89 3665 if (!env->bypass_spec_v1) {
088ec26d 3666 char tn_buf[48];
f1174f77 3667
088ec26d
AI
3668 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3669 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3670 regno, tn_buf);
3671 return -EACCES;
3672 }
f2bcd05e
AI
3673 /* Only initialized buffer on stack is allowed to be accessed
3674 * with variable offset. With uninitialized buffer it's hard to
3675 * guarantee that whole memory is marked as initialized on
3676 * helper return since specific bounds are unknown what may
3677 * cause uninitialized stack leaking.
3678 */
3679 if (meta && meta->raw_mode)
3680 meta = NULL;
3681
107c26a7
AI
3682 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3683 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3684 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3685 regno);
3686 return -EACCES;
3687 }
2011fccf 3688 min_off = reg->smin_value + reg->off;
107c26a7 3689 max_off = reg->smax_value + reg->off;
2011fccf
AI
3690 err = __check_stack_boundary(env, regno, min_off, access_size,
3691 zero_size_allowed);
107c26a7
AI
3692 if (err) {
3693 verbose(env, "R%d min value is outside of stack bound\n",
3694 regno);
2011fccf 3695 return err;
107c26a7 3696 }
2011fccf
AI
3697 err = __check_stack_boundary(env, regno, max_off, access_size,
3698 zero_size_allowed);
107c26a7
AI
3699 if (err) {
3700 verbose(env, "R%d max value is outside of stack bound\n",
3701 regno);
2011fccf 3702 return err;
107c26a7 3703 }
17a52670
AS
3704 }
3705
435faee1
DB
3706 if (meta && meta->raw_mode) {
3707 meta->access_size = access_size;
3708 meta->regno = regno;
3709 return 0;
3710 }
3711
2011fccf 3712 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
3713 u8 *stype;
3714
2011fccf 3715 slot = -i - 1;
638f5b90 3716 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
3717 if (state->allocated_stack <= slot)
3718 goto err;
3719 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3720 if (*stype == STACK_MISC)
3721 goto mark;
3722 if (*stype == STACK_ZERO) {
3723 /* helper can write anything into the stack */
3724 *stype = STACK_MISC;
3725 goto mark;
17a52670 3726 }
1d68f22b
YS
3727
3728 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3729 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3730 goto mark;
3731
f7cf25b2
AS
3732 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3733 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
f54c7898 3734 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
f7cf25b2
AS
3735 for (j = 0; j < BPF_REG_SIZE; j++)
3736 state->stack[spi].slot_type[j] = STACK_MISC;
3737 goto mark;
3738 }
3739
cc2b14d5 3740err:
2011fccf
AI
3741 if (tnum_is_const(reg->var_off)) {
3742 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3743 min_off, i - min_off, access_size);
3744 } else {
3745 char tn_buf[48];
3746
3747 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3748 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3749 tn_buf, i - min_off, access_size);
3750 }
cc2b14d5
AS
3751 return -EACCES;
3752mark:
3753 /* reading any byte out of 8-byte 'spill_slot' will cause
3754 * the whole slot to be marked as 'read'
3755 */
679c782d 3756 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
3757 state->stack[spi].spilled_ptr.parent,
3758 REG_LIVE_READ64);
17a52670 3759 }
2011fccf 3760 return update_stack_depth(env, state, min_off);
17a52670
AS
3761}
3762
06c1c049
GB
3763static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3764 int access_size, bool zero_size_allowed,
3765 struct bpf_call_arg_meta *meta)
3766{
638f5b90 3767 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 3768
f1174f77 3769 switch (reg->type) {
06c1c049 3770 case PTR_TO_PACKET:
de8f3a83 3771 case PTR_TO_PACKET_META:
9fd29c08
YS
3772 return check_packet_access(env, regno, reg->off, access_size,
3773 zero_size_allowed);
06c1c049 3774 case PTR_TO_MAP_VALUE:
591fe988
DB
3775 if (check_map_access_type(env, regno, reg->off, access_size,
3776 meta && meta->raw_mode ? BPF_WRITE :
3777 BPF_READ))
3778 return -EACCES;
9fd29c08
YS
3779 return check_map_access(env, regno, reg->off, access_size,
3780 zero_size_allowed);
457f4436
AN
3781 case PTR_TO_MEM:
3782 return check_mem_region_access(env, regno, reg->off,
3783 access_size, reg->mem_size,
3784 zero_size_allowed);
afbf21dc
YS
3785 case PTR_TO_RDONLY_BUF:
3786 if (meta && meta->raw_mode)
3787 return -EACCES;
3788 return check_buffer_access(env, reg, regno, reg->off,
3789 access_size, zero_size_allowed,
3790 "rdonly",
3791 &env->prog->aux->max_rdonly_access);
3792 case PTR_TO_RDWR_BUF:
3793 return check_buffer_access(env, reg, regno, reg->off,
3794 access_size, zero_size_allowed,
3795 "rdwr",
3796 &env->prog->aux->max_rdwr_access);
f1174f77 3797 default: /* scalar_value|ptr_to_stack or invalid ptr */
06c1c049
GB
3798 return check_stack_boundary(env, regno, access_size,
3799 zero_size_allowed, meta);
3800 }
3801}
3802
d83525ca
AS
3803/* Implementation details:
3804 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3805 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3806 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3807 * value_or_null->value transition, since the verifier only cares about
3808 * the range of access to valid map value pointer and doesn't care about actual
3809 * address of the map element.
3810 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3811 * reg->id > 0 after value_or_null->value transition. By doing so
3812 * two bpf_map_lookups will be considered two different pointers that
3813 * point to different bpf_spin_locks.
3814 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3815 * dead-locks.
3816 * Since only one bpf_spin_lock is allowed the checks are simpler than
3817 * reg_is_refcounted() logic. The verifier needs to remember only
3818 * one spin_lock instead of array of acquired_refs.
3819 * cur_state->active_spin_lock remembers which map value element got locked
3820 * and clears it after bpf_spin_unlock.
3821 */
3822static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3823 bool is_lock)
3824{
3825 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3826 struct bpf_verifier_state *cur = env->cur_state;
3827 bool is_const = tnum_is_const(reg->var_off);
3828 struct bpf_map *map = reg->map_ptr;
3829 u64 val = reg->var_off.value;
3830
3831 if (reg->type != PTR_TO_MAP_VALUE) {
3832 verbose(env, "R%d is not a pointer to map_value\n", regno);
3833 return -EINVAL;
3834 }
3835 if (!is_const) {
3836 verbose(env,
3837 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3838 regno);
3839 return -EINVAL;
3840 }
3841 if (!map->btf) {
3842 verbose(env,
3843 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3844 map->name);
3845 return -EINVAL;
3846 }
3847 if (!map_value_has_spin_lock(map)) {
3848 if (map->spin_lock_off == -E2BIG)
3849 verbose(env,
3850 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3851 map->name);
3852 else if (map->spin_lock_off == -ENOENT)
3853 verbose(env,
3854 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3855 map->name);
3856 else
3857 verbose(env,
3858 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3859 map->name);
3860 return -EINVAL;
3861 }
3862 if (map->spin_lock_off != val + reg->off) {
3863 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3864 val + reg->off);
3865 return -EINVAL;
3866 }
3867 if (is_lock) {
3868 if (cur->active_spin_lock) {
3869 verbose(env,
3870 "Locking two bpf_spin_locks are not allowed\n");
3871 return -EINVAL;
3872 }
3873 cur->active_spin_lock = reg->id;
3874 } else {
3875 if (!cur->active_spin_lock) {
3876 verbose(env, "bpf_spin_unlock without taking a lock\n");
3877 return -EINVAL;
3878 }
3879 if (cur->active_spin_lock != reg->id) {
3880 verbose(env, "bpf_spin_unlock of different lock\n");
3881 return -EINVAL;
3882 }
3883 cur->active_spin_lock = 0;
3884 }
3885 return 0;
3886}
3887
90133415
DB
3888static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3889{
3890 return type == ARG_PTR_TO_MEM ||
3891 type == ARG_PTR_TO_MEM_OR_NULL ||
3892 type == ARG_PTR_TO_UNINIT_MEM;
3893}
3894
3895static bool arg_type_is_mem_size(enum bpf_arg_type type)
3896{
3897 return type == ARG_CONST_SIZE ||
3898 type == ARG_CONST_SIZE_OR_ZERO;
3899}
3900
457f4436
AN
3901static bool arg_type_is_alloc_mem_ptr(enum bpf_arg_type type)
3902{
3903 return type == ARG_PTR_TO_ALLOC_MEM ||
3904 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
3905}
3906
3907static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3908{
3909 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3910}
3911
57c3bb72
AI
3912static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3913{
3914 return type == ARG_PTR_TO_INT ||
3915 type == ARG_PTR_TO_LONG;
3916}
3917
3918static int int_ptr_type_to_size(enum bpf_arg_type type)
3919{
3920 if (type == ARG_PTR_TO_INT)
3921 return sizeof(u32);
3922 else if (type == ARG_PTR_TO_LONG)
3923 return sizeof(u64);
3924
3925 return -EINVAL;
3926}
3927
912f442c
LB
3928static int resolve_map_arg_type(struct bpf_verifier_env *env,
3929 const struct bpf_call_arg_meta *meta,
3930 enum bpf_arg_type *arg_type)
3931{
3932 if (!meta->map_ptr) {
3933 /* kernel subsystem misconfigured verifier */
3934 verbose(env, "invalid map_ptr to access map->type\n");
3935 return -EACCES;
3936 }
3937
3938 switch (meta->map_ptr->map_type) {
3939 case BPF_MAP_TYPE_SOCKMAP:
3940 case BPF_MAP_TYPE_SOCKHASH:
3941 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
3942 *arg_type = ARG_PTR_TO_SOCKET;
3943 } else {
3944 verbose(env, "invalid arg_type for sockmap/sockhash\n");
3945 return -EINVAL;
3946 }
3947 break;
3948
3949 default:
3950 break;
3951 }
3952 return 0;
3953}
3954
af7ec138
YS
3955static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
3956 struct bpf_call_arg_meta *meta,
3957 const struct bpf_func_proto *fn)
17a52670 3958{
af7ec138 3959 u32 regno = BPF_REG_1 + arg;
638f5b90 3960 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6841de8b 3961 enum bpf_reg_type expected_type, type = reg->type;
af7ec138 3962 enum bpf_arg_type arg_type = fn->arg_type[arg];
17a52670
AS
3963 int err = 0;
3964
80f1d68c 3965 if (arg_type == ARG_DONTCARE)
17a52670
AS
3966 return 0;
3967
dc503a8a
EC
3968 err = check_reg_arg(env, regno, SRC_OP);
3969 if (err)
3970 return err;
17a52670 3971
1be7f75d
AS
3972 if (arg_type == ARG_ANYTHING) {
3973 if (is_pointer_value(env, regno)) {
61bd5218
JK
3974 verbose(env, "R%d leaks addr into helper function\n",
3975 regno);
1be7f75d
AS
3976 return -EACCES;
3977 }
80f1d68c 3978 return 0;
1be7f75d 3979 }
80f1d68c 3980
de8f3a83 3981 if (type_is_pkt_pointer(type) &&
3a0af8fd 3982 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 3983 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
3984 return -EACCES;
3985 }
3986
912f442c
LB
3987 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3988 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3989 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3990 err = resolve_map_arg_type(env, meta, &arg_type);
3991 if (err)
3992 return err;
3993 }
3994
8e2fe1d9 3995 if (arg_type == ARG_PTR_TO_MAP_KEY ||
2ea864c5 3996 arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
3997 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3998 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
17a52670 3999 expected_type = PTR_TO_STACK;
6ac99e8f
MKL
4000 if (register_is_null(reg) &&
4001 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
4002 /* final test in check_stack_boundary() */;
4003 else if (!type_is_pkt_pointer(type) &&
4004 type != PTR_TO_MAP_VALUE &&
4005 type != expected_type)
6841de8b 4006 goto err_type;
39f19ebb 4007 } else if (arg_type == ARG_CONST_SIZE ||
457f4436
AN
4008 arg_type == ARG_CONST_SIZE_OR_ZERO ||
4009 arg_type == ARG_CONST_ALLOC_SIZE_OR_ZERO) {
f1174f77
EC
4010 expected_type = SCALAR_VALUE;
4011 if (type != expected_type)
6841de8b 4012 goto err_type;
17a52670
AS
4013 } else if (arg_type == ARG_CONST_MAP_PTR) {
4014 expected_type = CONST_PTR_TO_MAP;
6841de8b
AS
4015 if (type != expected_type)
4016 goto err_type;
f318903c
DB
4017 } else if (arg_type == ARG_PTR_TO_CTX ||
4018 arg_type == ARG_PTR_TO_CTX_OR_NULL) {
608cd71a 4019 expected_type = PTR_TO_CTX;
f318903c
DB
4020 if (!(register_is_null(reg) &&
4021 arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
4022 if (type != expected_type)
4023 goto err_type;
4024 err = check_ctx_reg(env, reg, regno);
4025 if (err < 0)
4026 return err;
4027 }
46f8bc92
MKL
4028 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
4029 expected_type = PTR_TO_SOCK_COMMON;
4030 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
4031 if (!type_is_sk_pointer(type))
4032 goto err_type;
1b986589
MKL
4033 if (reg->ref_obj_id) {
4034 if (meta->ref_obj_id) {
4035 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4036 regno, reg->ref_obj_id,
4037 meta->ref_obj_id);
4038 return -EFAULT;
4039 }
4040 meta->ref_obj_id = reg->ref_obj_id;
fd978bf7 4041 }
e9ddbb77
JS
4042 } else if (arg_type == ARG_PTR_TO_SOCKET ||
4043 arg_type == ARG_PTR_TO_SOCKET_OR_NULL) {
6ac99e8f 4044 expected_type = PTR_TO_SOCKET;
e9ddbb77
JS
4045 if (!(register_is_null(reg) &&
4046 arg_type == ARG_PTR_TO_SOCKET_OR_NULL)) {
4047 if (type != expected_type)
4048 goto err_type;
4049 }
a7658e1a 4050 } else if (arg_type == ARG_PTR_TO_BTF_ID) {
faaf4a79
JO
4051 bool ids_match = false;
4052
a7658e1a
AS
4053 expected_type = PTR_TO_BTF_ID;
4054 if (type != expected_type)
4055 goto err_type;
af7ec138
YS
4056 if (!fn->check_btf_id) {
4057 if (reg->btf_id != meta->btf_id) {
faaf4a79
JO
4058 ids_match = btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4059 meta->btf_id);
4060 if (!ids_match) {
4061 verbose(env, "Helper has type %s got %s in R%d\n",
4062 kernel_type_name(meta->btf_id),
4063 kernel_type_name(reg->btf_id), regno);
4064 return -EACCES;
4065 }
af7ec138
YS
4066 }
4067 } else if (!fn->check_btf_id(reg->btf_id, arg)) {
4068 verbose(env, "Helper does not support %s in R%d\n",
a7658e1a
AS
4069 kernel_type_name(reg->btf_id), regno);
4070
4071 return -EACCES;
4072 }
faaf4a79 4073 if ((reg->off && !ids_match) || !tnum_is_const(reg->var_off) || reg->var_off.value) {
a7658e1a
AS
4074 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4075 regno);
4076 return -EACCES;
4077 }
d83525ca
AS
4078 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4079 if (meta->func_id == BPF_FUNC_spin_lock) {
4080 if (process_spin_lock(env, regno, true))
4081 return -EACCES;
4082 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4083 if (process_spin_lock(env, regno, false))
4084 return -EACCES;
4085 } else {
4086 verbose(env, "verifier internal error\n");
4087 return -EFAULT;
4088 }
90133415 4089 } else if (arg_type_is_mem_ptr(arg_type)) {
8e2fe1d9
DB
4090 expected_type = PTR_TO_STACK;
4091 /* One exception here. In case function allows for NULL to be
f1174f77 4092 * passed in as argument, it's a SCALAR_VALUE type. Final test
8e2fe1d9
DB
4093 * happens during stack boundary checking.
4094 */
914cb781 4095 if (register_is_null(reg) &&
457f4436
AN
4096 (arg_type == ARG_PTR_TO_MEM_OR_NULL ||
4097 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL))
6841de8b 4098 /* final test in check_stack_boundary() */;
de8f3a83
DB
4099 else if (!type_is_pkt_pointer(type) &&
4100 type != PTR_TO_MAP_VALUE &&
457f4436 4101 type != PTR_TO_MEM &&
afbf21dc
YS
4102 type != PTR_TO_RDONLY_BUF &&
4103 type != PTR_TO_RDWR_BUF &&
f1174f77 4104 type != expected_type)
6841de8b 4105 goto err_type;
39f19ebb 4106 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
457f4436
AN
4107 } else if (arg_type_is_alloc_mem_ptr(arg_type)) {
4108 expected_type = PTR_TO_MEM;
4109 if (register_is_null(reg) &&
4110 arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL)
4111 /* final test in check_stack_boundary() */;
4112 else if (type != expected_type)
4113 goto err_type;
4114 if (meta->ref_obj_id) {
4115 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4116 regno, reg->ref_obj_id,
4117 meta->ref_obj_id);
4118 return -EFAULT;
4119 }
4120 meta->ref_obj_id = reg->ref_obj_id;
57c3bb72
AI
4121 } else if (arg_type_is_int_ptr(arg_type)) {
4122 expected_type = PTR_TO_STACK;
4123 if (!type_is_pkt_pointer(type) &&
4124 type != PTR_TO_MAP_VALUE &&
4125 type != expected_type)
4126 goto err_type;
17a52670 4127 } else {
61bd5218 4128 verbose(env, "unsupported arg_type %d\n", arg_type);
17a52670
AS
4129 return -EFAULT;
4130 }
4131
17a52670
AS
4132 if (arg_type == ARG_CONST_MAP_PTR) {
4133 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4134 meta->map_ptr = reg->map_ptr;
17a52670
AS
4135 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4136 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4137 * check that [key, key + map->key_size) are within
4138 * stack limits and initialized
4139 */
33ff9823 4140 if (!meta->map_ptr) {
17a52670
AS
4141 /* in function declaration map_ptr must come before
4142 * map_key, so that it's verified and known before
4143 * we have to check map_key here. Otherwise it means
4144 * that kernel subsystem misconfigured verifier
4145 */
61bd5218 4146 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4147 return -EACCES;
4148 }
d71962f3
PC
4149 err = check_helper_mem_access(env, regno,
4150 meta->map_ptr->key_size, false,
4151 NULL);
2ea864c5 4152 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4153 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4154 !register_is_null(reg)) ||
2ea864c5 4155 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4156 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4157 * check [value, value + map->value_size) validity
4158 */
33ff9823 4159 if (!meta->map_ptr) {
17a52670 4160 /* kernel subsystem misconfigured verifier */
61bd5218 4161 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4162 return -EACCES;
4163 }
2ea864c5 4164 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4165 err = check_helper_mem_access(env, regno,
4166 meta->map_ptr->value_size, false,
2ea864c5 4167 meta);
90133415 4168 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 4169 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 4170
10060503
JF
4171 /* This is used to refine r0 return value bounds for helpers
4172 * that enforce this value as an upper bound on return values.
4173 * See do_refine_retval_range() for helpers that can refine
4174 * the return value. C type of helper is u32 so we pull register
4175 * bound from umax_value however, if negative verifier errors
4176 * out. Only upper bounds can be learned because retval is an
4177 * int type and negative retvals are allowed.
849fa506 4178 */
10060503 4179 meta->msize_max_value = reg->umax_value;
849fa506 4180
f1174f77
EC
4181 /* The register is SCALAR_VALUE; the access check
4182 * happens using its boundaries.
06c1c049 4183 */
f1174f77 4184 if (!tnum_is_const(reg->var_off))
06c1c049
GB
4185 /* For unprivileged variable accesses, disable raw
4186 * mode so that the program is required to
4187 * initialize all the memory that the helper could
4188 * just partially fill up.
4189 */
4190 meta = NULL;
4191
b03c9f9f 4192 if (reg->smin_value < 0) {
61bd5218 4193 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
4194 regno);
4195 return -EACCES;
4196 }
06c1c049 4197
b03c9f9f 4198 if (reg->umin_value == 0) {
f1174f77
EC
4199 err = check_helper_mem_access(env, regno - 1, 0,
4200 zero_size_allowed,
4201 meta);
06c1c049
GB
4202 if (err)
4203 return err;
06c1c049 4204 }
f1174f77 4205
b03c9f9f 4206 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 4207 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
4208 regno);
4209 return -EACCES;
4210 }
4211 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 4212 reg->umax_value,
f1174f77 4213 zero_size_allowed, meta);
b5dc0163
AS
4214 if (!err)
4215 err = mark_chain_precision(env, regno);
457f4436
AN
4216 } else if (arg_type_is_alloc_size(arg_type)) {
4217 if (!tnum_is_const(reg->var_off)) {
4218 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4219 regno);
4220 return -EACCES;
4221 }
4222 meta->mem_size = reg->var_off.value;
57c3bb72
AI
4223 } else if (arg_type_is_int_ptr(arg_type)) {
4224 int size = int_ptr_type_to_size(arg_type);
4225
4226 err = check_helper_mem_access(env, regno, size, false, meta);
4227 if (err)
4228 return err;
4229 err = check_ptr_alignment(env, reg, 0, size, true);
17a52670
AS
4230 }
4231
4232 return err;
6841de8b 4233err_type:
61bd5218 4234 verbose(env, "R%d type=%s expected=%s\n", regno,
6841de8b
AS
4235 reg_type_str[type], reg_type_str[expected_type]);
4236 return -EACCES;
17a52670
AS
4237}
4238
0126240f
LB
4239static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4240{
4241 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 4242 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
4243
4244 if (func_id != BPF_FUNC_map_update_elem)
4245 return false;
4246
4247 /* It's not possible to get access to a locked struct sock in these
4248 * contexts, so updating is safe.
4249 */
4250 switch (type) {
4251 case BPF_PROG_TYPE_TRACING:
4252 if (eatype == BPF_TRACE_ITER)
4253 return true;
4254 break;
4255 case BPF_PROG_TYPE_SOCKET_FILTER:
4256 case BPF_PROG_TYPE_SCHED_CLS:
4257 case BPF_PROG_TYPE_SCHED_ACT:
4258 case BPF_PROG_TYPE_XDP:
4259 case BPF_PROG_TYPE_SK_REUSEPORT:
4260 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4261 case BPF_PROG_TYPE_SK_LOOKUP:
4262 return true;
4263 default:
4264 break;
4265 }
4266
4267 verbose(env, "cannot update sockmap in this context\n");
4268 return false;
4269}
4270
e411901c
MF
4271static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4272{
4273 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4274}
4275
61bd5218
JK
4276static int check_map_func_compatibility(struct bpf_verifier_env *env,
4277 struct bpf_map *map, int func_id)
35578d79 4278{
35578d79
KX
4279 if (!map)
4280 return 0;
4281
6aff67c8
AS
4282 /* We need a two way check, first is from map perspective ... */
4283 switch (map->map_type) {
4284 case BPF_MAP_TYPE_PROG_ARRAY:
4285 if (func_id != BPF_FUNC_tail_call)
4286 goto error;
4287 break;
4288 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4289 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 4290 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 4291 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
4292 func_id != BPF_FUNC_perf_event_read_value &&
4293 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
4294 goto error;
4295 break;
457f4436
AN
4296 case BPF_MAP_TYPE_RINGBUF:
4297 if (func_id != BPF_FUNC_ringbuf_output &&
4298 func_id != BPF_FUNC_ringbuf_reserve &&
4299 func_id != BPF_FUNC_ringbuf_submit &&
4300 func_id != BPF_FUNC_ringbuf_discard &&
4301 func_id != BPF_FUNC_ringbuf_query)
4302 goto error;
4303 break;
6aff67c8
AS
4304 case BPF_MAP_TYPE_STACK_TRACE:
4305 if (func_id != BPF_FUNC_get_stackid)
4306 goto error;
4307 break;
4ed8ec52 4308 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 4309 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 4310 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
4311 goto error;
4312 break;
cd339431 4313 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 4314 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
4315 if (func_id != BPF_FUNC_get_local_storage)
4316 goto error;
4317 break;
546ac1ff 4318 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 4319 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
4320 if (func_id != BPF_FUNC_redirect_map &&
4321 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
4322 goto error;
4323 break;
fbfc504a
BT
4324 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4325 * appear.
4326 */
6710e112
JDB
4327 case BPF_MAP_TYPE_CPUMAP:
4328 if (func_id != BPF_FUNC_redirect_map)
4329 goto error;
4330 break;
fada7fdc
JL
4331 case BPF_MAP_TYPE_XSKMAP:
4332 if (func_id != BPF_FUNC_redirect_map &&
4333 func_id != BPF_FUNC_map_lookup_elem)
4334 goto error;
4335 break;
56f668df 4336 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 4337 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
4338 if (func_id != BPF_FUNC_map_lookup_elem)
4339 goto error;
16a43625 4340 break;
174a79ff
JF
4341 case BPF_MAP_TYPE_SOCKMAP:
4342 if (func_id != BPF_FUNC_sk_redirect_map &&
4343 func_id != BPF_FUNC_sock_map_update &&
4f738adb 4344 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4345 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 4346 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4347 func_id != BPF_FUNC_map_lookup_elem &&
4348 !may_update_sockmap(env, func_id))
174a79ff
JF
4349 goto error;
4350 break;
81110384
JF
4351 case BPF_MAP_TYPE_SOCKHASH:
4352 if (func_id != BPF_FUNC_sk_redirect_hash &&
4353 func_id != BPF_FUNC_sock_hash_update &&
4354 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 4355 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 4356 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
4357 func_id != BPF_FUNC_map_lookup_elem &&
4358 !may_update_sockmap(env, func_id))
81110384
JF
4359 goto error;
4360 break;
2dbb9b9e
MKL
4361 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4362 if (func_id != BPF_FUNC_sk_select_reuseport)
4363 goto error;
4364 break;
f1a2e44a
MV
4365 case BPF_MAP_TYPE_QUEUE:
4366 case BPF_MAP_TYPE_STACK:
4367 if (func_id != BPF_FUNC_map_peek_elem &&
4368 func_id != BPF_FUNC_map_pop_elem &&
4369 func_id != BPF_FUNC_map_push_elem)
4370 goto error;
4371 break;
6ac99e8f
MKL
4372 case BPF_MAP_TYPE_SK_STORAGE:
4373 if (func_id != BPF_FUNC_sk_storage_get &&
4374 func_id != BPF_FUNC_sk_storage_delete)
4375 goto error;
4376 break;
8ea63684
KS
4377 case BPF_MAP_TYPE_INODE_STORAGE:
4378 if (func_id != BPF_FUNC_inode_storage_get &&
4379 func_id != BPF_FUNC_inode_storage_delete)
4380 goto error;
4381 break;
6aff67c8
AS
4382 default:
4383 break;
4384 }
4385
4386 /* ... and second from the function itself. */
4387 switch (func_id) {
4388 case BPF_FUNC_tail_call:
4389 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4390 goto error;
e411901c
MF
4391 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4392 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
4393 return -EINVAL;
4394 }
6aff67c8
AS
4395 break;
4396 case BPF_FUNC_perf_event_read:
4397 case BPF_FUNC_perf_event_output:
908432ca 4398 case BPF_FUNC_perf_event_read_value:
a7658e1a 4399 case BPF_FUNC_skb_output:
d831ee84 4400 case BPF_FUNC_xdp_output:
6aff67c8
AS
4401 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4402 goto error;
4403 break;
4404 case BPF_FUNC_get_stackid:
4405 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4406 goto error;
4407 break;
60d20f91 4408 case BPF_FUNC_current_task_under_cgroup:
747ea55e 4409 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
4410 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4411 goto error;
4412 break;
97f91a7c 4413 case BPF_FUNC_redirect_map:
9c270af3 4414 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 4415 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
4416 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4417 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
4418 goto error;
4419 break;
174a79ff 4420 case BPF_FUNC_sk_redirect_map:
4f738adb 4421 case BPF_FUNC_msg_redirect_map:
81110384 4422 case BPF_FUNC_sock_map_update:
174a79ff
JF
4423 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4424 goto error;
4425 break;
81110384
JF
4426 case BPF_FUNC_sk_redirect_hash:
4427 case BPF_FUNC_msg_redirect_hash:
4428 case BPF_FUNC_sock_hash_update:
4429 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
4430 goto error;
4431 break;
cd339431 4432 case BPF_FUNC_get_local_storage:
b741f163
RG
4433 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4434 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
4435 goto error;
4436 break;
2dbb9b9e 4437 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
4438 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4439 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4440 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
4441 goto error;
4442 break;
f1a2e44a
MV
4443 case BPF_FUNC_map_peek_elem:
4444 case BPF_FUNC_map_pop_elem:
4445 case BPF_FUNC_map_push_elem:
4446 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4447 map->map_type != BPF_MAP_TYPE_STACK)
4448 goto error;
4449 break;
6ac99e8f
MKL
4450 case BPF_FUNC_sk_storage_get:
4451 case BPF_FUNC_sk_storage_delete:
4452 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4453 goto error;
4454 break;
8ea63684
KS
4455 case BPF_FUNC_inode_storage_get:
4456 case BPF_FUNC_inode_storage_delete:
4457 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4458 goto error;
4459 break;
6aff67c8
AS
4460 default:
4461 break;
35578d79
KX
4462 }
4463
4464 return 0;
6aff67c8 4465error:
61bd5218 4466 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 4467 map->map_type, func_id_name(func_id), func_id);
6aff67c8 4468 return -EINVAL;
35578d79
KX
4469}
4470
90133415 4471static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
4472{
4473 int count = 0;
4474
39f19ebb 4475 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4476 count++;
39f19ebb 4477 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4478 count++;
39f19ebb 4479 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4480 count++;
39f19ebb 4481 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 4482 count++;
39f19ebb 4483 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
4484 count++;
4485
90133415
DB
4486 /* We only support one arg being in raw mode at the moment,
4487 * which is sufficient for the helper functions we have
4488 * right now.
4489 */
4490 return count <= 1;
4491}
4492
4493static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4494 enum bpf_arg_type arg_next)
4495{
4496 return (arg_type_is_mem_ptr(arg_curr) &&
4497 !arg_type_is_mem_size(arg_next)) ||
4498 (!arg_type_is_mem_ptr(arg_curr) &&
4499 arg_type_is_mem_size(arg_next));
4500}
4501
4502static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4503{
4504 /* bpf_xxx(..., buf, len) call will access 'len'
4505 * bytes from memory 'buf'. Both arg types need
4506 * to be paired, so make sure there's no buggy
4507 * helper function specification.
4508 */
4509 if (arg_type_is_mem_size(fn->arg1_type) ||
4510 arg_type_is_mem_ptr(fn->arg5_type) ||
4511 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4512 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4513 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4514 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4515 return false;
4516
4517 return true;
4518}
4519
1b986589 4520static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
4521{
4522 int count = 0;
4523
1b986589 4524 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 4525 count++;
1b986589 4526 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 4527 count++;
1b986589 4528 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 4529 count++;
1b986589 4530 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 4531 count++;
1b986589 4532 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
4533 count++;
4534
1b986589
MKL
4535 /* A reference acquiring function cannot acquire
4536 * another refcounted ptr.
4537 */
64d85290 4538 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
4539 return false;
4540
fd978bf7
JS
4541 /* We only support one arg being unreferenced at the moment,
4542 * which is sufficient for the helper functions we have right now.
4543 */
4544 return count <= 1;
4545}
4546
1b986589 4547static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
4548{
4549 return check_raw_mode_ok(fn) &&
fd978bf7 4550 check_arg_pair_ok(fn) &&
1b986589 4551 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
4552}
4553
de8f3a83
DB
4554/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4555 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 4556 */
f4d7e40a
AS
4557static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4558 struct bpf_func_state *state)
969bf05e 4559{
58e2af8b 4560 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
4561 int i;
4562
4563 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 4564 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 4565 mark_reg_unknown(env, regs, i);
969bf05e 4566
f3709f69
JS
4567 bpf_for_each_spilled_reg(i, state, reg) {
4568 if (!reg)
969bf05e 4569 continue;
de8f3a83 4570 if (reg_is_pkt_pointer_any(reg))
f54c7898 4571 __mark_reg_unknown(env, reg);
969bf05e
AS
4572 }
4573}
4574
f4d7e40a
AS
4575static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4576{
4577 struct bpf_verifier_state *vstate = env->cur_state;
4578 int i;
4579
4580 for (i = 0; i <= vstate->curframe; i++)
4581 __clear_all_pkt_pointers(env, vstate->frame[i]);
4582}
4583
fd978bf7 4584static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
4585 struct bpf_func_state *state,
4586 int ref_obj_id)
fd978bf7
JS
4587{
4588 struct bpf_reg_state *regs = state->regs, *reg;
4589 int i;
4590
4591 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 4592 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
4593 mark_reg_unknown(env, regs, i);
4594
4595 bpf_for_each_spilled_reg(i, state, reg) {
4596 if (!reg)
4597 continue;
1b986589 4598 if (reg->ref_obj_id == ref_obj_id)
f54c7898 4599 __mark_reg_unknown(env, reg);
fd978bf7
JS
4600 }
4601}
4602
4603/* The pointer with the specified id has released its reference to kernel
4604 * resources. Identify all copies of the same pointer and clear the reference.
4605 */
4606static int release_reference(struct bpf_verifier_env *env,
1b986589 4607 int ref_obj_id)
fd978bf7
JS
4608{
4609 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 4610 int err;
fd978bf7
JS
4611 int i;
4612
1b986589
MKL
4613 err = release_reference_state(cur_func(env), ref_obj_id);
4614 if (err)
4615 return err;
4616
fd978bf7 4617 for (i = 0; i <= vstate->curframe; i++)
1b986589 4618 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 4619
1b986589 4620 return 0;
fd978bf7
JS
4621}
4622
51c39bb1
AS
4623static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4624 struct bpf_reg_state *regs)
4625{
4626 int i;
4627
4628 /* after the call registers r0 - r5 were scratched */
4629 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4630 mark_reg_not_init(env, regs, caller_saved[i]);
4631 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4632 }
4633}
4634
f4d7e40a
AS
4635static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4636 int *insn_idx)
4637{
4638 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 4639 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 4640 struct bpf_func_state *caller, *callee;
fd978bf7 4641 int i, err, subprog, target_insn;
51c39bb1 4642 bool is_global = false;
f4d7e40a 4643
aada9ce6 4644 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 4645 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 4646 state->curframe + 2);
f4d7e40a
AS
4647 return -E2BIG;
4648 }
4649
4650 target_insn = *insn_idx + insn->imm;
4651 subprog = find_subprog(env, target_insn + 1);
4652 if (subprog < 0) {
4653 verbose(env, "verifier bug. No program starts at insn %d\n",
4654 target_insn + 1);
4655 return -EFAULT;
4656 }
4657
4658 caller = state->frame[state->curframe];
4659 if (state->frame[state->curframe + 1]) {
4660 verbose(env, "verifier bug. Frame %d already allocated\n",
4661 state->curframe + 1);
4662 return -EFAULT;
4663 }
4664
51c39bb1
AS
4665 func_info_aux = env->prog->aux->func_info_aux;
4666 if (func_info_aux)
4667 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4668 err = btf_check_func_arg_match(env, subprog, caller->regs);
4669 if (err == -EFAULT)
4670 return err;
4671 if (is_global) {
4672 if (err) {
4673 verbose(env, "Caller passes invalid args into func#%d\n",
4674 subprog);
4675 return err;
4676 } else {
4677 if (env->log.level & BPF_LOG_LEVEL)
4678 verbose(env,
4679 "Func#%d is global and valid. Skipping.\n",
4680 subprog);
4681 clear_caller_saved_regs(env, caller->regs);
4682
4683 /* All global functions return SCALAR_VALUE */
4684 mark_reg_unknown(env, caller->regs, BPF_REG_0);
4685
4686 /* continue with next insn after call */
4687 return 0;
4688 }
4689 }
4690
f4d7e40a
AS
4691 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4692 if (!callee)
4693 return -ENOMEM;
4694 state->frame[state->curframe + 1] = callee;
4695
4696 /* callee cannot access r0, r6 - r9 for reading and has to write
4697 * into its own stack before reading from it.
4698 * callee can read/write into caller's stack
4699 */
4700 init_func_state(env, callee,
4701 /* remember the callsite, it will be used by bpf_exit */
4702 *insn_idx /* callsite */,
4703 state->curframe + 1 /* frameno within this callchain */,
f910cefa 4704 subprog /* subprog number within this prog */);
f4d7e40a 4705
fd978bf7
JS
4706 /* Transfer references to the callee */
4707 err = transfer_reference_state(callee, caller);
4708 if (err)
4709 return err;
4710
679c782d
EC
4711 /* copy r1 - r5 args that callee can access. The copy includes parent
4712 * pointers, which connects us up to the liveness chain
4713 */
f4d7e40a
AS
4714 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4715 callee->regs[i] = caller->regs[i];
4716
51c39bb1 4717 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
4718
4719 /* only increment it after check_reg_arg() finished */
4720 state->curframe++;
4721
4722 /* and go analyze first insn of the callee */
4723 *insn_idx = target_insn;
4724
06ee7115 4725 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4726 verbose(env, "caller:\n");
4727 print_verifier_state(env, caller);
4728 verbose(env, "callee:\n");
4729 print_verifier_state(env, callee);
4730 }
4731 return 0;
4732}
4733
4734static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4735{
4736 struct bpf_verifier_state *state = env->cur_state;
4737 struct bpf_func_state *caller, *callee;
4738 struct bpf_reg_state *r0;
fd978bf7 4739 int err;
f4d7e40a
AS
4740
4741 callee = state->frame[state->curframe];
4742 r0 = &callee->regs[BPF_REG_0];
4743 if (r0->type == PTR_TO_STACK) {
4744 /* technically it's ok to return caller's stack pointer
4745 * (or caller's caller's pointer) back to the caller,
4746 * since these pointers are valid. Only current stack
4747 * pointer will be invalid as soon as function exits,
4748 * but let's be conservative
4749 */
4750 verbose(env, "cannot return stack pointer to the caller\n");
4751 return -EINVAL;
4752 }
4753
4754 state->curframe--;
4755 caller = state->frame[state->curframe];
4756 /* return to the caller whatever r0 had in the callee */
4757 caller->regs[BPF_REG_0] = *r0;
4758
fd978bf7
JS
4759 /* Transfer references to the caller */
4760 err = transfer_reference_state(caller, callee);
4761 if (err)
4762 return err;
4763
f4d7e40a 4764 *insn_idx = callee->callsite + 1;
06ee7115 4765 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
4766 verbose(env, "returning from callee:\n");
4767 print_verifier_state(env, callee);
4768 verbose(env, "to caller at %d:\n", *insn_idx);
4769 print_verifier_state(env, caller);
4770 }
4771 /* clear everything in the callee */
4772 free_func_state(callee);
4773 state->frame[state->curframe + 1] = NULL;
4774 return 0;
4775}
4776
849fa506
YS
4777static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4778 int func_id,
4779 struct bpf_call_arg_meta *meta)
4780{
4781 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4782
4783 if (ret_type != RET_INTEGER ||
4784 (func_id != BPF_FUNC_get_stack &&
47cc0ed5
DB
4785 func_id != BPF_FUNC_probe_read_str &&
4786 func_id != BPF_FUNC_probe_read_kernel_str &&
4787 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
4788 return;
4789
10060503 4790 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 4791 ret_reg->s32_max_value = meta->msize_max_value;
849fa506
YS
4792 __reg_deduce_bounds(ret_reg);
4793 __reg_bound_offset(ret_reg);
10060503 4794 __update_reg_bounds(ret_reg);
849fa506
YS
4795}
4796
c93552c4
DB
4797static int
4798record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4799 int func_id, int insn_idx)
4800{
4801 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 4802 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
4803
4804 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
4805 func_id != BPF_FUNC_map_lookup_elem &&
4806 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
4807 func_id != BPF_FUNC_map_delete_elem &&
4808 func_id != BPF_FUNC_map_push_elem &&
4809 func_id != BPF_FUNC_map_pop_elem &&
4810 func_id != BPF_FUNC_map_peek_elem)
c93552c4 4811 return 0;
09772d92 4812
591fe988 4813 if (map == NULL) {
c93552c4
DB
4814 verbose(env, "kernel subsystem misconfigured verifier\n");
4815 return -EINVAL;
4816 }
4817
591fe988
DB
4818 /* In case of read-only, some additional restrictions
4819 * need to be applied in order to prevent altering the
4820 * state of the map from program side.
4821 */
4822 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4823 (func_id == BPF_FUNC_map_delete_elem ||
4824 func_id == BPF_FUNC_map_update_elem ||
4825 func_id == BPF_FUNC_map_push_elem ||
4826 func_id == BPF_FUNC_map_pop_elem)) {
4827 verbose(env, "write into map forbidden\n");
4828 return -EACCES;
4829 }
4830
d2e4c1e6 4831 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 4832 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 4833 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 4834 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 4835 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 4836 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
4837 return 0;
4838}
4839
d2e4c1e6
DB
4840static int
4841record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4842 int func_id, int insn_idx)
4843{
4844 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4845 struct bpf_reg_state *regs = cur_regs(env), *reg;
4846 struct bpf_map *map = meta->map_ptr;
4847 struct tnum range;
4848 u64 val;
cc52d914 4849 int err;
d2e4c1e6
DB
4850
4851 if (func_id != BPF_FUNC_tail_call)
4852 return 0;
4853 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4854 verbose(env, "kernel subsystem misconfigured verifier\n");
4855 return -EINVAL;
4856 }
4857
4858 range = tnum_range(0, map->max_entries - 1);
4859 reg = &regs[BPF_REG_3];
4860
4861 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4862 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4863 return 0;
4864 }
4865
cc52d914
DB
4866 err = mark_chain_precision(env, BPF_REG_3);
4867 if (err)
4868 return err;
4869
d2e4c1e6
DB
4870 val = reg->var_off.value;
4871 if (bpf_map_key_unseen(aux))
4872 bpf_map_key_store(aux, val);
4873 else if (!bpf_map_key_poisoned(aux) &&
4874 bpf_map_key_immediate(aux) != val)
4875 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4876 return 0;
4877}
4878
fd978bf7
JS
4879static int check_reference_leak(struct bpf_verifier_env *env)
4880{
4881 struct bpf_func_state *state = cur_func(env);
4882 int i;
4883
4884 for (i = 0; i < state->acquired_refs; i++) {
4885 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4886 state->refs[i].id, state->refs[i].insn_idx);
4887 }
4888 return state->acquired_refs ? -EINVAL : 0;
4889}
4890
f4d7e40a 4891static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 4892{
17a52670 4893 const struct bpf_func_proto *fn = NULL;
638f5b90 4894 struct bpf_reg_state *regs;
33ff9823 4895 struct bpf_call_arg_meta meta;
969bf05e 4896 bool changes_data;
17a52670
AS
4897 int i, err;
4898
4899 /* find function prototype */
4900 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
4901 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4902 func_id);
17a52670
AS
4903 return -EINVAL;
4904 }
4905
00176a34 4906 if (env->ops->get_func_proto)
5e43f899 4907 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 4908 if (!fn) {
61bd5218
JK
4909 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4910 func_id);
17a52670
AS
4911 return -EINVAL;
4912 }
4913
4914 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 4915 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 4916 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
4917 return -EINVAL;
4918 }
4919
eae2e83e
JO
4920 if (fn->allowed && !fn->allowed(env->prog)) {
4921 verbose(env, "helper call is not allowed in probe\n");
4922 return -EINVAL;
4923 }
4924
04514d13 4925 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 4926 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
4927 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4928 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4929 func_id_name(func_id), func_id);
4930 return -EINVAL;
4931 }
969bf05e 4932
33ff9823 4933 memset(&meta, 0, sizeof(meta));
36bbef52 4934 meta.pkt_access = fn->pkt_access;
33ff9823 4935
1b986589 4936 err = check_func_proto(fn, func_id);
435faee1 4937 if (err) {
61bd5218 4938 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 4939 func_id_name(func_id), func_id);
435faee1
DB
4940 return err;
4941 }
4942
d83525ca 4943 meta.func_id = func_id;
17a52670 4944 /* check args */
a7658e1a 4945 for (i = 0; i < 5; i++) {
af7ec138
YS
4946 if (!fn->check_btf_id) {
4947 err = btf_resolve_helper_id(&env->log, fn, i);
4948 if (err > 0)
4949 meta.btf_id = err;
4950 }
4951 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
4952 if (err)
4953 return err;
4954 }
17a52670 4955
c93552c4
DB
4956 err = record_func_map(env, &meta, func_id, insn_idx);
4957 if (err)
4958 return err;
4959
d2e4c1e6
DB
4960 err = record_func_key(env, &meta, func_id, insn_idx);
4961 if (err)
4962 return err;
4963
435faee1
DB
4964 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4965 * is inferred from register state.
4966 */
4967 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
4968 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4969 BPF_WRITE, -1, false);
435faee1
DB
4970 if (err)
4971 return err;
4972 }
4973
fd978bf7
JS
4974 if (func_id == BPF_FUNC_tail_call) {
4975 err = check_reference_leak(env);
4976 if (err) {
4977 verbose(env, "tail_call would lead to reference leak\n");
4978 return err;
4979 }
4980 } else if (is_release_function(func_id)) {
1b986589 4981 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
4982 if (err) {
4983 verbose(env, "func %s#%d reference has not been acquired before\n",
4984 func_id_name(func_id), func_id);
fd978bf7 4985 return err;
46f8bc92 4986 }
fd978bf7
JS
4987 }
4988
638f5b90 4989 regs = cur_regs(env);
cd339431
RG
4990
4991 /* check that flags argument in get_local_storage(map, flags) is 0,
4992 * this is required because get_local_storage() can't return an error.
4993 */
4994 if (func_id == BPF_FUNC_get_local_storage &&
4995 !register_is_null(&regs[BPF_REG_2])) {
4996 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4997 return -EINVAL;
4998 }
4999
17a52670 5000 /* reset caller saved regs */
dc503a8a 5001 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 5002 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
5003 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5004 }
17a52670 5005
5327ed3d
JW
5006 /* helper call returns 64-bit value. */
5007 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5008
dc503a8a 5009 /* update return register (already marked as written above) */
17a52670 5010 if (fn->ret_type == RET_INTEGER) {
f1174f77 5011 /* sets type to SCALAR_VALUE */
61bd5218 5012 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
5013 } else if (fn->ret_type == RET_VOID) {
5014 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
5015 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5016 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 5017 /* There is no offset yet applied, variable or fixed */
61bd5218 5018 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
5019 /* remember map_ptr, so that check_map_access()
5020 * can check 'value_size' boundary of memory access
5021 * to map element returned from bpf_map_lookup_elem()
5022 */
33ff9823 5023 if (meta.map_ptr == NULL) {
61bd5218
JK
5024 verbose(env,
5025 "kernel subsystem misconfigured verifier\n");
17a52670
AS
5026 return -EINVAL;
5027 }
33ff9823 5028 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
5029 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5030 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
5031 if (map_value_has_spin_lock(meta.map_ptr))
5032 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
5033 } else {
5034 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5035 regs[BPF_REG_0].id = ++env->id_gen;
5036 }
c64b7983
JS
5037 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5038 mark_reg_known_zero(env, regs, BPF_REG_0);
5039 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
0f3adc28 5040 regs[BPF_REG_0].id = ++env->id_gen;
85a51f8c
LB
5041 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5042 mark_reg_known_zero(env, regs, BPF_REG_0);
5043 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5044 regs[BPF_REG_0].id = ++env->id_gen;
655a51e5
MKL
5045 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5046 mark_reg_known_zero(env, regs, BPF_REG_0);
5047 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5048 regs[BPF_REG_0].id = ++env->id_gen;
457f4436
AN
5049 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5050 mark_reg_known_zero(env, regs, BPF_REG_0);
5051 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5052 regs[BPF_REG_0].id = ++env->id_gen;
5053 regs[BPF_REG_0].mem_size = meta.mem_size;
af7ec138
YS
5054 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5055 int ret_btf_id;
5056
5057 mark_reg_known_zero(env, regs, BPF_REG_0);
5058 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5059 ret_btf_id = *fn->ret_btf_id;
5060 if (ret_btf_id == 0) {
5061 verbose(env, "invalid return type %d of func %s#%d\n",
5062 fn->ret_type, func_id_name(func_id), func_id);
5063 return -EINVAL;
5064 }
5065 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 5066 } else {
61bd5218 5067 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 5068 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
5069 return -EINVAL;
5070 }
04fd61ab 5071
0f3adc28 5072 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
5073 /* For release_reference() */
5074 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 5075 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
5076 int id = acquire_reference_state(env, insn_idx);
5077
5078 if (id < 0)
5079 return id;
5080 /* For mark_ptr_or_null_reg() */
5081 regs[BPF_REG_0].id = id;
5082 /* For release_reference() */
5083 regs[BPF_REG_0].ref_obj_id = id;
5084 }
1b986589 5085
849fa506
YS
5086 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5087
61bd5218 5088 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
5089 if (err)
5090 return err;
04fd61ab 5091
fa28dcb8
SL
5092 if ((func_id == BPF_FUNC_get_stack ||
5093 func_id == BPF_FUNC_get_task_stack) &&
5094 !env->prog->has_callchain_buf) {
c195651e
YS
5095 const char *err_str;
5096
5097#ifdef CONFIG_PERF_EVENTS
5098 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5099 err_str = "cannot get callchain buffer for func %s#%d\n";
5100#else
5101 err = -ENOTSUPP;
5102 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5103#endif
5104 if (err) {
5105 verbose(env, err_str, func_id_name(func_id), func_id);
5106 return err;
5107 }
5108
5109 env->prog->has_callchain_buf = true;
5110 }
5111
5d99cb2c
SL
5112 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5113 env->prog->call_get_stack = true;
5114
969bf05e
AS
5115 if (changes_data)
5116 clear_all_pkt_pointers(env);
5117 return 0;
5118}
5119
b03c9f9f
EC
5120static bool signed_add_overflows(s64 a, s64 b)
5121{
5122 /* Do the add in u64, where overflow is well-defined */
5123 s64 res = (s64)((u64)a + (u64)b);
5124
5125 if (b < 0)
5126 return res > a;
5127 return res < a;
5128}
5129
3f50f132
JF
5130static bool signed_add32_overflows(s64 a, s64 b)
5131{
5132 /* Do the add in u32, where overflow is well-defined */
5133 s32 res = (s32)((u32)a + (u32)b);
5134
5135 if (b < 0)
5136 return res > a;
5137 return res < a;
5138}
5139
5140static bool signed_sub_overflows(s32 a, s32 b)
b03c9f9f
EC
5141{
5142 /* Do the sub in u64, where overflow is well-defined */
5143 s64 res = (s64)((u64)a - (u64)b);
5144
5145 if (b < 0)
5146 return res < a;
5147 return res > a;
969bf05e
AS
5148}
5149
3f50f132
JF
5150static bool signed_sub32_overflows(s32 a, s32 b)
5151{
5152 /* Do the sub in u64, where overflow is well-defined */
5153 s32 res = (s32)((u32)a - (u32)b);
5154
5155 if (b < 0)
5156 return res < a;
5157 return res > a;
5158}
5159
bb7f0f98
AS
5160static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5161 const struct bpf_reg_state *reg,
5162 enum bpf_reg_type type)
5163{
5164 bool known = tnum_is_const(reg->var_off);
5165 s64 val = reg->var_off.value;
5166 s64 smin = reg->smin_value;
5167
5168 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5169 verbose(env, "math between %s pointer and %lld is not allowed\n",
5170 reg_type_str[type], val);
5171 return false;
5172 }
5173
5174 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5175 verbose(env, "%s pointer offset %d is not allowed\n",
5176 reg_type_str[type], reg->off);
5177 return false;
5178 }
5179
5180 if (smin == S64_MIN) {
5181 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5182 reg_type_str[type]);
5183 return false;
5184 }
5185
5186 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5187 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5188 smin, reg_type_str[type]);
5189 return false;
5190 }
5191
5192 return true;
5193}
5194
979d63d5
DB
5195static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5196{
5197 return &env->insn_aux_data[env->insn_idx];
5198}
5199
5200static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5201 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5202{
5203 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5204 (opcode == BPF_SUB && !off_is_neg);
5205 u32 off;
5206
5207 switch (ptr_reg->type) {
5208 case PTR_TO_STACK:
088ec26d
AI
5209 /* Indirect variable offset stack access is prohibited in
5210 * unprivileged mode so it's not handled here.
5211 */
979d63d5
DB
5212 off = ptr_reg->off + ptr_reg->var_off.value;
5213 if (mask_to_left)
5214 *ptr_limit = MAX_BPF_STACK + off;
5215 else
5216 *ptr_limit = -off;
5217 return 0;
5218 case PTR_TO_MAP_VALUE:
5219 if (mask_to_left) {
5220 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5221 } else {
5222 off = ptr_reg->smin_value + ptr_reg->off;
5223 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5224 }
5225 return 0;
5226 default:
5227 return -EINVAL;
5228 }
5229}
5230
d3bd7413
DB
5231static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5232 const struct bpf_insn *insn)
5233{
2c78ee89 5234 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
5235}
5236
5237static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5238 u32 alu_state, u32 alu_limit)
5239{
5240 /* If we arrived here from different branches with different
5241 * state or limits to sanitize, then this won't work.
5242 */
5243 if (aux->alu_state &&
5244 (aux->alu_state != alu_state ||
5245 aux->alu_limit != alu_limit))
5246 return -EACCES;
5247
5248 /* Corresponding fixup done in fixup_bpf_calls(). */
5249 aux->alu_state = alu_state;
5250 aux->alu_limit = alu_limit;
5251 return 0;
5252}
5253
5254static int sanitize_val_alu(struct bpf_verifier_env *env,
5255 struct bpf_insn *insn)
5256{
5257 struct bpf_insn_aux_data *aux = cur_aux(env);
5258
5259 if (can_skip_alu_sanitation(env, insn))
5260 return 0;
5261
5262 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5263}
5264
979d63d5
DB
5265static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5266 struct bpf_insn *insn,
5267 const struct bpf_reg_state *ptr_reg,
5268 struct bpf_reg_state *dst_reg,
5269 bool off_is_neg)
5270{
5271 struct bpf_verifier_state *vstate = env->cur_state;
5272 struct bpf_insn_aux_data *aux = cur_aux(env);
5273 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5274 u8 opcode = BPF_OP(insn->code);
5275 u32 alu_state, alu_limit;
5276 struct bpf_reg_state tmp;
5277 bool ret;
5278
d3bd7413 5279 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
5280 return 0;
5281
5282 /* We already marked aux for masking from non-speculative
5283 * paths, thus we got here in the first place. We only care
5284 * to explore bad access from here.
5285 */
5286 if (vstate->speculative)
5287 goto do_sim;
5288
5289 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5290 alu_state |= ptr_is_dst_reg ?
5291 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5292
5293 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5294 return 0;
d3bd7413 5295 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 5296 return -EACCES;
979d63d5
DB
5297do_sim:
5298 /* Simulate and find potential out-of-bounds access under
5299 * speculative execution from truncation as a result of
5300 * masking when off was not within expected range. If off
5301 * sits in dst, then we temporarily need to move ptr there
5302 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5303 * for cases where we use K-based arithmetic in one direction
5304 * and truncated reg-based in the other in order to explore
5305 * bad access.
5306 */
5307 if (!ptr_is_dst_reg) {
5308 tmp = *dst_reg;
5309 *dst_reg = *ptr_reg;
5310 }
5311 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 5312 if (!ptr_is_dst_reg && ret)
979d63d5
DB
5313 *dst_reg = tmp;
5314 return !ret ? -EFAULT : 0;
5315}
5316
f1174f77 5317/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
5318 * Caller should also handle BPF_MOV case separately.
5319 * If we return -EACCES, caller may want to try again treating pointer as a
5320 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5321 */
5322static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5323 struct bpf_insn *insn,
5324 const struct bpf_reg_state *ptr_reg,
5325 const struct bpf_reg_state *off_reg)
969bf05e 5326{
f4d7e40a
AS
5327 struct bpf_verifier_state *vstate = env->cur_state;
5328 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5329 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 5330 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
5331 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5332 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5333 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5334 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 5335 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 5336 u8 opcode = BPF_OP(insn->code);
979d63d5 5337 int ret;
969bf05e 5338
f1174f77 5339 dst_reg = &regs[dst];
969bf05e 5340
6f16101e
DB
5341 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5342 smin_val > smax_val || umin_val > umax_val) {
5343 /* Taint dst register if offset had invalid bounds derived from
5344 * e.g. dead branches.
5345 */
f54c7898 5346 __mark_reg_unknown(env, dst_reg);
6f16101e 5347 return 0;
f1174f77
EC
5348 }
5349
5350 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5351 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
5352 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5353 __mark_reg_unknown(env, dst_reg);
5354 return 0;
5355 }
5356
82abbf8d
AS
5357 verbose(env,
5358 "R%d 32-bit pointer arithmetic prohibited\n",
5359 dst);
f1174f77 5360 return -EACCES;
969bf05e
AS
5361 }
5362
aad2eeaf
JS
5363 switch (ptr_reg->type) {
5364 case PTR_TO_MAP_VALUE_OR_NULL:
5365 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5366 dst, reg_type_str[ptr_reg->type]);
f1174f77 5367 return -EACCES;
aad2eeaf 5368 case CONST_PTR_TO_MAP:
7c696732
YS
5369 /* smin_val represents the known value */
5370 if (known && smin_val == 0 && opcode == BPF_ADD)
5371 break;
5372 /* fall-through */
aad2eeaf 5373 case PTR_TO_PACKET_END:
c64b7983
JS
5374 case PTR_TO_SOCKET:
5375 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
5376 case PTR_TO_SOCK_COMMON:
5377 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
5378 case PTR_TO_TCP_SOCK:
5379 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 5380 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
5381 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5382 dst, reg_type_str[ptr_reg->type]);
f1174f77 5383 return -EACCES;
9d7eceed
DB
5384 case PTR_TO_MAP_VALUE:
5385 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5386 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5387 off_reg == dst_reg ? dst : src);
5388 return -EACCES;
5389 }
5390 /* fall-through */
aad2eeaf
JS
5391 default:
5392 break;
f1174f77
EC
5393 }
5394
5395 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5396 * The id may be overwritten later if we create a new variable offset.
969bf05e 5397 */
f1174f77
EC
5398 dst_reg->type = ptr_reg->type;
5399 dst_reg->id = ptr_reg->id;
969bf05e 5400
bb7f0f98
AS
5401 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5402 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5403 return -EINVAL;
5404
3f50f132
JF
5405 /* pointer types do not carry 32-bit bounds at the moment. */
5406 __mark_reg32_unbounded(dst_reg);
5407
f1174f77
EC
5408 switch (opcode) {
5409 case BPF_ADD:
979d63d5
DB
5410 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5411 if (ret < 0) {
5412 verbose(env, "R%d tried to add from different maps or paths\n", dst);
5413 return ret;
5414 }
f1174f77
EC
5415 /* We can take a fixed offset as long as it doesn't overflow
5416 * the s32 'off' field
969bf05e 5417 */
b03c9f9f
EC
5418 if (known && (ptr_reg->off + smin_val ==
5419 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 5420 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
5421 dst_reg->smin_value = smin_ptr;
5422 dst_reg->smax_value = smax_ptr;
5423 dst_reg->umin_value = umin_ptr;
5424 dst_reg->umax_value = umax_ptr;
f1174f77 5425 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 5426 dst_reg->off = ptr_reg->off + smin_val;
0962590e 5427 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5428 break;
5429 }
f1174f77
EC
5430 /* A new variable offset is created. Note that off_reg->off
5431 * == 0, since it's a scalar.
5432 * dst_reg gets the pointer type and since some positive
5433 * integer value was added to the pointer, give it a new 'id'
5434 * if it's a PTR_TO_PACKET.
5435 * this creates a new 'base' pointer, off_reg (variable) gets
5436 * added into the variable offset, and we copy the fixed offset
5437 * from ptr_reg.
969bf05e 5438 */
b03c9f9f
EC
5439 if (signed_add_overflows(smin_ptr, smin_val) ||
5440 signed_add_overflows(smax_ptr, smax_val)) {
5441 dst_reg->smin_value = S64_MIN;
5442 dst_reg->smax_value = S64_MAX;
5443 } else {
5444 dst_reg->smin_value = smin_ptr + smin_val;
5445 dst_reg->smax_value = smax_ptr + smax_val;
5446 }
5447 if (umin_ptr + umin_val < umin_ptr ||
5448 umax_ptr + umax_val < umax_ptr) {
5449 dst_reg->umin_value = 0;
5450 dst_reg->umax_value = U64_MAX;
5451 } else {
5452 dst_reg->umin_value = umin_ptr + umin_val;
5453 dst_reg->umax_value = umax_ptr + umax_val;
5454 }
f1174f77
EC
5455 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5456 dst_reg->off = ptr_reg->off;
0962590e 5457 dst_reg->raw = ptr_reg->raw;
de8f3a83 5458 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5459 dst_reg->id = ++env->id_gen;
5460 /* something was added to pkt_ptr, set range to zero */
0962590e 5461 dst_reg->raw = 0;
f1174f77
EC
5462 }
5463 break;
5464 case BPF_SUB:
979d63d5
DB
5465 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5466 if (ret < 0) {
5467 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5468 return ret;
5469 }
f1174f77
EC
5470 if (dst_reg == off_reg) {
5471 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
5472 verbose(env, "R%d tried to subtract pointer from scalar\n",
5473 dst);
f1174f77
EC
5474 return -EACCES;
5475 }
5476 /* We don't allow subtraction from FP, because (according to
5477 * test_verifier.c test "invalid fp arithmetic", JITs might not
5478 * be able to deal with it.
969bf05e 5479 */
f1174f77 5480 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
5481 verbose(env, "R%d subtraction from stack pointer prohibited\n",
5482 dst);
f1174f77
EC
5483 return -EACCES;
5484 }
b03c9f9f
EC
5485 if (known && (ptr_reg->off - smin_val ==
5486 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 5487 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
5488 dst_reg->smin_value = smin_ptr;
5489 dst_reg->smax_value = smax_ptr;
5490 dst_reg->umin_value = umin_ptr;
5491 dst_reg->umax_value = umax_ptr;
f1174f77
EC
5492 dst_reg->var_off = ptr_reg->var_off;
5493 dst_reg->id = ptr_reg->id;
b03c9f9f 5494 dst_reg->off = ptr_reg->off - smin_val;
0962590e 5495 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
5496 break;
5497 }
f1174f77
EC
5498 /* A new variable offset is created. If the subtrahend is known
5499 * nonnegative, then any reg->range we had before is still good.
969bf05e 5500 */
b03c9f9f
EC
5501 if (signed_sub_overflows(smin_ptr, smax_val) ||
5502 signed_sub_overflows(smax_ptr, smin_val)) {
5503 /* Overflow possible, we know nothing */
5504 dst_reg->smin_value = S64_MIN;
5505 dst_reg->smax_value = S64_MAX;
5506 } else {
5507 dst_reg->smin_value = smin_ptr - smax_val;
5508 dst_reg->smax_value = smax_ptr - smin_val;
5509 }
5510 if (umin_ptr < umax_val) {
5511 /* Overflow possible, we know nothing */
5512 dst_reg->umin_value = 0;
5513 dst_reg->umax_value = U64_MAX;
5514 } else {
5515 /* Cannot overflow (as long as bounds are consistent) */
5516 dst_reg->umin_value = umin_ptr - umax_val;
5517 dst_reg->umax_value = umax_ptr - umin_val;
5518 }
f1174f77
EC
5519 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5520 dst_reg->off = ptr_reg->off;
0962590e 5521 dst_reg->raw = ptr_reg->raw;
de8f3a83 5522 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
5523 dst_reg->id = ++env->id_gen;
5524 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 5525 if (smin_val < 0)
0962590e 5526 dst_reg->raw = 0;
43188702 5527 }
f1174f77
EC
5528 break;
5529 case BPF_AND:
5530 case BPF_OR:
5531 case BPF_XOR:
82abbf8d
AS
5532 /* bitwise ops on pointers are troublesome, prohibit. */
5533 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5534 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
5535 return -EACCES;
5536 default:
5537 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
5538 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5539 dst, bpf_alu_string[opcode >> 4]);
f1174f77 5540 return -EACCES;
43188702
JF
5541 }
5542
bb7f0f98
AS
5543 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5544 return -EINVAL;
5545
b03c9f9f
EC
5546 __update_reg_bounds(dst_reg);
5547 __reg_deduce_bounds(dst_reg);
5548 __reg_bound_offset(dst_reg);
0d6303db
DB
5549
5550 /* For unprivileged we require that resulting offset must be in bounds
5551 * in order to be able to sanitize access later on.
5552 */
2c78ee89 5553 if (!env->bypass_spec_v1) {
e4298d25
DB
5554 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5555 check_map_access(env, dst, dst_reg->off, 1, false)) {
5556 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5557 "prohibited for !root\n", dst);
5558 return -EACCES;
5559 } else if (dst_reg->type == PTR_TO_STACK &&
5560 check_stack_access(env, dst_reg, dst_reg->off +
5561 dst_reg->var_off.value, 1)) {
5562 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5563 "prohibited for !root\n", dst);
5564 return -EACCES;
5565 }
0d6303db
DB
5566 }
5567
43188702
JF
5568 return 0;
5569}
5570
3f50f132
JF
5571static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5572 struct bpf_reg_state *src_reg)
5573{
5574 s32 smin_val = src_reg->s32_min_value;
5575 s32 smax_val = src_reg->s32_max_value;
5576 u32 umin_val = src_reg->u32_min_value;
5577 u32 umax_val = src_reg->u32_max_value;
5578
5579 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5580 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5581 dst_reg->s32_min_value = S32_MIN;
5582 dst_reg->s32_max_value = S32_MAX;
5583 } else {
5584 dst_reg->s32_min_value += smin_val;
5585 dst_reg->s32_max_value += smax_val;
5586 }
5587 if (dst_reg->u32_min_value + umin_val < umin_val ||
5588 dst_reg->u32_max_value + umax_val < umax_val) {
5589 dst_reg->u32_min_value = 0;
5590 dst_reg->u32_max_value = U32_MAX;
5591 } else {
5592 dst_reg->u32_min_value += umin_val;
5593 dst_reg->u32_max_value += umax_val;
5594 }
5595}
5596
07cd2631
JF
5597static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5598 struct bpf_reg_state *src_reg)
5599{
5600 s64 smin_val = src_reg->smin_value;
5601 s64 smax_val = src_reg->smax_value;
5602 u64 umin_val = src_reg->umin_value;
5603 u64 umax_val = src_reg->umax_value;
5604
5605 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5606 signed_add_overflows(dst_reg->smax_value, smax_val)) {
5607 dst_reg->smin_value = S64_MIN;
5608 dst_reg->smax_value = S64_MAX;
5609 } else {
5610 dst_reg->smin_value += smin_val;
5611 dst_reg->smax_value += smax_val;
5612 }
5613 if (dst_reg->umin_value + umin_val < umin_val ||
5614 dst_reg->umax_value + umax_val < umax_val) {
5615 dst_reg->umin_value = 0;
5616 dst_reg->umax_value = U64_MAX;
5617 } else {
5618 dst_reg->umin_value += umin_val;
5619 dst_reg->umax_value += umax_val;
5620 }
3f50f132
JF
5621}
5622
5623static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5624 struct bpf_reg_state *src_reg)
5625{
5626 s32 smin_val = src_reg->s32_min_value;
5627 s32 smax_val = src_reg->s32_max_value;
5628 u32 umin_val = src_reg->u32_min_value;
5629 u32 umax_val = src_reg->u32_max_value;
5630
5631 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5632 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5633 /* Overflow possible, we know nothing */
5634 dst_reg->s32_min_value = S32_MIN;
5635 dst_reg->s32_max_value = S32_MAX;
5636 } else {
5637 dst_reg->s32_min_value -= smax_val;
5638 dst_reg->s32_max_value -= smin_val;
5639 }
5640 if (dst_reg->u32_min_value < umax_val) {
5641 /* Overflow possible, we know nothing */
5642 dst_reg->u32_min_value = 0;
5643 dst_reg->u32_max_value = U32_MAX;
5644 } else {
5645 /* Cannot overflow (as long as bounds are consistent) */
5646 dst_reg->u32_min_value -= umax_val;
5647 dst_reg->u32_max_value -= umin_val;
5648 }
07cd2631
JF
5649}
5650
5651static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5652 struct bpf_reg_state *src_reg)
5653{
5654 s64 smin_val = src_reg->smin_value;
5655 s64 smax_val = src_reg->smax_value;
5656 u64 umin_val = src_reg->umin_value;
5657 u64 umax_val = src_reg->umax_value;
5658
5659 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5660 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5661 /* Overflow possible, we know nothing */
5662 dst_reg->smin_value = S64_MIN;
5663 dst_reg->smax_value = S64_MAX;
5664 } else {
5665 dst_reg->smin_value -= smax_val;
5666 dst_reg->smax_value -= smin_val;
5667 }
5668 if (dst_reg->umin_value < umax_val) {
5669 /* Overflow possible, we know nothing */
5670 dst_reg->umin_value = 0;
5671 dst_reg->umax_value = U64_MAX;
5672 } else {
5673 /* Cannot overflow (as long as bounds are consistent) */
5674 dst_reg->umin_value -= umax_val;
5675 dst_reg->umax_value -= umin_val;
5676 }
3f50f132
JF
5677}
5678
5679static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5680 struct bpf_reg_state *src_reg)
5681{
5682 s32 smin_val = src_reg->s32_min_value;
5683 u32 umin_val = src_reg->u32_min_value;
5684 u32 umax_val = src_reg->u32_max_value;
5685
5686 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5687 /* Ain't nobody got time to multiply that sign */
5688 __mark_reg32_unbounded(dst_reg);
5689 return;
5690 }
5691 /* Both values are positive, so we can work with unsigned and
5692 * copy the result to signed (unless it exceeds S32_MAX).
5693 */
5694 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5695 /* Potential overflow, we know nothing */
5696 __mark_reg32_unbounded(dst_reg);
5697 return;
5698 }
5699 dst_reg->u32_min_value *= umin_val;
5700 dst_reg->u32_max_value *= umax_val;
5701 if (dst_reg->u32_max_value > S32_MAX) {
5702 /* Overflow possible, we know nothing */
5703 dst_reg->s32_min_value = S32_MIN;
5704 dst_reg->s32_max_value = S32_MAX;
5705 } else {
5706 dst_reg->s32_min_value = dst_reg->u32_min_value;
5707 dst_reg->s32_max_value = dst_reg->u32_max_value;
5708 }
07cd2631
JF
5709}
5710
5711static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5712 struct bpf_reg_state *src_reg)
5713{
5714 s64 smin_val = src_reg->smin_value;
5715 u64 umin_val = src_reg->umin_value;
5716 u64 umax_val = src_reg->umax_value;
5717
07cd2631
JF
5718 if (smin_val < 0 || dst_reg->smin_value < 0) {
5719 /* Ain't nobody got time to multiply that sign */
3f50f132 5720 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5721 return;
5722 }
5723 /* Both values are positive, so we can work with unsigned and
5724 * copy the result to signed (unless it exceeds S64_MAX).
5725 */
5726 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5727 /* Potential overflow, we know nothing */
3f50f132 5728 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
5729 return;
5730 }
5731 dst_reg->umin_value *= umin_val;
5732 dst_reg->umax_value *= umax_val;
5733 if (dst_reg->umax_value > S64_MAX) {
5734 /* Overflow possible, we know nothing */
5735 dst_reg->smin_value = S64_MIN;
5736 dst_reg->smax_value = S64_MAX;
5737 } else {
5738 dst_reg->smin_value = dst_reg->umin_value;
5739 dst_reg->smax_value = dst_reg->umax_value;
5740 }
5741}
5742
3f50f132
JF
5743static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5744 struct bpf_reg_state *src_reg)
5745{
5746 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5747 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5748 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5749 s32 smin_val = src_reg->s32_min_value;
5750 u32 umax_val = src_reg->u32_max_value;
5751
5752 /* Assuming scalar64_min_max_and will be called so its safe
5753 * to skip updating register for known 32-bit case.
5754 */
5755 if (src_known && dst_known)
5756 return;
5757
5758 /* We get our minimum from the var_off, since that's inherently
5759 * bitwise. Our maximum is the minimum of the operands' maxima.
5760 */
5761 dst_reg->u32_min_value = var32_off.value;
5762 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5763 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5764 /* Lose signed bounds when ANDing negative numbers,
5765 * ain't nobody got time for that.
5766 */
5767 dst_reg->s32_min_value = S32_MIN;
5768 dst_reg->s32_max_value = S32_MAX;
5769 } else {
5770 /* ANDing two positives gives a positive, so safe to
5771 * cast result into s64.
5772 */
5773 dst_reg->s32_min_value = dst_reg->u32_min_value;
5774 dst_reg->s32_max_value = dst_reg->u32_max_value;
5775 }
5776
5777}
5778
07cd2631
JF
5779static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5780 struct bpf_reg_state *src_reg)
5781{
3f50f132
JF
5782 bool src_known = tnum_is_const(src_reg->var_off);
5783 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5784 s64 smin_val = src_reg->smin_value;
5785 u64 umax_val = src_reg->umax_value;
5786
3f50f132
JF
5787 if (src_known && dst_known) {
5788 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5789 src_reg->var_off.value);
5790 return;
5791 }
5792
07cd2631
JF
5793 /* We get our minimum from the var_off, since that's inherently
5794 * bitwise. Our maximum is the minimum of the operands' maxima.
5795 */
07cd2631
JF
5796 dst_reg->umin_value = dst_reg->var_off.value;
5797 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5798 if (dst_reg->smin_value < 0 || smin_val < 0) {
5799 /* Lose signed bounds when ANDing negative numbers,
5800 * ain't nobody got time for that.
5801 */
5802 dst_reg->smin_value = S64_MIN;
5803 dst_reg->smax_value = S64_MAX;
5804 } else {
5805 /* ANDing two positives gives a positive, so safe to
5806 * cast result into s64.
5807 */
5808 dst_reg->smin_value = dst_reg->umin_value;
5809 dst_reg->smax_value = dst_reg->umax_value;
5810 }
5811 /* We may learn something more from the var_off */
5812 __update_reg_bounds(dst_reg);
5813}
5814
3f50f132
JF
5815static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5816 struct bpf_reg_state *src_reg)
5817{
5818 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5819 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5820 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5821 s32 smin_val = src_reg->smin_value;
5822 u32 umin_val = src_reg->umin_value;
5823
5824 /* Assuming scalar64_min_max_or will be called so it is safe
5825 * to skip updating register for known case.
5826 */
5827 if (src_known && dst_known)
5828 return;
5829
5830 /* We get our maximum from the var_off, and our minimum is the
5831 * maximum of the operands' minima
5832 */
5833 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5834 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5835 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5836 /* Lose signed bounds when ORing negative numbers,
5837 * ain't nobody got time for that.
5838 */
5839 dst_reg->s32_min_value = S32_MIN;
5840 dst_reg->s32_max_value = S32_MAX;
5841 } else {
5842 /* ORing two positives gives a positive, so safe to
5843 * cast result into s64.
5844 */
5845 dst_reg->s32_min_value = dst_reg->umin_value;
5846 dst_reg->s32_max_value = dst_reg->umax_value;
5847 }
5848}
5849
07cd2631
JF
5850static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5851 struct bpf_reg_state *src_reg)
5852{
3f50f132
JF
5853 bool src_known = tnum_is_const(src_reg->var_off);
5854 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
5855 s64 smin_val = src_reg->smin_value;
5856 u64 umin_val = src_reg->umin_value;
5857
3f50f132
JF
5858 if (src_known && dst_known) {
5859 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5860 src_reg->var_off.value);
5861 return;
5862 }
5863
07cd2631
JF
5864 /* We get our maximum from the var_off, and our minimum is the
5865 * maximum of the operands' minima
5866 */
07cd2631
JF
5867 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5868 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5869 if (dst_reg->smin_value < 0 || smin_val < 0) {
5870 /* Lose signed bounds when ORing negative numbers,
5871 * ain't nobody got time for that.
5872 */
5873 dst_reg->smin_value = S64_MIN;
5874 dst_reg->smax_value = S64_MAX;
5875 } else {
5876 /* ORing two positives gives a positive, so safe to
5877 * cast result into s64.
5878 */
5879 dst_reg->smin_value = dst_reg->umin_value;
5880 dst_reg->smax_value = dst_reg->umax_value;
5881 }
5882 /* We may learn something more from the var_off */
5883 __update_reg_bounds(dst_reg);
5884}
5885
2921c90d
YS
5886static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
5887 struct bpf_reg_state *src_reg)
5888{
5889 bool src_known = tnum_subreg_is_const(src_reg->var_off);
5890 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5891 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5892 s32 smin_val = src_reg->s32_min_value;
5893
5894 /* Assuming scalar64_min_max_xor will be called so it is safe
5895 * to skip updating register for known case.
5896 */
5897 if (src_known && dst_known)
5898 return;
5899
5900 /* We get both minimum and maximum from the var32_off. */
5901 dst_reg->u32_min_value = var32_off.value;
5902 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5903
5904 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
5905 /* XORing two positive sign numbers gives a positive,
5906 * so safe to cast u32 result into s32.
5907 */
5908 dst_reg->s32_min_value = dst_reg->u32_min_value;
5909 dst_reg->s32_max_value = dst_reg->u32_max_value;
5910 } else {
5911 dst_reg->s32_min_value = S32_MIN;
5912 dst_reg->s32_max_value = S32_MAX;
5913 }
5914}
5915
5916static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
5917 struct bpf_reg_state *src_reg)
5918{
5919 bool src_known = tnum_is_const(src_reg->var_off);
5920 bool dst_known = tnum_is_const(dst_reg->var_off);
5921 s64 smin_val = src_reg->smin_value;
5922
5923 if (src_known && dst_known) {
5924 /* dst_reg->var_off.value has been updated earlier */
5925 __mark_reg_known(dst_reg, dst_reg->var_off.value);
5926 return;
5927 }
5928
5929 /* We get both minimum and maximum from the var_off. */
5930 dst_reg->umin_value = dst_reg->var_off.value;
5931 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5932
5933 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
5934 /* XORing two positive sign numbers gives a positive,
5935 * so safe to cast u64 result into s64.
5936 */
5937 dst_reg->smin_value = dst_reg->umin_value;
5938 dst_reg->smax_value = dst_reg->umax_value;
5939 } else {
5940 dst_reg->smin_value = S64_MIN;
5941 dst_reg->smax_value = S64_MAX;
5942 }
5943
5944 __update_reg_bounds(dst_reg);
5945}
5946
3f50f132
JF
5947static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5948 u64 umin_val, u64 umax_val)
07cd2631 5949{
07cd2631
JF
5950 /* We lose all sign bit information (except what we can pick
5951 * up from var_off)
5952 */
3f50f132
JF
5953 dst_reg->s32_min_value = S32_MIN;
5954 dst_reg->s32_max_value = S32_MAX;
5955 /* If we might shift our top bit out, then we know nothing */
5956 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5957 dst_reg->u32_min_value = 0;
5958 dst_reg->u32_max_value = U32_MAX;
5959 } else {
5960 dst_reg->u32_min_value <<= umin_val;
5961 dst_reg->u32_max_value <<= umax_val;
5962 }
5963}
5964
5965static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5966 struct bpf_reg_state *src_reg)
5967{
5968 u32 umax_val = src_reg->u32_max_value;
5969 u32 umin_val = src_reg->u32_min_value;
5970 /* u32 alu operation will zext upper bits */
5971 struct tnum subreg = tnum_subreg(dst_reg->var_off);
5972
5973 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5974 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
5975 /* Not required but being careful mark reg64 bounds as unknown so
5976 * that we are forced to pick them up from tnum and zext later and
5977 * if some path skips this step we are still safe.
5978 */
5979 __mark_reg64_unbounded(dst_reg);
5980 __update_reg32_bounds(dst_reg);
5981}
5982
5983static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
5984 u64 umin_val, u64 umax_val)
5985{
5986 /* Special case <<32 because it is a common compiler pattern to sign
5987 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5988 * positive we know this shift will also be positive so we can track
5989 * bounds correctly. Otherwise we lose all sign bit information except
5990 * what we can pick up from var_off. Perhaps we can generalize this
5991 * later to shifts of any length.
5992 */
5993 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
5994 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
5995 else
5996 dst_reg->smax_value = S64_MAX;
5997
5998 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
5999 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6000 else
6001 dst_reg->smin_value = S64_MIN;
6002
07cd2631
JF
6003 /* If we might shift our top bit out, then we know nothing */
6004 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6005 dst_reg->umin_value = 0;
6006 dst_reg->umax_value = U64_MAX;
6007 } else {
6008 dst_reg->umin_value <<= umin_val;
6009 dst_reg->umax_value <<= umax_val;
6010 }
3f50f132
JF
6011}
6012
6013static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6014 struct bpf_reg_state *src_reg)
6015{
6016 u64 umax_val = src_reg->umax_value;
6017 u64 umin_val = src_reg->umin_value;
6018
6019 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6020 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6021 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6022
07cd2631
JF
6023 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6024 /* We may learn something more from the var_off */
6025 __update_reg_bounds(dst_reg);
6026}
6027
3f50f132
JF
6028static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6029 struct bpf_reg_state *src_reg)
6030{
6031 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6032 u32 umax_val = src_reg->u32_max_value;
6033 u32 umin_val = src_reg->u32_min_value;
6034
6035 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6036 * be negative, then either:
6037 * 1) src_reg might be zero, so the sign bit of the result is
6038 * unknown, so we lose our signed bounds
6039 * 2) it's known negative, thus the unsigned bounds capture the
6040 * signed bounds
6041 * 3) the signed bounds cross zero, so they tell us nothing
6042 * about the result
6043 * If the value in dst_reg is known nonnegative, then again the
6044 * unsigned bounts capture the signed bounds.
6045 * Thus, in all cases it suffices to blow away our signed bounds
6046 * and rely on inferring new ones from the unsigned bounds and
6047 * var_off of the result.
6048 */
6049 dst_reg->s32_min_value = S32_MIN;
6050 dst_reg->s32_max_value = S32_MAX;
6051
6052 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6053 dst_reg->u32_min_value >>= umax_val;
6054 dst_reg->u32_max_value >>= umin_val;
6055
6056 __mark_reg64_unbounded(dst_reg);
6057 __update_reg32_bounds(dst_reg);
6058}
6059
07cd2631
JF
6060static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6061 struct bpf_reg_state *src_reg)
6062{
6063 u64 umax_val = src_reg->umax_value;
6064 u64 umin_val = src_reg->umin_value;
6065
6066 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6067 * be negative, then either:
6068 * 1) src_reg might be zero, so the sign bit of the result is
6069 * unknown, so we lose our signed bounds
6070 * 2) it's known negative, thus the unsigned bounds capture the
6071 * signed bounds
6072 * 3) the signed bounds cross zero, so they tell us nothing
6073 * about the result
6074 * If the value in dst_reg is known nonnegative, then again the
6075 * unsigned bounts capture the signed bounds.
6076 * Thus, in all cases it suffices to blow away our signed bounds
6077 * and rely on inferring new ones from the unsigned bounds and
6078 * var_off of the result.
6079 */
6080 dst_reg->smin_value = S64_MIN;
6081 dst_reg->smax_value = S64_MAX;
6082 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6083 dst_reg->umin_value >>= umax_val;
6084 dst_reg->umax_value >>= umin_val;
3f50f132
JF
6085
6086 /* Its not easy to operate on alu32 bounds here because it depends
6087 * on bits being shifted in. Take easy way out and mark unbounded
6088 * so we can recalculate later from tnum.
6089 */
6090 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6091 __update_reg_bounds(dst_reg);
6092}
6093
3f50f132
JF
6094static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6095 struct bpf_reg_state *src_reg)
07cd2631 6096{
3f50f132 6097 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
6098
6099 /* Upon reaching here, src_known is true and
6100 * umax_val is equal to umin_val.
6101 */
3f50f132
JF
6102 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6103 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 6104
3f50f132
JF
6105 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6106
6107 /* blow away the dst_reg umin_value/umax_value and rely on
6108 * dst_reg var_off to refine the result.
6109 */
6110 dst_reg->u32_min_value = 0;
6111 dst_reg->u32_max_value = U32_MAX;
6112
6113 __mark_reg64_unbounded(dst_reg);
6114 __update_reg32_bounds(dst_reg);
6115}
6116
6117static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6118 struct bpf_reg_state *src_reg)
6119{
6120 u64 umin_val = src_reg->umin_value;
6121
6122 /* Upon reaching here, src_known is true and umax_val is equal
6123 * to umin_val.
6124 */
6125 dst_reg->smin_value >>= umin_val;
6126 dst_reg->smax_value >>= umin_val;
6127
6128 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
6129
6130 /* blow away the dst_reg umin_value/umax_value and rely on
6131 * dst_reg var_off to refine the result.
6132 */
6133 dst_reg->umin_value = 0;
6134 dst_reg->umax_value = U64_MAX;
3f50f132
JF
6135
6136 /* Its not easy to operate on alu32 bounds here because it depends
6137 * on bits being shifted in from upper 32-bits. Take easy way out
6138 * and mark unbounded so we can recalculate later from tnum.
6139 */
6140 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
6141 __update_reg_bounds(dst_reg);
6142}
6143
468f6eaf
JH
6144/* WARNING: This function does calculations on 64-bit values, but the actual
6145 * execution may occur on 32-bit values. Therefore, things like bitshifts
6146 * need extra checks in the 32-bit case.
6147 */
f1174f77
EC
6148static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6149 struct bpf_insn *insn,
6150 struct bpf_reg_state *dst_reg,
6151 struct bpf_reg_state src_reg)
969bf05e 6152{
638f5b90 6153 struct bpf_reg_state *regs = cur_regs(env);
48461135 6154 u8 opcode = BPF_OP(insn->code);
b0b3fb67 6155 bool src_known;
b03c9f9f
EC
6156 s64 smin_val, smax_val;
6157 u64 umin_val, umax_val;
3f50f132
JF
6158 s32 s32_min_val, s32_max_val;
6159 u32 u32_min_val, u32_max_val;
468f6eaf 6160 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
6161 u32 dst = insn->dst_reg;
6162 int ret;
3f50f132 6163 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
b799207e 6164
b03c9f9f
EC
6165 smin_val = src_reg.smin_value;
6166 smax_val = src_reg.smax_value;
6167 umin_val = src_reg.umin_value;
6168 umax_val = src_reg.umax_value;
f23cc643 6169
3f50f132
JF
6170 s32_min_val = src_reg.s32_min_value;
6171 s32_max_val = src_reg.s32_max_value;
6172 u32_min_val = src_reg.u32_min_value;
6173 u32_max_val = src_reg.u32_max_value;
6174
6175 if (alu32) {
6176 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
6177 if ((src_known &&
6178 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6179 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6180 /* Taint dst register if offset had invalid bounds
6181 * derived from e.g. dead branches.
6182 */
6183 __mark_reg_unknown(env, dst_reg);
6184 return 0;
6185 }
6186 } else {
6187 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
6188 if ((src_known &&
6189 (smin_val != smax_val || umin_val != umax_val)) ||
6190 smin_val > smax_val || umin_val > umax_val) {
6191 /* Taint dst register if offset had invalid bounds
6192 * derived from e.g. dead branches.
6193 */
6194 __mark_reg_unknown(env, dst_reg);
6195 return 0;
6196 }
6f16101e
DB
6197 }
6198
bb7f0f98
AS
6199 if (!src_known &&
6200 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 6201 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
6202 return 0;
6203 }
6204
3f50f132
JF
6205 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6206 * There are two classes of instructions: The first class we track both
6207 * alu32 and alu64 sign/unsigned bounds independently this provides the
6208 * greatest amount of precision when alu operations are mixed with jmp32
6209 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6210 * and BPF_OR. This is possible because these ops have fairly easy to
6211 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6212 * See alu32 verifier tests for examples. The second class of
6213 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6214 * with regards to tracking sign/unsigned bounds because the bits may
6215 * cross subreg boundaries in the alu64 case. When this happens we mark
6216 * the reg unbounded in the subreg bound space and use the resulting
6217 * tnum to calculate an approximation of the sign/unsigned bounds.
6218 */
48461135
JB
6219 switch (opcode) {
6220 case BPF_ADD:
d3bd7413
DB
6221 ret = sanitize_val_alu(env, insn);
6222 if (ret < 0) {
6223 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6224 return ret;
6225 }
3f50f132 6226 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 6227 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 6228 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
6229 break;
6230 case BPF_SUB:
d3bd7413
DB
6231 ret = sanitize_val_alu(env, insn);
6232 if (ret < 0) {
6233 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6234 return ret;
6235 }
3f50f132 6236 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 6237 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 6238 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
6239 break;
6240 case BPF_MUL:
3f50f132
JF
6241 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6242 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 6243 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
6244 break;
6245 case BPF_AND:
3f50f132
JF
6246 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6247 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 6248 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
6249 break;
6250 case BPF_OR:
3f50f132
JF
6251 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6252 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 6253 scalar_min_max_or(dst_reg, &src_reg);
48461135 6254 break;
2921c90d
YS
6255 case BPF_XOR:
6256 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6257 scalar32_min_max_xor(dst_reg, &src_reg);
6258 scalar_min_max_xor(dst_reg, &src_reg);
6259 break;
48461135 6260 case BPF_LSH:
468f6eaf
JH
6261 if (umax_val >= insn_bitness) {
6262 /* Shifts greater than 31 or 63 are undefined.
6263 * This includes shifts by a negative number.
b03c9f9f 6264 */
61bd5218 6265 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6266 break;
6267 }
3f50f132
JF
6268 if (alu32)
6269 scalar32_min_max_lsh(dst_reg, &src_reg);
6270 else
6271 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
6272 break;
6273 case BPF_RSH:
468f6eaf
JH
6274 if (umax_val >= insn_bitness) {
6275 /* Shifts greater than 31 or 63 are undefined.
6276 * This includes shifts by a negative number.
b03c9f9f 6277 */
61bd5218 6278 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
6279 break;
6280 }
3f50f132
JF
6281 if (alu32)
6282 scalar32_min_max_rsh(dst_reg, &src_reg);
6283 else
6284 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 6285 break;
9cbe1f5a
YS
6286 case BPF_ARSH:
6287 if (umax_val >= insn_bitness) {
6288 /* Shifts greater than 31 or 63 are undefined.
6289 * This includes shifts by a negative number.
6290 */
6291 mark_reg_unknown(env, regs, insn->dst_reg);
6292 break;
6293 }
3f50f132
JF
6294 if (alu32)
6295 scalar32_min_max_arsh(dst_reg, &src_reg);
6296 else
6297 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 6298 break;
48461135 6299 default:
61bd5218 6300 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
6301 break;
6302 }
6303
3f50f132
JF
6304 /* ALU32 ops are zero extended into 64bit register */
6305 if (alu32)
6306 zext_32_to_64(dst_reg);
468f6eaf 6307
294f2fc6 6308 __update_reg_bounds(dst_reg);
b03c9f9f
EC
6309 __reg_deduce_bounds(dst_reg);
6310 __reg_bound_offset(dst_reg);
f1174f77
EC
6311 return 0;
6312}
6313
6314/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6315 * and var_off.
6316 */
6317static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6318 struct bpf_insn *insn)
6319{
f4d7e40a
AS
6320 struct bpf_verifier_state *vstate = env->cur_state;
6321 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6322 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
6323 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6324 u8 opcode = BPF_OP(insn->code);
b5dc0163 6325 int err;
f1174f77
EC
6326
6327 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
6328 src_reg = NULL;
6329 if (dst_reg->type != SCALAR_VALUE)
6330 ptr_reg = dst_reg;
6331 if (BPF_SRC(insn->code) == BPF_X) {
6332 src_reg = &regs[insn->src_reg];
f1174f77
EC
6333 if (src_reg->type != SCALAR_VALUE) {
6334 if (dst_reg->type != SCALAR_VALUE) {
6335 /* Combining two pointers by any ALU op yields
82abbf8d
AS
6336 * an arbitrary scalar. Disallow all math except
6337 * pointer subtraction
f1174f77 6338 */
dd066823 6339 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
6340 mark_reg_unknown(env, regs, insn->dst_reg);
6341 return 0;
f1174f77 6342 }
82abbf8d
AS
6343 verbose(env, "R%d pointer %s pointer prohibited\n",
6344 insn->dst_reg,
6345 bpf_alu_string[opcode >> 4]);
6346 return -EACCES;
f1174f77
EC
6347 } else {
6348 /* scalar += pointer
6349 * This is legal, but we have to reverse our
6350 * src/dest handling in computing the range
6351 */
b5dc0163
AS
6352 err = mark_chain_precision(env, insn->dst_reg);
6353 if (err)
6354 return err;
82abbf8d
AS
6355 return adjust_ptr_min_max_vals(env, insn,
6356 src_reg, dst_reg);
f1174f77
EC
6357 }
6358 } else if (ptr_reg) {
6359 /* pointer += scalar */
b5dc0163
AS
6360 err = mark_chain_precision(env, insn->src_reg);
6361 if (err)
6362 return err;
82abbf8d
AS
6363 return adjust_ptr_min_max_vals(env, insn,
6364 dst_reg, src_reg);
f1174f77
EC
6365 }
6366 } else {
6367 /* Pretend the src is a reg with a known value, since we only
6368 * need to be able to read from this state.
6369 */
6370 off_reg.type = SCALAR_VALUE;
b03c9f9f 6371 __mark_reg_known(&off_reg, insn->imm);
f1174f77 6372 src_reg = &off_reg;
82abbf8d
AS
6373 if (ptr_reg) /* pointer += K */
6374 return adjust_ptr_min_max_vals(env, insn,
6375 ptr_reg, src_reg);
f1174f77
EC
6376 }
6377
6378 /* Got here implies adding two SCALAR_VALUEs */
6379 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 6380 print_verifier_state(env, state);
61bd5218 6381 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
6382 return -EINVAL;
6383 }
6384 if (WARN_ON(!src_reg)) {
f4d7e40a 6385 print_verifier_state(env, state);
61bd5218 6386 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
6387 return -EINVAL;
6388 }
6389 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
6390}
6391
17a52670 6392/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 6393static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 6394{
638f5b90 6395 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
6396 u8 opcode = BPF_OP(insn->code);
6397 int err;
6398
6399 if (opcode == BPF_END || opcode == BPF_NEG) {
6400 if (opcode == BPF_NEG) {
6401 if (BPF_SRC(insn->code) != 0 ||
6402 insn->src_reg != BPF_REG_0 ||
6403 insn->off != 0 || insn->imm != 0) {
61bd5218 6404 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
6405 return -EINVAL;
6406 }
6407 } else {
6408 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
6409 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6410 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 6411 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
6412 return -EINVAL;
6413 }
6414 }
6415
6416 /* check src operand */
dc503a8a 6417 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6418 if (err)
6419 return err;
6420
1be7f75d 6421 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 6422 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
6423 insn->dst_reg);
6424 return -EACCES;
6425 }
6426
17a52670 6427 /* check dest operand */
dc503a8a 6428 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
6429 if (err)
6430 return err;
6431
6432 } else if (opcode == BPF_MOV) {
6433
6434 if (BPF_SRC(insn->code) == BPF_X) {
6435 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6436 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6437 return -EINVAL;
6438 }
6439
6440 /* check src operand */
dc503a8a 6441 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6442 if (err)
6443 return err;
6444 } else {
6445 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6446 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
6447 return -EINVAL;
6448 }
6449 }
6450
fbeb1603
AF
6451 /* check dest operand, mark as required later */
6452 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
6453 if (err)
6454 return err;
6455
6456 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
6457 struct bpf_reg_state *src_reg = regs + insn->src_reg;
6458 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6459
17a52670
AS
6460 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6461 /* case: R1 = R2
6462 * copy register state to dest reg
6463 */
e434b8cd
JW
6464 *dst_reg = *src_reg;
6465 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6466 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 6467 } else {
f1174f77 6468 /* R1 = (u32) R2 */
1be7f75d 6469 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
6470 verbose(env,
6471 "R%d partial copy of pointer\n",
1be7f75d
AS
6472 insn->src_reg);
6473 return -EACCES;
e434b8cd
JW
6474 } else if (src_reg->type == SCALAR_VALUE) {
6475 *dst_reg = *src_reg;
6476 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 6477 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
6478 } else {
6479 mark_reg_unknown(env, regs,
6480 insn->dst_reg);
1be7f75d 6481 }
3f50f132 6482 zext_32_to_64(dst_reg);
17a52670
AS
6483 }
6484 } else {
6485 /* case: R = imm
6486 * remember the value we stored into this reg
6487 */
fbeb1603
AF
6488 /* clear any state __mark_reg_known doesn't set */
6489 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 6490 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
6491 if (BPF_CLASS(insn->code) == BPF_ALU64) {
6492 __mark_reg_known(regs + insn->dst_reg,
6493 insn->imm);
6494 } else {
6495 __mark_reg_known(regs + insn->dst_reg,
6496 (u32)insn->imm);
6497 }
17a52670
AS
6498 }
6499
6500 } else if (opcode > BPF_END) {
61bd5218 6501 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
6502 return -EINVAL;
6503
6504 } else { /* all other ALU ops: and, sub, xor, add, ... */
6505
17a52670
AS
6506 if (BPF_SRC(insn->code) == BPF_X) {
6507 if (insn->imm != 0 || insn->off != 0) {
61bd5218 6508 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6509 return -EINVAL;
6510 }
6511 /* check src1 operand */
dc503a8a 6512 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
6513 if (err)
6514 return err;
6515 } else {
6516 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 6517 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
6518 return -EINVAL;
6519 }
6520 }
6521
6522 /* check src2 operand */
dc503a8a 6523 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
6524 if (err)
6525 return err;
6526
6527 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6528 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 6529 verbose(env, "div by zero\n");
17a52670
AS
6530 return -EINVAL;
6531 }
6532
229394e8
RV
6533 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6534 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6535 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6536
6537 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 6538 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
6539 return -EINVAL;
6540 }
6541 }
6542
1a0dc1ac 6543 /* check dest operand */
dc503a8a 6544 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
6545 if (err)
6546 return err;
6547
f1174f77 6548 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
6549 }
6550
6551 return 0;
6552}
6553
c6a9efa1
PC
6554static void __find_good_pkt_pointers(struct bpf_func_state *state,
6555 struct bpf_reg_state *dst_reg,
6556 enum bpf_reg_type type, u16 new_range)
6557{
6558 struct bpf_reg_state *reg;
6559 int i;
6560
6561 for (i = 0; i < MAX_BPF_REG; i++) {
6562 reg = &state->regs[i];
6563 if (reg->type == type && reg->id == dst_reg->id)
6564 /* keep the maximum range already checked */
6565 reg->range = max(reg->range, new_range);
6566 }
6567
6568 bpf_for_each_spilled_reg(i, state, reg) {
6569 if (!reg)
6570 continue;
6571 if (reg->type == type && reg->id == dst_reg->id)
6572 reg->range = max(reg->range, new_range);
6573 }
6574}
6575
f4d7e40a 6576static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 6577 struct bpf_reg_state *dst_reg,
f8ddadc4 6578 enum bpf_reg_type type,
fb2a311a 6579 bool range_right_open)
969bf05e 6580{
fb2a311a 6581 u16 new_range;
c6a9efa1 6582 int i;
2d2be8ca 6583
fb2a311a
DB
6584 if (dst_reg->off < 0 ||
6585 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
6586 /* This doesn't give us any range */
6587 return;
6588
b03c9f9f
EC
6589 if (dst_reg->umax_value > MAX_PACKET_OFF ||
6590 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
6591 /* Risk of overflow. For instance, ptr + (1<<63) may be less
6592 * than pkt_end, but that's because it's also less than pkt.
6593 */
6594 return;
6595
fb2a311a
DB
6596 new_range = dst_reg->off;
6597 if (range_right_open)
6598 new_range--;
6599
6600 /* Examples for register markings:
2d2be8ca 6601 *
fb2a311a 6602 * pkt_data in dst register:
2d2be8ca
DB
6603 *
6604 * r2 = r3;
6605 * r2 += 8;
6606 * if (r2 > pkt_end) goto <handle exception>
6607 * <access okay>
6608 *
b4e432f1
DB
6609 * r2 = r3;
6610 * r2 += 8;
6611 * if (r2 < pkt_end) goto <access okay>
6612 * <handle exception>
6613 *
2d2be8ca
DB
6614 * Where:
6615 * r2 == dst_reg, pkt_end == src_reg
6616 * r2=pkt(id=n,off=8,r=0)
6617 * r3=pkt(id=n,off=0,r=0)
6618 *
fb2a311a 6619 * pkt_data in src register:
2d2be8ca
DB
6620 *
6621 * r2 = r3;
6622 * r2 += 8;
6623 * if (pkt_end >= r2) goto <access okay>
6624 * <handle exception>
6625 *
b4e432f1
DB
6626 * r2 = r3;
6627 * r2 += 8;
6628 * if (pkt_end <= r2) goto <handle exception>
6629 * <access okay>
6630 *
2d2be8ca
DB
6631 * Where:
6632 * pkt_end == dst_reg, r2 == src_reg
6633 * r2=pkt(id=n,off=8,r=0)
6634 * r3=pkt(id=n,off=0,r=0)
6635 *
6636 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
6637 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6638 * and [r3, r3 + 8-1) respectively is safe to access depending on
6639 * the check.
969bf05e 6640 */
2d2be8ca 6641
f1174f77
EC
6642 /* If our ids match, then we must have the same max_value. And we
6643 * don't care about the other reg's fixed offset, since if it's too big
6644 * the range won't allow anything.
6645 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6646 */
c6a9efa1
PC
6647 for (i = 0; i <= vstate->curframe; i++)
6648 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6649 new_range);
969bf05e
AS
6650}
6651
3f50f132 6652static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 6653{
3f50f132
JF
6654 struct tnum subreg = tnum_subreg(reg->var_off);
6655 s32 sval = (s32)val;
a72dafaf 6656
3f50f132
JF
6657 switch (opcode) {
6658 case BPF_JEQ:
6659 if (tnum_is_const(subreg))
6660 return !!tnum_equals_const(subreg, val);
6661 break;
6662 case BPF_JNE:
6663 if (tnum_is_const(subreg))
6664 return !tnum_equals_const(subreg, val);
6665 break;
6666 case BPF_JSET:
6667 if ((~subreg.mask & subreg.value) & val)
6668 return 1;
6669 if (!((subreg.mask | subreg.value) & val))
6670 return 0;
6671 break;
6672 case BPF_JGT:
6673 if (reg->u32_min_value > val)
6674 return 1;
6675 else if (reg->u32_max_value <= val)
6676 return 0;
6677 break;
6678 case BPF_JSGT:
6679 if (reg->s32_min_value > sval)
6680 return 1;
6681 else if (reg->s32_max_value < sval)
6682 return 0;
6683 break;
6684 case BPF_JLT:
6685 if (reg->u32_max_value < val)
6686 return 1;
6687 else if (reg->u32_min_value >= val)
6688 return 0;
6689 break;
6690 case BPF_JSLT:
6691 if (reg->s32_max_value < sval)
6692 return 1;
6693 else if (reg->s32_min_value >= sval)
6694 return 0;
6695 break;
6696 case BPF_JGE:
6697 if (reg->u32_min_value >= val)
6698 return 1;
6699 else if (reg->u32_max_value < val)
6700 return 0;
6701 break;
6702 case BPF_JSGE:
6703 if (reg->s32_min_value >= sval)
6704 return 1;
6705 else if (reg->s32_max_value < sval)
6706 return 0;
6707 break;
6708 case BPF_JLE:
6709 if (reg->u32_max_value <= val)
6710 return 1;
6711 else if (reg->u32_min_value > val)
6712 return 0;
6713 break;
6714 case BPF_JSLE:
6715 if (reg->s32_max_value <= sval)
6716 return 1;
6717 else if (reg->s32_min_value > sval)
6718 return 0;
6719 break;
6720 }
4f7b3e82 6721
3f50f132
JF
6722 return -1;
6723}
092ed096 6724
3f50f132
JF
6725
6726static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6727{
6728 s64 sval = (s64)val;
a72dafaf 6729
4f7b3e82
AS
6730 switch (opcode) {
6731 case BPF_JEQ:
6732 if (tnum_is_const(reg->var_off))
6733 return !!tnum_equals_const(reg->var_off, val);
6734 break;
6735 case BPF_JNE:
6736 if (tnum_is_const(reg->var_off))
6737 return !tnum_equals_const(reg->var_off, val);
6738 break;
960ea056
JK
6739 case BPF_JSET:
6740 if ((~reg->var_off.mask & reg->var_off.value) & val)
6741 return 1;
6742 if (!((reg->var_off.mask | reg->var_off.value) & val))
6743 return 0;
6744 break;
4f7b3e82
AS
6745 case BPF_JGT:
6746 if (reg->umin_value > val)
6747 return 1;
6748 else if (reg->umax_value <= val)
6749 return 0;
6750 break;
6751 case BPF_JSGT:
a72dafaf 6752 if (reg->smin_value > sval)
4f7b3e82 6753 return 1;
a72dafaf 6754 else if (reg->smax_value < sval)
4f7b3e82
AS
6755 return 0;
6756 break;
6757 case BPF_JLT:
6758 if (reg->umax_value < val)
6759 return 1;
6760 else if (reg->umin_value >= val)
6761 return 0;
6762 break;
6763 case BPF_JSLT:
a72dafaf 6764 if (reg->smax_value < sval)
4f7b3e82 6765 return 1;
a72dafaf 6766 else if (reg->smin_value >= sval)
4f7b3e82
AS
6767 return 0;
6768 break;
6769 case BPF_JGE:
6770 if (reg->umin_value >= val)
6771 return 1;
6772 else if (reg->umax_value < val)
6773 return 0;
6774 break;
6775 case BPF_JSGE:
a72dafaf 6776 if (reg->smin_value >= sval)
4f7b3e82 6777 return 1;
a72dafaf 6778 else if (reg->smax_value < sval)
4f7b3e82
AS
6779 return 0;
6780 break;
6781 case BPF_JLE:
6782 if (reg->umax_value <= val)
6783 return 1;
6784 else if (reg->umin_value > val)
6785 return 0;
6786 break;
6787 case BPF_JSLE:
a72dafaf 6788 if (reg->smax_value <= sval)
4f7b3e82 6789 return 1;
a72dafaf 6790 else if (reg->smin_value > sval)
4f7b3e82
AS
6791 return 0;
6792 break;
6793 }
6794
6795 return -1;
6796}
6797
3f50f132
JF
6798/* compute branch direction of the expression "if (reg opcode val) goto target;"
6799 * and return:
6800 * 1 - branch will be taken and "goto target" will be executed
6801 * 0 - branch will not be taken and fall-through to next insn
6802 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6803 * range [0,10]
604dca5e 6804 */
3f50f132
JF
6805static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6806 bool is_jmp32)
604dca5e 6807{
cac616db
JF
6808 if (__is_pointer_value(false, reg)) {
6809 if (!reg_type_not_null(reg->type))
6810 return -1;
6811
6812 /* If pointer is valid tests against zero will fail so we can
6813 * use this to direct branch taken.
6814 */
6815 if (val != 0)
6816 return -1;
6817
6818 switch (opcode) {
6819 case BPF_JEQ:
6820 return 0;
6821 case BPF_JNE:
6822 return 1;
6823 default:
6824 return -1;
6825 }
6826 }
604dca5e 6827
3f50f132
JF
6828 if (is_jmp32)
6829 return is_branch32_taken(reg, val, opcode);
6830 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
6831}
6832
48461135
JB
6833/* Adjusts the register min/max values in the case that the dst_reg is the
6834 * variable register that we are working on, and src_reg is a constant or we're
6835 * simply doing a BPF_K check.
f1174f77 6836 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
6837 */
6838static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
6839 struct bpf_reg_state *false_reg,
6840 u64 val, u32 val32,
092ed096 6841 u8 opcode, bool is_jmp32)
48461135 6842{
3f50f132
JF
6843 struct tnum false_32off = tnum_subreg(false_reg->var_off);
6844 struct tnum false_64off = false_reg->var_off;
6845 struct tnum true_32off = tnum_subreg(true_reg->var_off);
6846 struct tnum true_64off = true_reg->var_off;
6847 s64 sval = (s64)val;
6848 s32 sval32 = (s32)val32;
a72dafaf 6849
f1174f77
EC
6850 /* If the dst_reg is a pointer, we can't learn anything about its
6851 * variable offset from the compare (unless src_reg were a pointer into
6852 * the same object, but we don't bother with that.
6853 * Since false_reg and true_reg have the same type by construction, we
6854 * only need to check one of them for pointerness.
6855 */
6856 if (__is_pointer_value(false, false_reg))
6857 return;
4cabc5b1 6858
48461135
JB
6859 switch (opcode) {
6860 case BPF_JEQ:
48461135 6861 case BPF_JNE:
a72dafaf
JW
6862 {
6863 struct bpf_reg_state *reg =
6864 opcode == BPF_JEQ ? true_reg : false_reg;
6865
6866 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6867 * if it is true we know the value for sure. Likewise for
6868 * BPF_JNE.
48461135 6869 */
3f50f132
JF
6870 if (is_jmp32)
6871 __mark_reg32_known(reg, val32);
6872 else
092ed096 6873 __mark_reg_known(reg, val);
48461135 6874 break;
a72dafaf 6875 }
960ea056 6876 case BPF_JSET:
3f50f132
JF
6877 if (is_jmp32) {
6878 false_32off = tnum_and(false_32off, tnum_const(~val32));
6879 if (is_power_of_2(val32))
6880 true_32off = tnum_or(true_32off,
6881 tnum_const(val32));
6882 } else {
6883 false_64off = tnum_and(false_64off, tnum_const(~val));
6884 if (is_power_of_2(val))
6885 true_64off = tnum_or(true_64off,
6886 tnum_const(val));
6887 }
960ea056 6888 break;
48461135 6889 case BPF_JGE:
a72dafaf
JW
6890 case BPF_JGT:
6891 {
3f50f132
JF
6892 if (is_jmp32) {
6893 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
6894 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6895
6896 false_reg->u32_max_value = min(false_reg->u32_max_value,
6897 false_umax);
6898 true_reg->u32_min_value = max(true_reg->u32_min_value,
6899 true_umin);
6900 } else {
6901 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
6902 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6903
6904 false_reg->umax_value = min(false_reg->umax_value, false_umax);
6905 true_reg->umin_value = max(true_reg->umin_value, true_umin);
6906 }
b03c9f9f 6907 break;
a72dafaf 6908 }
48461135 6909 case BPF_JSGE:
a72dafaf
JW
6910 case BPF_JSGT:
6911 {
3f50f132
JF
6912 if (is_jmp32) {
6913 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
6914 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 6915
3f50f132
JF
6916 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6917 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6918 } else {
6919 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
6920 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6921
6922 false_reg->smax_value = min(false_reg->smax_value, false_smax);
6923 true_reg->smin_value = max(true_reg->smin_value, true_smin);
6924 }
48461135 6925 break;
a72dafaf 6926 }
b4e432f1 6927 case BPF_JLE:
a72dafaf
JW
6928 case BPF_JLT:
6929 {
3f50f132
JF
6930 if (is_jmp32) {
6931 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
6932 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6933
6934 false_reg->u32_min_value = max(false_reg->u32_min_value,
6935 false_umin);
6936 true_reg->u32_max_value = min(true_reg->u32_max_value,
6937 true_umax);
6938 } else {
6939 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
6940 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6941
6942 false_reg->umin_value = max(false_reg->umin_value, false_umin);
6943 true_reg->umax_value = min(true_reg->umax_value, true_umax);
6944 }
b4e432f1 6945 break;
a72dafaf 6946 }
b4e432f1 6947 case BPF_JSLE:
a72dafaf
JW
6948 case BPF_JSLT:
6949 {
3f50f132
JF
6950 if (is_jmp32) {
6951 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
6952 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 6953
3f50f132
JF
6954 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6955 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6956 } else {
6957 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
6958 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6959
6960 false_reg->smin_value = max(false_reg->smin_value, false_smin);
6961 true_reg->smax_value = min(true_reg->smax_value, true_smax);
6962 }
b4e432f1 6963 break;
a72dafaf 6964 }
48461135 6965 default:
0fc31b10 6966 return;
48461135
JB
6967 }
6968
3f50f132
JF
6969 if (is_jmp32) {
6970 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
6971 tnum_subreg(false_32off));
6972 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
6973 tnum_subreg(true_32off));
6974 __reg_combine_32_into_64(false_reg);
6975 __reg_combine_32_into_64(true_reg);
6976 } else {
6977 false_reg->var_off = false_64off;
6978 true_reg->var_off = true_64off;
6979 __reg_combine_64_into_32(false_reg);
6980 __reg_combine_64_into_32(true_reg);
6981 }
48461135
JB
6982}
6983
f1174f77
EC
6984/* Same as above, but for the case that dst_reg holds a constant and src_reg is
6985 * the variable reg.
48461135
JB
6986 */
6987static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
6988 struct bpf_reg_state *false_reg,
6989 u64 val, u32 val32,
092ed096 6990 u8 opcode, bool is_jmp32)
48461135 6991{
0fc31b10
JH
6992 /* How can we transform "a <op> b" into "b <op> a"? */
6993 static const u8 opcode_flip[16] = {
6994 /* these stay the same */
6995 [BPF_JEQ >> 4] = BPF_JEQ,
6996 [BPF_JNE >> 4] = BPF_JNE,
6997 [BPF_JSET >> 4] = BPF_JSET,
6998 /* these swap "lesser" and "greater" (L and G in the opcodes) */
6999 [BPF_JGE >> 4] = BPF_JLE,
7000 [BPF_JGT >> 4] = BPF_JLT,
7001 [BPF_JLE >> 4] = BPF_JGE,
7002 [BPF_JLT >> 4] = BPF_JGT,
7003 [BPF_JSGE >> 4] = BPF_JSLE,
7004 [BPF_JSGT >> 4] = BPF_JSLT,
7005 [BPF_JSLE >> 4] = BPF_JSGE,
7006 [BPF_JSLT >> 4] = BPF_JSGT
7007 };
7008 opcode = opcode_flip[opcode >> 4];
7009 /* This uses zero as "not present in table"; luckily the zero opcode,
7010 * BPF_JA, can't get here.
b03c9f9f 7011 */
0fc31b10 7012 if (opcode)
3f50f132 7013 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
7014}
7015
7016/* Regs are known to be equal, so intersect their min/max/var_off */
7017static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7018 struct bpf_reg_state *dst_reg)
7019{
b03c9f9f
EC
7020 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7021 dst_reg->umin_value);
7022 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7023 dst_reg->umax_value);
7024 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7025 dst_reg->smin_value);
7026 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7027 dst_reg->smax_value);
f1174f77
EC
7028 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7029 dst_reg->var_off);
b03c9f9f
EC
7030 /* We might have learned new bounds from the var_off. */
7031 __update_reg_bounds(src_reg);
7032 __update_reg_bounds(dst_reg);
7033 /* We might have learned something about the sign bit. */
7034 __reg_deduce_bounds(src_reg);
7035 __reg_deduce_bounds(dst_reg);
7036 /* We might have learned some bits from the bounds. */
7037 __reg_bound_offset(src_reg);
7038 __reg_bound_offset(dst_reg);
7039 /* Intersecting with the old var_off might have improved our bounds
7040 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7041 * then new var_off is (0; 0x7f...fc) which improves our umax.
7042 */
7043 __update_reg_bounds(src_reg);
7044 __update_reg_bounds(dst_reg);
f1174f77
EC
7045}
7046
7047static void reg_combine_min_max(struct bpf_reg_state *true_src,
7048 struct bpf_reg_state *true_dst,
7049 struct bpf_reg_state *false_src,
7050 struct bpf_reg_state *false_dst,
7051 u8 opcode)
7052{
7053 switch (opcode) {
7054 case BPF_JEQ:
7055 __reg_combine_min_max(true_src, true_dst);
7056 break;
7057 case BPF_JNE:
7058 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 7059 break;
4cabc5b1 7060 }
48461135
JB
7061}
7062
fd978bf7
JS
7063static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7064 struct bpf_reg_state *reg, u32 id,
840b9615 7065 bool is_null)
57a09bf0 7066{
840b9615 7067 if (reg_type_may_be_null(reg->type) && reg->id == id) {
f1174f77
EC
7068 /* Old offset (both fixed and variable parts) should
7069 * have been known-zero, because we don't allow pointer
7070 * arithmetic on pointers that might be NULL.
7071 */
b03c9f9f
EC
7072 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7073 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 7074 reg->off)) {
b03c9f9f
EC
7075 __mark_reg_known_zero(reg);
7076 reg->off = 0;
f1174f77
EC
7077 }
7078 if (is_null) {
7079 reg->type = SCALAR_VALUE;
840b9615 7080 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
64d85290
JS
7081 const struct bpf_map *map = reg->map_ptr;
7082
7083 if (map->inner_map_meta) {
840b9615 7084 reg->type = CONST_PTR_TO_MAP;
64d85290
JS
7085 reg->map_ptr = map->inner_map_meta;
7086 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
fada7fdc 7087 reg->type = PTR_TO_XDP_SOCK;
64d85290
JS
7088 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7089 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7090 reg->type = PTR_TO_SOCKET;
840b9615
JS
7091 } else {
7092 reg->type = PTR_TO_MAP_VALUE;
7093 }
c64b7983
JS
7094 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7095 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
7096 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7097 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
7098 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7099 reg->type = PTR_TO_TCP_SOCK;
b121b341
YS
7100 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7101 reg->type = PTR_TO_BTF_ID;
457f4436
AN
7102 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7103 reg->type = PTR_TO_MEM;
afbf21dc
YS
7104 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7105 reg->type = PTR_TO_RDONLY_BUF;
7106 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7107 reg->type = PTR_TO_RDWR_BUF;
56f668df 7108 }
1b986589
MKL
7109 if (is_null) {
7110 /* We don't need id and ref_obj_id from this point
7111 * onwards anymore, thus we should better reset it,
7112 * so that state pruning has chances to take effect.
7113 */
7114 reg->id = 0;
7115 reg->ref_obj_id = 0;
7116 } else if (!reg_may_point_to_spin_lock(reg)) {
7117 /* For not-NULL ptr, reg->ref_obj_id will be reset
7118 * in release_reg_references().
7119 *
7120 * reg->id is still used by spin_lock ptr. Other
7121 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
7122 */
7123 reg->id = 0;
56f668df 7124 }
57a09bf0
TG
7125 }
7126}
7127
c6a9efa1
PC
7128static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7129 bool is_null)
7130{
7131 struct bpf_reg_state *reg;
7132 int i;
7133
7134 for (i = 0; i < MAX_BPF_REG; i++)
7135 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7136
7137 bpf_for_each_spilled_reg(i, state, reg) {
7138 if (!reg)
7139 continue;
7140 mark_ptr_or_null_reg(state, reg, id, is_null);
7141 }
7142}
7143
57a09bf0
TG
7144/* The logic is similar to find_good_pkt_pointers(), both could eventually
7145 * be folded together at some point.
7146 */
840b9615
JS
7147static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7148 bool is_null)
57a09bf0 7149{
f4d7e40a 7150 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 7151 struct bpf_reg_state *regs = state->regs;
1b986589 7152 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 7153 u32 id = regs[regno].id;
c6a9efa1 7154 int i;
57a09bf0 7155
1b986589
MKL
7156 if (ref_obj_id && ref_obj_id == id && is_null)
7157 /* regs[regno] is in the " == NULL" branch.
7158 * No one could have freed the reference state before
7159 * doing the NULL check.
7160 */
7161 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 7162
c6a9efa1
PC
7163 for (i = 0; i <= vstate->curframe; i++)
7164 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
7165}
7166
5beca081
DB
7167static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7168 struct bpf_reg_state *dst_reg,
7169 struct bpf_reg_state *src_reg,
7170 struct bpf_verifier_state *this_branch,
7171 struct bpf_verifier_state *other_branch)
7172{
7173 if (BPF_SRC(insn->code) != BPF_X)
7174 return false;
7175
092ed096
JW
7176 /* Pointers are always 64-bit. */
7177 if (BPF_CLASS(insn->code) == BPF_JMP32)
7178 return false;
7179
5beca081
DB
7180 switch (BPF_OP(insn->code)) {
7181 case BPF_JGT:
7182 if ((dst_reg->type == PTR_TO_PACKET &&
7183 src_reg->type == PTR_TO_PACKET_END) ||
7184 (dst_reg->type == PTR_TO_PACKET_META &&
7185 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7186 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7187 find_good_pkt_pointers(this_branch, dst_reg,
7188 dst_reg->type, false);
7189 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7190 src_reg->type == PTR_TO_PACKET) ||
7191 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7192 src_reg->type == PTR_TO_PACKET_META)) {
7193 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7194 find_good_pkt_pointers(other_branch, src_reg,
7195 src_reg->type, true);
7196 } else {
7197 return false;
7198 }
7199 break;
7200 case BPF_JLT:
7201 if ((dst_reg->type == PTR_TO_PACKET &&
7202 src_reg->type == PTR_TO_PACKET_END) ||
7203 (dst_reg->type == PTR_TO_PACKET_META &&
7204 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7205 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7206 find_good_pkt_pointers(other_branch, dst_reg,
7207 dst_reg->type, true);
7208 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7209 src_reg->type == PTR_TO_PACKET) ||
7210 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7211 src_reg->type == PTR_TO_PACKET_META)) {
7212 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7213 find_good_pkt_pointers(this_branch, src_reg,
7214 src_reg->type, false);
7215 } else {
7216 return false;
7217 }
7218 break;
7219 case BPF_JGE:
7220 if ((dst_reg->type == PTR_TO_PACKET &&
7221 src_reg->type == PTR_TO_PACKET_END) ||
7222 (dst_reg->type == PTR_TO_PACKET_META &&
7223 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7224 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7225 find_good_pkt_pointers(this_branch, dst_reg,
7226 dst_reg->type, true);
7227 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7228 src_reg->type == PTR_TO_PACKET) ||
7229 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7230 src_reg->type == PTR_TO_PACKET_META)) {
7231 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7232 find_good_pkt_pointers(other_branch, src_reg,
7233 src_reg->type, false);
7234 } else {
7235 return false;
7236 }
7237 break;
7238 case BPF_JLE:
7239 if ((dst_reg->type == PTR_TO_PACKET &&
7240 src_reg->type == PTR_TO_PACKET_END) ||
7241 (dst_reg->type == PTR_TO_PACKET_META &&
7242 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7243 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7244 find_good_pkt_pointers(other_branch, dst_reg,
7245 dst_reg->type, false);
7246 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7247 src_reg->type == PTR_TO_PACKET) ||
7248 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7249 src_reg->type == PTR_TO_PACKET_META)) {
7250 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7251 find_good_pkt_pointers(this_branch, src_reg,
7252 src_reg->type, true);
7253 } else {
7254 return false;
7255 }
7256 break;
7257 default:
7258 return false;
7259 }
7260
7261 return true;
7262}
7263
58e2af8b 7264static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
7265 struct bpf_insn *insn, int *insn_idx)
7266{
f4d7e40a
AS
7267 struct bpf_verifier_state *this_branch = env->cur_state;
7268 struct bpf_verifier_state *other_branch;
7269 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 7270 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 7271 u8 opcode = BPF_OP(insn->code);
092ed096 7272 bool is_jmp32;
fb8d251e 7273 int pred = -1;
17a52670
AS
7274 int err;
7275
092ed096
JW
7276 /* Only conditional jumps are expected to reach here. */
7277 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7278 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
7279 return -EINVAL;
7280 }
7281
7282 if (BPF_SRC(insn->code) == BPF_X) {
7283 if (insn->imm != 0) {
092ed096 7284 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7285 return -EINVAL;
7286 }
7287
7288 /* check src1 operand */
dc503a8a 7289 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7290 if (err)
7291 return err;
1be7f75d
AS
7292
7293 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 7294 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
7295 insn->src_reg);
7296 return -EACCES;
7297 }
fb8d251e 7298 src_reg = &regs[insn->src_reg];
17a52670
AS
7299 } else {
7300 if (insn->src_reg != BPF_REG_0) {
092ed096 7301 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
7302 return -EINVAL;
7303 }
7304 }
7305
7306 /* check src2 operand */
dc503a8a 7307 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7308 if (err)
7309 return err;
7310
1a0dc1ac 7311 dst_reg = &regs[insn->dst_reg];
092ed096 7312 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 7313
3f50f132
JF
7314 if (BPF_SRC(insn->code) == BPF_K) {
7315 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
7316 } else if (src_reg->type == SCALAR_VALUE &&
7317 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
7318 pred = is_branch_taken(dst_reg,
7319 tnum_subreg(src_reg->var_off).value,
7320 opcode,
7321 is_jmp32);
7322 } else if (src_reg->type == SCALAR_VALUE &&
7323 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
7324 pred = is_branch_taken(dst_reg,
7325 src_reg->var_off.value,
7326 opcode,
7327 is_jmp32);
7328 }
7329
b5dc0163 7330 if (pred >= 0) {
cac616db
JF
7331 /* If we get here with a dst_reg pointer type it is because
7332 * above is_branch_taken() special cased the 0 comparison.
7333 */
7334 if (!__is_pointer_value(false, dst_reg))
7335 err = mark_chain_precision(env, insn->dst_reg);
b5dc0163
AS
7336 if (BPF_SRC(insn->code) == BPF_X && !err)
7337 err = mark_chain_precision(env, insn->src_reg);
7338 if (err)
7339 return err;
7340 }
fb8d251e
AS
7341 if (pred == 1) {
7342 /* only follow the goto, ignore fall-through */
7343 *insn_idx += insn->off;
7344 return 0;
7345 } else if (pred == 0) {
7346 /* only follow fall-through branch, since
7347 * that's where the program will go
7348 */
7349 return 0;
17a52670
AS
7350 }
7351
979d63d5
DB
7352 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
7353 false);
17a52670
AS
7354 if (!other_branch)
7355 return -EFAULT;
f4d7e40a 7356 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 7357
48461135
JB
7358 /* detect if we are comparing against a constant value so we can adjust
7359 * our min/max values for our dst register.
f1174f77
EC
7360 * this is only legit if both are scalars (or pointers to the same
7361 * object, I suppose, but we don't support that right now), because
7362 * otherwise the different base pointers mean the offsets aren't
7363 * comparable.
48461135
JB
7364 */
7365 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 7366 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 7367
f1174f77 7368 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
7369 src_reg->type == SCALAR_VALUE) {
7370 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
7371 (is_jmp32 &&
7372 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 7373 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 7374 dst_reg,
3f50f132
JF
7375 src_reg->var_off.value,
7376 tnum_subreg(src_reg->var_off).value,
092ed096
JW
7377 opcode, is_jmp32);
7378 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
7379 (is_jmp32 &&
7380 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 7381 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 7382 src_reg,
3f50f132
JF
7383 dst_reg->var_off.value,
7384 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
7385 opcode, is_jmp32);
7386 else if (!is_jmp32 &&
7387 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 7388 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
7389 reg_combine_min_max(&other_branch_regs[insn->src_reg],
7390 &other_branch_regs[insn->dst_reg],
092ed096 7391 src_reg, dst_reg, opcode);
f1174f77
EC
7392 }
7393 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 7394 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
7395 dst_reg, insn->imm, (u32)insn->imm,
7396 opcode, is_jmp32);
48461135
JB
7397 }
7398
092ed096
JW
7399 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7400 * NOTE: these optimizations below are related with pointer comparison
7401 * which will never be JMP32.
7402 */
7403 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 7404 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
7405 reg_type_may_be_null(dst_reg->type)) {
7406 /* Mark all identical registers in each branch as either
57a09bf0
TG
7407 * safe or unknown depending R == 0 or R != 0 conditional.
7408 */
840b9615
JS
7409 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7410 opcode == BPF_JNE);
7411 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7412 opcode == BPF_JEQ);
5beca081
DB
7413 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7414 this_branch, other_branch) &&
7415 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
7416 verbose(env, "R%d pointer comparison prohibited\n",
7417 insn->dst_reg);
1be7f75d 7418 return -EACCES;
17a52670 7419 }
06ee7115 7420 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 7421 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
7422 return 0;
7423}
7424
17a52670 7425/* verify BPF_LD_IMM64 instruction */
58e2af8b 7426static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7427{
d8eca5bb 7428 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 7429 struct bpf_reg_state *regs = cur_regs(env);
d8eca5bb 7430 struct bpf_map *map;
17a52670
AS
7431 int err;
7432
7433 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 7434 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
7435 return -EINVAL;
7436 }
7437 if (insn->off != 0) {
61bd5218 7438 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
7439 return -EINVAL;
7440 }
7441
dc503a8a 7442 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7443 if (err)
7444 return err;
7445
6b173873 7446 if (insn->src_reg == 0) {
6b173873
JK
7447 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7448
f1174f77 7449 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 7450 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 7451 return 0;
6b173873 7452 }
17a52670 7453
d8eca5bb
DB
7454 map = env->used_maps[aux->map_index];
7455 mark_reg_known_zero(env, regs, insn->dst_reg);
7456 regs[insn->dst_reg].map_ptr = map;
7457
7458 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7459 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
7460 regs[insn->dst_reg].off = aux->map_off;
7461 if (map_value_has_spin_lock(map))
7462 regs[insn->dst_reg].id = ++env->id_gen;
7463 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7464 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
7465 } else {
7466 verbose(env, "bpf verifier is misconfigured\n");
7467 return -EINVAL;
7468 }
17a52670 7469
17a52670
AS
7470 return 0;
7471}
7472
96be4325
DB
7473static bool may_access_skb(enum bpf_prog_type type)
7474{
7475 switch (type) {
7476 case BPF_PROG_TYPE_SOCKET_FILTER:
7477 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 7478 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
7479 return true;
7480 default:
7481 return false;
7482 }
7483}
7484
ddd872bc
AS
7485/* verify safety of LD_ABS|LD_IND instructions:
7486 * - they can only appear in the programs where ctx == skb
7487 * - since they are wrappers of function calls, they scratch R1-R5 registers,
7488 * preserve R6-R9, and store return value into R0
7489 *
7490 * Implicit input:
7491 * ctx == skb == R6 == CTX
7492 *
7493 * Explicit input:
7494 * SRC == any register
7495 * IMM == 32-bit immediate
7496 *
7497 * Output:
7498 * R0 - 8/16/32-bit skb data converted to cpu endianness
7499 */
58e2af8b 7500static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 7501{
638f5b90 7502 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 7503 static const int ctx_reg = BPF_REG_6;
ddd872bc 7504 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
7505 int i, err;
7506
7e40781c 7507 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 7508 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
7509 return -EINVAL;
7510 }
7511
e0cea7ce
DB
7512 if (!env->ops->gen_ld_abs) {
7513 verbose(env, "bpf verifier is misconfigured\n");
7514 return -EINVAL;
7515 }
7516
f910cefa 7517 if (env->subprog_cnt > 1) {
f4d7e40a
AS
7518 /* when program has LD_ABS insn JITs and interpreter assume
7519 * that r1 == ctx == skb which is not the case for callees
7520 * that can have arbitrary arguments. It's problematic
7521 * for main prog as well since JITs would need to analyze
7522 * all functions in order to make proper register save/restore
7523 * decisions in the main prog. Hence disallow LD_ABS with calls
7524 */
7525 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
7526 return -EINVAL;
7527 }
7528
ddd872bc 7529 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 7530 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 7531 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 7532 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
7533 return -EINVAL;
7534 }
7535
7536 /* check whether implicit source operand (register R6) is readable */
6d4f151a 7537 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
7538 if (err)
7539 return err;
7540
fd978bf7
JS
7541 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7542 * gen_ld_abs() may terminate the program at runtime, leading to
7543 * reference leak.
7544 */
7545 err = check_reference_leak(env);
7546 if (err) {
7547 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7548 return err;
7549 }
7550
d83525ca
AS
7551 if (env->cur_state->active_spin_lock) {
7552 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7553 return -EINVAL;
7554 }
7555
6d4f151a 7556 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
7557 verbose(env,
7558 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
7559 return -EINVAL;
7560 }
7561
7562 if (mode == BPF_IND) {
7563 /* check explicit source operand */
dc503a8a 7564 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
7565 if (err)
7566 return err;
7567 }
7568
6d4f151a
DB
7569 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7570 if (err < 0)
7571 return err;
7572
ddd872bc 7573 /* reset caller saved regs to unreadable */
dc503a8a 7574 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 7575 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
7576 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7577 }
ddd872bc
AS
7578
7579 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
7580 * the value fetched from the packet.
7581 * Already marked as written above.
ddd872bc 7582 */
61bd5218 7583 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
7584 /* ld_abs load up to 32-bit skb data. */
7585 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
7586 return 0;
7587}
7588
390ee7e2
AS
7589static int check_return_code(struct bpf_verifier_env *env)
7590{
5cf1e914 7591 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 7592 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
7593 struct bpf_reg_state *reg;
7594 struct tnum range = tnum_range(0, 1);
7e40781c 7595 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997
MKL
7596 int err;
7597
9e4e01df 7598 /* LSM and struct_ops func-ptr's return type could be "void" */
7e40781c
UP
7599 if ((prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7600 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
7601 !prog->aux->attach_func_proto->type)
7602 return 0;
7603
7604 /* eBPF calling convetion is such that R0 is used
7605 * to return the value from eBPF program.
7606 * Make sure that it's readable at this time
7607 * of bpf_exit, which means that program wrote
7608 * something into it earlier
7609 */
7610 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7611 if (err)
7612 return err;
7613
7614 if (is_pointer_value(env, BPF_REG_0)) {
7615 verbose(env, "R0 leaks addr as return value\n");
7616 return -EACCES;
7617 }
390ee7e2 7618
7e40781c 7619 switch (prog_type) {
983695fa
DB
7620 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7621 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
7622 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7623 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7624 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7625 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7626 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 7627 range = tnum_range(1, 1);
ed4ed404 7628 break;
390ee7e2 7629 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 7630 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7631 range = tnum_range(0, 3);
7632 enforce_attach_type_range = tnum_range(2, 3);
7633 }
ed4ed404 7634 break;
390ee7e2
AS
7635 case BPF_PROG_TYPE_CGROUP_SOCK:
7636 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 7637 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 7638 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 7639 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 7640 break;
15ab09bd
AS
7641 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7642 if (!env->prog->aux->attach_btf_id)
7643 return 0;
7644 range = tnum_const(0);
7645 break;
15d83c4d 7646 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
7647 switch (env->prog->expected_attach_type) {
7648 case BPF_TRACE_FENTRY:
7649 case BPF_TRACE_FEXIT:
7650 range = tnum_const(0);
7651 break;
7652 case BPF_TRACE_RAW_TP:
7653 case BPF_MODIFY_RETURN:
15d83c4d 7654 return 0;
2ec0616e
DB
7655 case BPF_TRACE_ITER:
7656 break;
e92888c7
YS
7657 default:
7658 return -ENOTSUPP;
7659 }
15d83c4d 7660 break;
e9ddbb77
JS
7661 case BPF_PROG_TYPE_SK_LOOKUP:
7662 range = tnum_range(SK_DROP, SK_PASS);
7663 break;
e92888c7
YS
7664 case BPF_PROG_TYPE_EXT:
7665 /* freplace program can return anything as its return value
7666 * depends on the to-be-replaced kernel func or bpf program.
7667 */
390ee7e2
AS
7668 default:
7669 return 0;
7670 }
7671
638f5b90 7672 reg = cur_regs(env) + BPF_REG_0;
390ee7e2 7673 if (reg->type != SCALAR_VALUE) {
61bd5218 7674 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
7675 reg_type_str[reg->type]);
7676 return -EINVAL;
7677 }
7678
7679 if (!tnum_in(range, reg->var_off)) {
5cf1e914 7680 char tn_buf[48];
7681
61bd5218 7682 verbose(env, "At program exit the register R0 ");
390ee7e2 7683 if (!tnum_is_unknown(reg->var_off)) {
390ee7e2 7684 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 7685 verbose(env, "has value %s", tn_buf);
390ee7e2 7686 } else {
61bd5218 7687 verbose(env, "has unknown scalar value");
390ee7e2 7688 }
5cf1e914 7689 tnum_strn(tn_buf, sizeof(tn_buf), range);
983695fa 7690 verbose(env, " should have been in %s\n", tn_buf);
390ee7e2
AS
7691 return -EINVAL;
7692 }
5cf1e914 7693
7694 if (!tnum_is_unknown(enforce_attach_type_range) &&
7695 tnum_in(enforce_attach_type_range, reg->var_off))
7696 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
7697 return 0;
7698}
7699
475fb78f
AS
7700/* non-recursive DFS pseudo code
7701 * 1 procedure DFS-iterative(G,v):
7702 * 2 label v as discovered
7703 * 3 let S be a stack
7704 * 4 S.push(v)
7705 * 5 while S is not empty
7706 * 6 t <- S.pop()
7707 * 7 if t is what we're looking for:
7708 * 8 return t
7709 * 9 for all edges e in G.adjacentEdges(t) do
7710 * 10 if edge e is already labelled
7711 * 11 continue with the next edge
7712 * 12 w <- G.adjacentVertex(t,e)
7713 * 13 if vertex w is not discovered and not explored
7714 * 14 label e as tree-edge
7715 * 15 label w as discovered
7716 * 16 S.push(w)
7717 * 17 continue at 5
7718 * 18 else if vertex w is discovered
7719 * 19 label e as back-edge
7720 * 20 else
7721 * 21 // vertex w is explored
7722 * 22 label e as forward- or cross-edge
7723 * 23 label t as explored
7724 * 24 S.pop()
7725 *
7726 * convention:
7727 * 0x10 - discovered
7728 * 0x11 - discovered and fall-through edge labelled
7729 * 0x12 - discovered and fall-through and branch edges labelled
7730 * 0x20 - explored
7731 */
7732
7733enum {
7734 DISCOVERED = 0x10,
7735 EXPLORED = 0x20,
7736 FALLTHROUGH = 1,
7737 BRANCH = 2,
7738};
7739
dc2a4ebc
AS
7740static u32 state_htab_size(struct bpf_verifier_env *env)
7741{
7742 return env->prog->len;
7743}
7744
5d839021
AS
7745static struct bpf_verifier_state_list **explored_state(
7746 struct bpf_verifier_env *env,
7747 int idx)
7748{
dc2a4ebc
AS
7749 struct bpf_verifier_state *cur = env->cur_state;
7750 struct bpf_func_state *state = cur->frame[cur->curframe];
7751
7752 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
7753}
7754
7755static void init_explored_state(struct bpf_verifier_env *env, int idx)
7756{
a8f500af 7757 env->insn_aux_data[idx].prune_point = true;
5d839021 7758}
f1bca824 7759
475fb78f
AS
7760/* t, w, e - match pseudo-code above:
7761 * t - index of current instruction
7762 * w - next instruction
7763 * e - edge
7764 */
2589726d
AS
7765static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7766 bool loop_ok)
475fb78f 7767{
7df737e9
AS
7768 int *insn_stack = env->cfg.insn_stack;
7769 int *insn_state = env->cfg.insn_state;
7770
475fb78f
AS
7771 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7772 return 0;
7773
7774 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7775 return 0;
7776
7777 if (w < 0 || w >= env->prog->len) {
d9762e84 7778 verbose_linfo(env, t, "%d: ", t);
61bd5218 7779 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
7780 return -EINVAL;
7781 }
7782
f1bca824
AS
7783 if (e == BRANCH)
7784 /* mark branch target for state pruning */
5d839021 7785 init_explored_state(env, w);
f1bca824 7786
475fb78f
AS
7787 if (insn_state[w] == 0) {
7788 /* tree-edge */
7789 insn_state[t] = DISCOVERED | e;
7790 insn_state[w] = DISCOVERED;
7df737e9 7791 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 7792 return -E2BIG;
7df737e9 7793 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
7794 return 1;
7795 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 7796 if (loop_ok && env->bpf_capable)
2589726d 7797 return 0;
d9762e84
MKL
7798 verbose_linfo(env, t, "%d: ", t);
7799 verbose_linfo(env, w, "%d: ", w);
61bd5218 7800 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
7801 return -EINVAL;
7802 } else if (insn_state[w] == EXPLORED) {
7803 /* forward- or cross-edge */
7804 insn_state[t] = DISCOVERED | e;
7805 } else {
61bd5218 7806 verbose(env, "insn state internal bug\n");
475fb78f
AS
7807 return -EFAULT;
7808 }
7809 return 0;
7810}
7811
7812/* non-recursive depth-first-search to detect loops in BPF program
7813 * loop == back-edge in directed graph
7814 */
58e2af8b 7815static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
7816{
7817 struct bpf_insn *insns = env->prog->insnsi;
7818 int insn_cnt = env->prog->len;
7df737e9 7819 int *insn_stack, *insn_state;
475fb78f
AS
7820 int ret = 0;
7821 int i, t;
7822
7df737e9 7823 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
7824 if (!insn_state)
7825 return -ENOMEM;
7826
7df737e9 7827 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 7828 if (!insn_stack) {
71dde681 7829 kvfree(insn_state);
475fb78f
AS
7830 return -ENOMEM;
7831 }
7832
7833 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7834 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 7835 env->cfg.cur_stack = 1;
475fb78f
AS
7836
7837peek_stack:
7df737e9 7838 if (env->cfg.cur_stack == 0)
475fb78f 7839 goto check_state;
7df737e9 7840 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 7841
092ed096
JW
7842 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7843 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
7844 u8 opcode = BPF_OP(insns[t].code);
7845
7846 if (opcode == BPF_EXIT) {
7847 goto mark_explored;
7848 } else if (opcode == BPF_CALL) {
2589726d 7849 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
7850 if (ret == 1)
7851 goto peek_stack;
7852 else if (ret < 0)
7853 goto err_free;
07016151 7854 if (t + 1 < insn_cnt)
5d839021 7855 init_explored_state(env, t + 1);
cc8b0b92 7856 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5d839021 7857 init_explored_state(env, t);
2589726d
AS
7858 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7859 env, false);
cc8b0b92
AS
7860 if (ret == 1)
7861 goto peek_stack;
7862 else if (ret < 0)
7863 goto err_free;
7864 }
475fb78f
AS
7865 } else if (opcode == BPF_JA) {
7866 if (BPF_SRC(insns[t].code) != BPF_K) {
7867 ret = -EINVAL;
7868 goto err_free;
7869 }
7870 /* unconditional jump with single edge */
7871 ret = push_insn(t, t + insns[t].off + 1,
2589726d 7872 FALLTHROUGH, env, true);
475fb78f
AS
7873 if (ret == 1)
7874 goto peek_stack;
7875 else if (ret < 0)
7876 goto err_free;
b5dc0163
AS
7877 /* unconditional jmp is not a good pruning point,
7878 * but it's marked, since backtracking needs
7879 * to record jmp history in is_state_visited().
7880 */
7881 init_explored_state(env, t + insns[t].off + 1);
f1bca824
AS
7882 /* tell verifier to check for equivalent states
7883 * after every call and jump
7884 */
c3de6317 7885 if (t + 1 < insn_cnt)
5d839021 7886 init_explored_state(env, t + 1);
475fb78f
AS
7887 } else {
7888 /* conditional jump with two edges */
5d839021 7889 init_explored_state(env, t);
2589726d 7890 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
475fb78f
AS
7891 if (ret == 1)
7892 goto peek_stack;
7893 else if (ret < 0)
7894 goto err_free;
7895
2589726d 7896 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
475fb78f
AS
7897 if (ret == 1)
7898 goto peek_stack;
7899 else if (ret < 0)
7900 goto err_free;
7901 }
7902 } else {
7903 /* all other non-branch instructions with single
7904 * fall-through edge
7905 */
2589726d 7906 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
7907 if (ret == 1)
7908 goto peek_stack;
7909 else if (ret < 0)
7910 goto err_free;
7911 }
7912
7913mark_explored:
7914 insn_state[t] = EXPLORED;
7df737e9 7915 if (env->cfg.cur_stack-- <= 0) {
61bd5218 7916 verbose(env, "pop stack internal bug\n");
475fb78f
AS
7917 ret = -EFAULT;
7918 goto err_free;
7919 }
7920 goto peek_stack;
7921
7922check_state:
7923 for (i = 0; i < insn_cnt; i++) {
7924 if (insn_state[i] != EXPLORED) {
61bd5218 7925 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
7926 ret = -EINVAL;
7927 goto err_free;
7928 }
7929 }
7930 ret = 0; /* cfg looks good */
7931
7932err_free:
71dde681
AS
7933 kvfree(insn_state);
7934 kvfree(insn_stack);
7df737e9 7935 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
7936 return ret;
7937}
7938
838e9690
YS
7939/* The minimum supported BTF func info size */
7940#define MIN_BPF_FUNCINFO_SIZE 8
7941#define MAX_FUNCINFO_REC_SIZE 252
7942
c454a46b
MKL
7943static int check_btf_func(struct bpf_verifier_env *env,
7944 const union bpf_attr *attr,
7945 union bpf_attr __user *uattr)
838e9690 7946{
d0b2818e 7947 u32 i, nfuncs, urec_size, min_size;
838e9690 7948 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 7949 struct bpf_func_info *krecord;
8c1b6e69 7950 struct bpf_func_info_aux *info_aux = NULL;
838e9690 7951 const struct btf_type *type;
c454a46b
MKL
7952 struct bpf_prog *prog;
7953 const struct btf *btf;
838e9690 7954 void __user *urecord;
d0b2818e 7955 u32 prev_offset = 0;
e7ed83d6 7956 int ret = -ENOMEM;
838e9690
YS
7957
7958 nfuncs = attr->func_info_cnt;
7959 if (!nfuncs)
7960 return 0;
7961
7962 if (nfuncs != env->subprog_cnt) {
7963 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
7964 return -EINVAL;
7965 }
7966
7967 urec_size = attr->func_info_rec_size;
7968 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
7969 urec_size > MAX_FUNCINFO_REC_SIZE ||
7970 urec_size % sizeof(u32)) {
7971 verbose(env, "invalid func info rec size %u\n", urec_size);
7972 return -EINVAL;
7973 }
7974
c454a46b
MKL
7975 prog = env->prog;
7976 btf = prog->aux->btf;
838e9690
YS
7977
7978 urecord = u64_to_user_ptr(attr->func_info);
7979 min_size = min_t(u32, krec_size, urec_size);
7980
ba64e7d8 7981 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
7982 if (!krecord)
7983 return -ENOMEM;
8c1b6e69
AS
7984 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
7985 if (!info_aux)
7986 goto err_free;
ba64e7d8 7987
838e9690
YS
7988 for (i = 0; i < nfuncs; i++) {
7989 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
7990 if (ret) {
7991 if (ret == -E2BIG) {
7992 verbose(env, "nonzero tailing record in func info");
7993 /* set the size kernel expects so loader can zero
7994 * out the rest of the record.
7995 */
7996 if (put_user(min_size, &uattr->func_info_rec_size))
7997 ret = -EFAULT;
7998 }
c454a46b 7999 goto err_free;
838e9690
YS
8000 }
8001
ba64e7d8 8002 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 8003 ret = -EFAULT;
c454a46b 8004 goto err_free;
838e9690
YS
8005 }
8006
d30d42e0 8007 /* check insn_off */
838e9690 8008 if (i == 0) {
d30d42e0 8009 if (krecord[i].insn_off) {
838e9690 8010 verbose(env,
d30d42e0
MKL
8011 "nonzero insn_off %u for the first func info record",
8012 krecord[i].insn_off);
838e9690 8013 ret = -EINVAL;
c454a46b 8014 goto err_free;
838e9690 8015 }
d30d42e0 8016 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
8017 verbose(env,
8018 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 8019 krecord[i].insn_off, prev_offset);
838e9690 8020 ret = -EINVAL;
c454a46b 8021 goto err_free;
838e9690
YS
8022 }
8023
d30d42e0 8024 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690
YS
8025 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8026 ret = -EINVAL;
c454a46b 8027 goto err_free;
838e9690
YS
8028 }
8029
8030 /* check type_id */
ba64e7d8 8031 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 8032 if (!type || !btf_type_is_func(type)) {
838e9690 8033 verbose(env, "invalid type id %d in func info",
ba64e7d8 8034 krecord[i].type_id);
838e9690 8035 ret = -EINVAL;
c454a46b 8036 goto err_free;
838e9690 8037 }
51c39bb1 8038 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
d30d42e0 8039 prev_offset = krecord[i].insn_off;
838e9690
YS
8040 urecord += urec_size;
8041 }
8042
ba64e7d8
YS
8043 prog->aux->func_info = krecord;
8044 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 8045 prog->aux->func_info_aux = info_aux;
838e9690
YS
8046 return 0;
8047
c454a46b 8048err_free:
ba64e7d8 8049 kvfree(krecord);
8c1b6e69 8050 kfree(info_aux);
838e9690
YS
8051 return ret;
8052}
8053
ba64e7d8
YS
8054static void adjust_btf_func(struct bpf_verifier_env *env)
8055{
8c1b6e69 8056 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
8057 int i;
8058
8c1b6e69 8059 if (!aux->func_info)
ba64e7d8
YS
8060 return;
8061
8062 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 8063 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
8064}
8065
c454a46b
MKL
8066#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8067 sizeof(((struct bpf_line_info *)(0))->line_col))
8068#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8069
8070static int check_btf_line(struct bpf_verifier_env *env,
8071 const union bpf_attr *attr,
8072 union bpf_attr __user *uattr)
8073{
8074 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8075 struct bpf_subprog_info *sub;
8076 struct bpf_line_info *linfo;
8077 struct bpf_prog *prog;
8078 const struct btf *btf;
8079 void __user *ulinfo;
8080 int err;
8081
8082 nr_linfo = attr->line_info_cnt;
8083 if (!nr_linfo)
8084 return 0;
8085
8086 rec_size = attr->line_info_rec_size;
8087 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8088 rec_size > MAX_LINEINFO_REC_SIZE ||
8089 rec_size & (sizeof(u32) - 1))
8090 return -EINVAL;
8091
8092 /* Need to zero it in case the userspace may
8093 * pass in a smaller bpf_line_info object.
8094 */
8095 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8096 GFP_KERNEL | __GFP_NOWARN);
8097 if (!linfo)
8098 return -ENOMEM;
8099
8100 prog = env->prog;
8101 btf = prog->aux->btf;
8102
8103 s = 0;
8104 sub = env->subprog_info;
8105 ulinfo = u64_to_user_ptr(attr->line_info);
8106 expected_size = sizeof(struct bpf_line_info);
8107 ncopy = min_t(u32, expected_size, rec_size);
8108 for (i = 0; i < nr_linfo; i++) {
8109 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8110 if (err) {
8111 if (err == -E2BIG) {
8112 verbose(env, "nonzero tailing record in line_info");
8113 if (put_user(expected_size,
8114 &uattr->line_info_rec_size))
8115 err = -EFAULT;
8116 }
8117 goto err_free;
8118 }
8119
8120 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8121 err = -EFAULT;
8122 goto err_free;
8123 }
8124
8125 /*
8126 * Check insn_off to ensure
8127 * 1) strictly increasing AND
8128 * 2) bounded by prog->len
8129 *
8130 * The linfo[0].insn_off == 0 check logically falls into
8131 * the later "missing bpf_line_info for func..." case
8132 * because the first linfo[0].insn_off must be the
8133 * first sub also and the first sub must have
8134 * subprog_info[0].start == 0.
8135 */
8136 if ((i && linfo[i].insn_off <= prev_offset) ||
8137 linfo[i].insn_off >= prog->len) {
8138 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8139 i, linfo[i].insn_off, prev_offset,
8140 prog->len);
8141 err = -EINVAL;
8142 goto err_free;
8143 }
8144
fdbaa0be
MKL
8145 if (!prog->insnsi[linfo[i].insn_off].code) {
8146 verbose(env,
8147 "Invalid insn code at line_info[%u].insn_off\n",
8148 i);
8149 err = -EINVAL;
8150 goto err_free;
8151 }
8152
23127b33
MKL
8153 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8154 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
8155 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8156 err = -EINVAL;
8157 goto err_free;
8158 }
8159
8160 if (s != env->subprog_cnt) {
8161 if (linfo[i].insn_off == sub[s].start) {
8162 sub[s].linfo_idx = i;
8163 s++;
8164 } else if (sub[s].start < linfo[i].insn_off) {
8165 verbose(env, "missing bpf_line_info for func#%u\n", s);
8166 err = -EINVAL;
8167 goto err_free;
8168 }
8169 }
8170
8171 prev_offset = linfo[i].insn_off;
8172 ulinfo += rec_size;
8173 }
8174
8175 if (s != env->subprog_cnt) {
8176 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8177 env->subprog_cnt - s, s);
8178 err = -EINVAL;
8179 goto err_free;
8180 }
8181
8182 prog->aux->linfo = linfo;
8183 prog->aux->nr_linfo = nr_linfo;
8184
8185 return 0;
8186
8187err_free:
8188 kvfree(linfo);
8189 return err;
8190}
8191
8192static int check_btf_info(struct bpf_verifier_env *env,
8193 const union bpf_attr *attr,
8194 union bpf_attr __user *uattr)
8195{
8196 struct btf *btf;
8197 int err;
8198
8199 if (!attr->func_info_cnt && !attr->line_info_cnt)
8200 return 0;
8201
8202 btf = btf_get_by_fd(attr->prog_btf_fd);
8203 if (IS_ERR(btf))
8204 return PTR_ERR(btf);
8205 env->prog->aux->btf = btf;
8206
8207 err = check_btf_func(env, attr, uattr);
8208 if (err)
8209 return err;
8210
8211 err = check_btf_line(env, attr, uattr);
8212 if (err)
8213 return err;
8214
8215 return 0;
ba64e7d8
YS
8216}
8217
f1174f77
EC
8218/* check %cur's range satisfies %old's */
8219static bool range_within(struct bpf_reg_state *old,
8220 struct bpf_reg_state *cur)
8221{
b03c9f9f
EC
8222 return old->umin_value <= cur->umin_value &&
8223 old->umax_value >= cur->umax_value &&
8224 old->smin_value <= cur->smin_value &&
8225 old->smax_value >= cur->smax_value;
f1174f77
EC
8226}
8227
8228/* Maximum number of register states that can exist at once */
8229#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
8230struct idpair {
8231 u32 old;
8232 u32 cur;
8233};
8234
8235/* If in the old state two registers had the same id, then they need to have
8236 * the same id in the new state as well. But that id could be different from
8237 * the old state, so we need to track the mapping from old to new ids.
8238 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
8239 * regs with old id 5 must also have new id 9 for the new state to be safe. But
8240 * regs with a different old id could still have new id 9, we don't care about
8241 * that.
8242 * So we look through our idmap to see if this old id has been seen before. If
8243 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 8244 */
f1174f77 8245static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 8246{
f1174f77 8247 unsigned int i;
969bf05e 8248
f1174f77
EC
8249 for (i = 0; i < ID_MAP_SIZE; i++) {
8250 if (!idmap[i].old) {
8251 /* Reached an empty slot; haven't seen this id before */
8252 idmap[i].old = old_id;
8253 idmap[i].cur = cur_id;
8254 return true;
8255 }
8256 if (idmap[i].old == old_id)
8257 return idmap[i].cur == cur_id;
8258 }
8259 /* We ran out of idmap slots, which should be impossible */
8260 WARN_ON_ONCE(1);
8261 return false;
8262}
8263
9242b5f5
AS
8264static void clean_func_state(struct bpf_verifier_env *env,
8265 struct bpf_func_state *st)
8266{
8267 enum bpf_reg_liveness live;
8268 int i, j;
8269
8270 for (i = 0; i < BPF_REG_FP; i++) {
8271 live = st->regs[i].live;
8272 /* liveness must not touch this register anymore */
8273 st->regs[i].live |= REG_LIVE_DONE;
8274 if (!(live & REG_LIVE_READ))
8275 /* since the register is unused, clear its state
8276 * to make further comparison simpler
8277 */
f54c7898 8278 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
8279 }
8280
8281 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
8282 live = st->stack[i].spilled_ptr.live;
8283 /* liveness must not touch this stack slot anymore */
8284 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
8285 if (!(live & REG_LIVE_READ)) {
f54c7898 8286 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
8287 for (j = 0; j < BPF_REG_SIZE; j++)
8288 st->stack[i].slot_type[j] = STACK_INVALID;
8289 }
8290 }
8291}
8292
8293static void clean_verifier_state(struct bpf_verifier_env *env,
8294 struct bpf_verifier_state *st)
8295{
8296 int i;
8297
8298 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
8299 /* all regs in this state in all frames were already marked */
8300 return;
8301
8302 for (i = 0; i <= st->curframe; i++)
8303 clean_func_state(env, st->frame[i]);
8304}
8305
8306/* the parentage chains form a tree.
8307 * the verifier states are added to state lists at given insn and
8308 * pushed into state stack for future exploration.
8309 * when the verifier reaches bpf_exit insn some of the verifer states
8310 * stored in the state lists have their final liveness state already,
8311 * but a lot of states will get revised from liveness point of view when
8312 * the verifier explores other branches.
8313 * Example:
8314 * 1: r0 = 1
8315 * 2: if r1 == 100 goto pc+1
8316 * 3: r0 = 2
8317 * 4: exit
8318 * when the verifier reaches exit insn the register r0 in the state list of
8319 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
8320 * of insn 2 and goes exploring further. At the insn 4 it will walk the
8321 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
8322 *
8323 * Since the verifier pushes the branch states as it sees them while exploring
8324 * the program the condition of walking the branch instruction for the second
8325 * time means that all states below this branch were already explored and
8326 * their final liveness markes are already propagated.
8327 * Hence when the verifier completes the search of state list in is_state_visited()
8328 * we can call this clean_live_states() function to mark all liveness states
8329 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
8330 * will not be used.
8331 * This function also clears the registers and stack for states that !READ
8332 * to simplify state merging.
8333 *
8334 * Important note here that walking the same branch instruction in the callee
8335 * doesn't meant that the states are DONE. The verifier has to compare
8336 * the callsites
8337 */
8338static void clean_live_states(struct bpf_verifier_env *env, int insn,
8339 struct bpf_verifier_state *cur)
8340{
8341 struct bpf_verifier_state_list *sl;
8342 int i;
8343
5d839021 8344 sl = *explored_state(env, insn);
a8f500af 8345 while (sl) {
2589726d
AS
8346 if (sl->state.branches)
8347 goto next;
dc2a4ebc
AS
8348 if (sl->state.insn_idx != insn ||
8349 sl->state.curframe != cur->curframe)
9242b5f5
AS
8350 goto next;
8351 for (i = 0; i <= cur->curframe; i++)
8352 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
8353 goto next;
8354 clean_verifier_state(env, &sl->state);
8355next:
8356 sl = sl->next;
8357 }
8358}
8359
f1174f77 8360/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
8361static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8362 struct idpair *idmap)
f1174f77 8363{
f4d7e40a
AS
8364 bool equal;
8365
dc503a8a
EC
8366 if (!(rold->live & REG_LIVE_READ))
8367 /* explored state didn't use this */
8368 return true;
8369
679c782d 8370 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
8371
8372 if (rold->type == PTR_TO_STACK)
8373 /* two stack pointers are equal only if they're pointing to
8374 * the same stack frame, since fp-8 in foo != fp-8 in bar
8375 */
8376 return equal && rold->frameno == rcur->frameno;
8377
8378 if (equal)
969bf05e
AS
8379 return true;
8380
f1174f77
EC
8381 if (rold->type == NOT_INIT)
8382 /* explored state can't have used this */
969bf05e 8383 return true;
f1174f77
EC
8384 if (rcur->type == NOT_INIT)
8385 return false;
8386 switch (rold->type) {
8387 case SCALAR_VALUE:
8388 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
8389 if (!rold->precise && !rcur->precise)
8390 return true;
f1174f77
EC
8391 /* new val must satisfy old val knowledge */
8392 return range_within(rold, rcur) &&
8393 tnum_in(rold->var_off, rcur->var_off);
8394 } else {
179d1c56
JH
8395 /* We're trying to use a pointer in place of a scalar.
8396 * Even if the scalar was unbounded, this could lead to
8397 * pointer leaks because scalars are allowed to leak
8398 * while pointers are not. We could make this safe in
8399 * special cases if root is calling us, but it's
8400 * probably not worth the hassle.
f1174f77 8401 */
179d1c56 8402 return false;
f1174f77
EC
8403 }
8404 case PTR_TO_MAP_VALUE:
1b688a19
EC
8405 /* If the new min/max/var_off satisfy the old ones and
8406 * everything else matches, we are OK.
d83525ca
AS
8407 * 'id' is not compared, since it's only used for maps with
8408 * bpf_spin_lock inside map element and in such cases if
8409 * the rest of the prog is valid for one map element then
8410 * it's valid for all map elements regardless of the key
8411 * used in bpf_map_lookup()
1b688a19
EC
8412 */
8413 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8414 range_within(rold, rcur) &&
8415 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
8416 case PTR_TO_MAP_VALUE_OR_NULL:
8417 /* a PTR_TO_MAP_VALUE could be safe to use as a
8418 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8419 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8420 * checked, doing so could have affected others with the same
8421 * id, and we can't check for that because we lost the id when
8422 * we converted to a PTR_TO_MAP_VALUE.
8423 */
8424 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8425 return false;
8426 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8427 return false;
8428 /* Check our ids match any regs they're supposed to */
8429 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 8430 case PTR_TO_PACKET_META:
f1174f77 8431 case PTR_TO_PACKET:
de8f3a83 8432 if (rcur->type != rold->type)
f1174f77
EC
8433 return false;
8434 /* We must have at least as much range as the old ptr
8435 * did, so that any accesses which were safe before are
8436 * still safe. This is true even if old range < old off,
8437 * since someone could have accessed through (ptr - k), or
8438 * even done ptr -= k in a register, to get a safe access.
8439 */
8440 if (rold->range > rcur->range)
8441 return false;
8442 /* If the offsets don't match, we can't trust our alignment;
8443 * nor can we be sure that we won't fall out of range.
8444 */
8445 if (rold->off != rcur->off)
8446 return false;
8447 /* id relations must be preserved */
8448 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8449 return false;
8450 /* new val must satisfy old val knowledge */
8451 return range_within(rold, rcur) &&
8452 tnum_in(rold->var_off, rcur->var_off);
8453 case PTR_TO_CTX:
8454 case CONST_PTR_TO_MAP:
f1174f77 8455 case PTR_TO_PACKET_END:
d58e468b 8456 case PTR_TO_FLOW_KEYS:
c64b7983
JS
8457 case PTR_TO_SOCKET:
8458 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
8459 case PTR_TO_SOCK_COMMON:
8460 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
8461 case PTR_TO_TCP_SOCK:
8462 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 8463 case PTR_TO_XDP_SOCK:
f1174f77
EC
8464 /* Only valid matches are exact, which memcmp() above
8465 * would have accepted
8466 */
8467 default:
8468 /* Don't know what's going on, just say it's not safe */
8469 return false;
8470 }
969bf05e 8471
f1174f77
EC
8472 /* Shouldn't get here; if we do, say it's not safe */
8473 WARN_ON_ONCE(1);
969bf05e
AS
8474 return false;
8475}
8476
f4d7e40a
AS
8477static bool stacksafe(struct bpf_func_state *old,
8478 struct bpf_func_state *cur,
638f5b90
AS
8479 struct idpair *idmap)
8480{
8481 int i, spi;
8482
638f5b90
AS
8483 /* walk slots of the explored stack and ignore any additional
8484 * slots in the current stack, since explored(safe) state
8485 * didn't use them
8486 */
8487 for (i = 0; i < old->allocated_stack; i++) {
8488 spi = i / BPF_REG_SIZE;
8489
b233920c
AS
8490 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8491 i += BPF_REG_SIZE - 1;
cc2b14d5 8492 /* explored state didn't use this */
fd05e57b 8493 continue;
b233920c 8494 }
cc2b14d5 8495
638f5b90
AS
8496 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8497 continue;
19e2dbb7
AS
8498
8499 /* explored stack has more populated slots than current stack
8500 * and these slots were used
8501 */
8502 if (i >= cur->allocated_stack)
8503 return false;
8504
cc2b14d5
AS
8505 /* if old state was safe with misc data in the stack
8506 * it will be safe with zero-initialized stack.
8507 * The opposite is not true
8508 */
8509 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8510 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8511 continue;
638f5b90
AS
8512 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8513 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8514 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 8515 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
8516 * this verifier states are not equivalent,
8517 * return false to continue verification of this path
8518 */
8519 return false;
8520 if (i % BPF_REG_SIZE)
8521 continue;
8522 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8523 continue;
8524 if (!regsafe(&old->stack[spi].spilled_ptr,
8525 &cur->stack[spi].spilled_ptr,
8526 idmap))
8527 /* when explored and current stack slot are both storing
8528 * spilled registers, check that stored pointers types
8529 * are the same as well.
8530 * Ex: explored safe path could have stored
8531 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8532 * but current path has stored:
8533 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8534 * such verifier states are not equivalent.
8535 * return false to continue verification of this path
8536 */
8537 return false;
8538 }
8539 return true;
8540}
8541
fd978bf7
JS
8542static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8543{
8544 if (old->acquired_refs != cur->acquired_refs)
8545 return false;
8546 return !memcmp(old->refs, cur->refs,
8547 sizeof(*old->refs) * old->acquired_refs);
8548}
8549
f1bca824
AS
8550/* compare two verifier states
8551 *
8552 * all states stored in state_list are known to be valid, since
8553 * verifier reached 'bpf_exit' instruction through them
8554 *
8555 * this function is called when verifier exploring different branches of
8556 * execution popped from the state stack. If it sees an old state that has
8557 * more strict register state and more strict stack state then this execution
8558 * branch doesn't need to be explored further, since verifier already
8559 * concluded that more strict state leads to valid finish.
8560 *
8561 * Therefore two states are equivalent if register state is more conservative
8562 * and explored stack state is more conservative than the current one.
8563 * Example:
8564 * explored current
8565 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8566 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8567 *
8568 * In other words if current stack state (one being explored) has more
8569 * valid slots than old one that already passed validation, it means
8570 * the verifier can stop exploring and conclude that current state is valid too
8571 *
8572 * Similarly with registers. If explored state has register type as invalid
8573 * whereas register type in current state is meaningful, it means that
8574 * the current state will reach 'bpf_exit' instruction safely
8575 */
f4d7e40a
AS
8576static bool func_states_equal(struct bpf_func_state *old,
8577 struct bpf_func_state *cur)
f1bca824 8578{
f1174f77
EC
8579 struct idpair *idmap;
8580 bool ret = false;
f1bca824
AS
8581 int i;
8582
f1174f77
EC
8583 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8584 /* If we failed to allocate the idmap, just say it's not safe */
8585 if (!idmap)
1a0dc1ac 8586 return false;
f1174f77
EC
8587
8588 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 8589 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 8590 goto out_free;
f1bca824
AS
8591 }
8592
638f5b90
AS
8593 if (!stacksafe(old, cur, idmap))
8594 goto out_free;
fd978bf7
JS
8595
8596 if (!refsafe(old, cur))
8597 goto out_free;
f1174f77
EC
8598 ret = true;
8599out_free:
8600 kfree(idmap);
8601 return ret;
f1bca824
AS
8602}
8603
f4d7e40a
AS
8604static bool states_equal(struct bpf_verifier_env *env,
8605 struct bpf_verifier_state *old,
8606 struct bpf_verifier_state *cur)
8607{
8608 int i;
8609
8610 if (old->curframe != cur->curframe)
8611 return false;
8612
979d63d5
DB
8613 /* Verification state from speculative execution simulation
8614 * must never prune a non-speculative execution one.
8615 */
8616 if (old->speculative && !cur->speculative)
8617 return false;
8618
d83525ca
AS
8619 if (old->active_spin_lock != cur->active_spin_lock)
8620 return false;
8621
f4d7e40a
AS
8622 /* for states to be equal callsites have to be the same
8623 * and all frame states need to be equivalent
8624 */
8625 for (i = 0; i <= old->curframe; i++) {
8626 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8627 return false;
8628 if (!func_states_equal(old->frame[i], cur->frame[i]))
8629 return false;
8630 }
8631 return true;
8632}
8633
5327ed3d
JW
8634/* Return 0 if no propagation happened. Return negative error code if error
8635 * happened. Otherwise, return the propagated bit.
8636 */
55e7f3b5
JW
8637static int propagate_liveness_reg(struct bpf_verifier_env *env,
8638 struct bpf_reg_state *reg,
8639 struct bpf_reg_state *parent_reg)
8640{
5327ed3d
JW
8641 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8642 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
8643 int err;
8644
5327ed3d
JW
8645 /* When comes here, read flags of PARENT_REG or REG could be any of
8646 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8647 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8648 */
8649 if (parent_flag == REG_LIVE_READ64 ||
8650 /* Or if there is no read flag from REG. */
8651 !flag ||
8652 /* Or if the read flag from REG is the same as PARENT_REG. */
8653 parent_flag == flag)
55e7f3b5
JW
8654 return 0;
8655
5327ed3d 8656 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
8657 if (err)
8658 return err;
8659
5327ed3d 8660 return flag;
55e7f3b5
JW
8661}
8662
8e9cd9ce 8663/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
8664 * straight-line code between a state and its parent. When we arrive at an
8665 * equivalent state (jump target or such) we didn't arrive by the straight-line
8666 * code, so read marks in the state must propagate to the parent regardless
8667 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 8668 * in mark_reg_read() is for.
8e9cd9ce 8669 */
f4d7e40a
AS
8670static int propagate_liveness(struct bpf_verifier_env *env,
8671 const struct bpf_verifier_state *vstate,
8672 struct bpf_verifier_state *vparent)
dc503a8a 8673{
3f8cafa4 8674 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 8675 struct bpf_func_state *state, *parent;
3f8cafa4 8676 int i, frame, err = 0;
dc503a8a 8677
f4d7e40a
AS
8678 if (vparent->curframe != vstate->curframe) {
8679 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8680 vparent->curframe, vstate->curframe);
8681 return -EFAULT;
8682 }
dc503a8a
EC
8683 /* Propagate read liveness of registers... */
8684 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 8685 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
8686 parent = vparent->frame[frame];
8687 state = vstate->frame[frame];
8688 parent_reg = parent->regs;
8689 state_reg = state->regs;
83d16312
JK
8690 /* We don't need to worry about FP liveness, it's read-only */
8691 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
8692 err = propagate_liveness_reg(env, &state_reg[i],
8693 &parent_reg[i]);
5327ed3d 8694 if (err < 0)
3f8cafa4 8695 return err;
5327ed3d
JW
8696 if (err == REG_LIVE_READ64)
8697 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 8698 }
f4d7e40a 8699
1b04aee7 8700 /* Propagate stack slots. */
f4d7e40a
AS
8701 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8702 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
8703 parent_reg = &parent->stack[i].spilled_ptr;
8704 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
8705 err = propagate_liveness_reg(env, state_reg,
8706 parent_reg);
5327ed3d 8707 if (err < 0)
3f8cafa4 8708 return err;
dc503a8a
EC
8709 }
8710 }
5327ed3d 8711 return 0;
dc503a8a
EC
8712}
8713
a3ce685d
AS
8714/* find precise scalars in the previous equivalent state and
8715 * propagate them into the current state
8716 */
8717static int propagate_precision(struct bpf_verifier_env *env,
8718 const struct bpf_verifier_state *old)
8719{
8720 struct bpf_reg_state *state_reg;
8721 struct bpf_func_state *state;
8722 int i, err = 0;
8723
8724 state = old->frame[old->curframe];
8725 state_reg = state->regs;
8726 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8727 if (state_reg->type != SCALAR_VALUE ||
8728 !state_reg->precise)
8729 continue;
8730 if (env->log.level & BPF_LOG_LEVEL2)
8731 verbose(env, "propagating r%d\n", i);
8732 err = mark_chain_precision(env, i);
8733 if (err < 0)
8734 return err;
8735 }
8736
8737 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8738 if (state->stack[i].slot_type[0] != STACK_SPILL)
8739 continue;
8740 state_reg = &state->stack[i].spilled_ptr;
8741 if (state_reg->type != SCALAR_VALUE ||
8742 !state_reg->precise)
8743 continue;
8744 if (env->log.level & BPF_LOG_LEVEL2)
8745 verbose(env, "propagating fp%d\n",
8746 (-i - 1) * BPF_REG_SIZE);
8747 err = mark_chain_precision_stack(env, i);
8748 if (err < 0)
8749 return err;
8750 }
8751 return 0;
8752}
8753
2589726d
AS
8754static bool states_maybe_looping(struct bpf_verifier_state *old,
8755 struct bpf_verifier_state *cur)
8756{
8757 struct bpf_func_state *fold, *fcur;
8758 int i, fr = cur->curframe;
8759
8760 if (old->curframe != fr)
8761 return false;
8762
8763 fold = old->frame[fr];
8764 fcur = cur->frame[fr];
8765 for (i = 0; i < MAX_BPF_REG; i++)
8766 if (memcmp(&fold->regs[i], &fcur->regs[i],
8767 offsetof(struct bpf_reg_state, parent)))
8768 return false;
8769 return true;
8770}
8771
8772
58e2af8b 8773static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 8774{
58e2af8b 8775 struct bpf_verifier_state_list *new_sl;
9f4686c4 8776 struct bpf_verifier_state_list *sl, **pprev;
679c782d 8777 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 8778 int i, j, err, states_cnt = 0;
10d274e8 8779 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 8780
b5dc0163 8781 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 8782 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
8783 /* this 'insn_idx' instruction wasn't marked, so we will not
8784 * be doing state search here
8785 */
8786 return 0;
8787
2589726d
AS
8788 /* bpf progs typically have pruning point every 4 instructions
8789 * http://vger.kernel.org/bpfconf2019.html#session-1
8790 * Do not add new state for future pruning if the verifier hasn't seen
8791 * at least 2 jumps and at least 8 instructions.
8792 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8793 * In tests that amounts to up to 50% reduction into total verifier
8794 * memory consumption and 20% verifier time speedup.
8795 */
8796 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8797 env->insn_processed - env->prev_insn_processed >= 8)
8798 add_new_state = true;
8799
a8f500af
AS
8800 pprev = explored_state(env, insn_idx);
8801 sl = *pprev;
8802
9242b5f5
AS
8803 clean_live_states(env, insn_idx, cur);
8804
a8f500af 8805 while (sl) {
dc2a4ebc
AS
8806 states_cnt++;
8807 if (sl->state.insn_idx != insn_idx)
8808 goto next;
2589726d
AS
8809 if (sl->state.branches) {
8810 if (states_maybe_looping(&sl->state, cur) &&
8811 states_equal(env, &sl->state, cur)) {
8812 verbose_linfo(env, insn_idx, "; ");
8813 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8814 return -EINVAL;
8815 }
8816 /* if the verifier is processing a loop, avoid adding new state
8817 * too often, since different loop iterations have distinct
8818 * states and may not help future pruning.
8819 * This threshold shouldn't be too low to make sure that
8820 * a loop with large bound will be rejected quickly.
8821 * The most abusive loop will be:
8822 * r1 += 1
8823 * if r1 < 1000000 goto pc-2
8824 * 1M insn_procssed limit / 100 == 10k peak states.
8825 * This threshold shouldn't be too high either, since states
8826 * at the end of the loop are likely to be useful in pruning.
8827 */
8828 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8829 env->insn_processed - env->prev_insn_processed < 100)
8830 add_new_state = false;
8831 goto miss;
8832 }
638f5b90 8833 if (states_equal(env, &sl->state, cur)) {
9f4686c4 8834 sl->hit_cnt++;
f1bca824 8835 /* reached equivalent register/stack state,
dc503a8a
EC
8836 * prune the search.
8837 * Registers read by the continuation are read by us.
8e9cd9ce
EC
8838 * If we have any write marks in env->cur_state, they
8839 * will prevent corresponding reads in the continuation
8840 * from reaching our parent (an explored_state). Our
8841 * own state will get the read marks recorded, but
8842 * they'll be immediately forgotten as we're pruning
8843 * this state and will pop a new one.
f1bca824 8844 */
f4d7e40a 8845 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
8846
8847 /* if previous state reached the exit with precision and
8848 * current state is equivalent to it (except precsion marks)
8849 * the precision needs to be propagated back in
8850 * the current state.
8851 */
8852 err = err ? : push_jmp_history(env, cur);
8853 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
8854 if (err)
8855 return err;
f1bca824 8856 return 1;
dc503a8a 8857 }
2589726d
AS
8858miss:
8859 /* when new state is not going to be added do not increase miss count.
8860 * Otherwise several loop iterations will remove the state
8861 * recorded earlier. The goal of these heuristics is to have
8862 * states from some iterations of the loop (some in the beginning
8863 * and some at the end) to help pruning.
8864 */
8865 if (add_new_state)
8866 sl->miss_cnt++;
9f4686c4
AS
8867 /* heuristic to determine whether this state is beneficial
8868 * to keep checking from state equivalence point of view.
8869 * Higher numbers increase max_states_per_insn and verification time,
8870 * but do not meaningfully decrease insn_processed.
8871 */
8872 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8873 /* the state is unlikely to be useful. Remove it to
8874 * speed up verification
8875 */
8876 *pprev = sl->next;
8877 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
8878 u32 br = sl->state.branches;
8879
8880 WARN_ONCE(br,
8881 "BUG live_done but branches_to_explore %d\n",
8882 br);
9f4686c4
AS
8883 free_verifier_state(&sl->state, false);
8884 kfree(sl);
8885 env->peak_states--;
8886 } else {
8887 /* cannot free this state, since parentage chain may
8888 * walk it later. Add it for free_list instead to
8889 * be freed at the end of verification
8890 */
8891 sl->next = env->free_list;
8892 env->free_list = sl;
8893 }
8894 sl = *pprev;
8895 continue;
8896 }
dc2a4ebc 8897next:
9f4686c4
AS
8898 pprev = &sl->next;
8899 sl = *pprev;
f1bca824
AS
8900 }
8901
06ee7115
AS
8902 if (env->max_states_per_insn < states_cnt)
8903 env->max_states_per_insn = states_cnt;
8904
2c78ee89 8905 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 8906 return push_jmp_history(env, cur);
ceefbc96 8907
2589726d 8908 if (!add_new_state)
b5dc0163 8909 return push_jmp_history(env, cur);
ceefbc96 8910
2589726d
AS
8911 /* There were no equivalent states, remember the current one.
8912 * Technically the current state is not proven to be safe yet,
f4d7e40a 8913 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 8914 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 8915 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
8916 * again on the way to bpf_exit.
8917 * When looping the sl->state.branches will be > 0 and this state
8918 * will not be considered for equivalence until branches == 0.
f1bca824 8919 */
638f5b90 8920 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
8921 if (!new_sl)
8922 return -ENOMEM;
06ee7115
AS
8923 env->total_states++;
8924 env->peak_states++;
2589726d
AS
8925 env->prev_jmps_processed = env->jmps_processed;
8926 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
8927
8928 /* add new state to the head of linked list */
679c782d
EC
8929 new = &new_sl->state;
8930 err = copy_verifier_state(new, cur);
1969db47 8931 if (err) {
679c782d 8932 free_verifier_state(new, false);
1969db47
AS
8933 kfree(new_sl);
8934 return err;
8935 }
dc2a4ebc 8936 new->insn_idx = insn_idx;
2589726d
AS
8937 WARN_ONCE(new->branches != 1,
8938 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 8939
2589726d 8940 cur->parent = new;
b5dc0163
AS
8941 cur->first_insn_idx = insn_idx;
8942 clear_jmp_history(cur);
5d839021
AS
8943 new_sl->next = *explored_state(env, insn_idx);
8944 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
8945 /* connect new state to parentage chain. Current frame needs all
8946 * registers connected. Only r6 - r9 of the callers are alive (pushed
8947 * to the stack implicitly by JITs) so in callers' frames connect just
8948 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8949 * the state of the call instruction (with WRITTEN set), and r0 comes
8950 * from callee with its full parentage chain, anyway.
8951 */
8e9cd9ce
EC
8952 /* clear write marks in current state: the writes we did are not writes
8953 * our child did, so they don't screen off its reads from us.
8954 * (There are no read marks in current state, because reads always mark
8955 * their parent and current state never has children yet. Only
8956 * explored_states can get read marks.)
8957 */
eea1c227
AS
8958 for (j = 0; j <= cur->curframe; j++) {
8959 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
8960 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8961 for (i = 0; i < BPF_REG_FP; i++)
8962 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
8963 }
f4d7e40a
AS
8964
8965 /* all stack frames are accessible from callee, clear them all */
8966 for (j = 0; j <= cur->curframe; j++) {
8967 struct bpf_func_state *frame = cur->frame[j];
679c782d 8968 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 8969
679c782d 8970 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 8971 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
8972 frame->stack[i].spilled_ptr.parent =
8973 &newframe->stack[i].spilled_ptr;
8974 }
f4d7e40a 8975 }
f1bca824
AS
8976 return 0;
8977}
8978
c64b7983
JS
8979/* Return true if it's OK to have the same insn return a different type. */
8980static bool reg_type_mismatch_ok(enum bpf_reg_type type)
8981{
8982 switch (type) {
8983 case PTR_TO_CTX:
8984 case PTR_TO_SOCKET:
8985 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
8986 case PTR_TO_SOCK_COMMON:
8987 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
8988 case PTR_TO_TCP_SOCK:
8989 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 8990 case PTR_TO_XDP_SOCK:
2a02759e 8991 case PTR_TO_BTF_ID:
b121b341 8992 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
8993 return false;
8994 default:
8995 return true;
8996 }
8997}
8998
8999/* If an instruction was previously used with particular pointer types, then we
9000 * need to be careful to avoid cases such as the below, where it may be ok
9001 * for one branch accessing the pointer, but not ok for the other branch:
9002 *
9003 * R1 = sock_ptr
9004 * goto X;
9005 * ...
9006 * R1 = some_other_valid_ptr;
9007 * goto X;
9008 * ...
9009 * R2 = *(u32 *)(R1 + 0);
9010 */
9011static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9012{
9013 return src != prev && (!reg_type_mismatch_ok(src) ||
9014 !reg_type_mismatch_ok(prev));
9015}
9016
58e2af8b 9017static int do_check(struct bpf_verifier_env *env)
17a52670 9018{
6f8a57cc 9019 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 9020 struct bpf_verifier_state *state = env->cur_state;
17a52670 9021 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 9022 struct bpf_reg_state *regs;
06ee7115 9023 int insn_cnt = env->prog->len;
17a52670 9024 bool do_print_state = false;
b5dc0163 9025 int prev_insn_idx = -1;
17a52670 9026
17a52670
AS
9027 for (;;) {
9028 struct bpf_insn *insn;
9029 u8 class;
9030 int err;
9031
b5dc0163 9032 env->prev_insn_idx = prev_insn_idx;
c08435ec 9033 if (env->insn_idx >= insn_cnt) {
61bd5218 9034 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 9035 env->insn_idx, insn_cnt);
17a52670
AS
9036 return -EFAULT;
9037 }
9038
c08435ec 9039 insn = &insns[env->insn_idx];
17a52670
AS
9040 class = BPF_CLASS(insn->code);
9041
06ee7115 9042 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
9043 verbose(env,
9044 "BPF program is too large. Processed %d insn\n",
06ee7115 9045 env->insn_processed);
17a52670
AS
9046 return -E2BIG;
9047 }
9048
c08435ec 9049 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
9050 if (err < 0)
9051 return err;
9052 if (err == 1) {
9053 /* found equivalent state, can prune the search */
06ee7115 9054 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 9055 if (do_print_state)
979d63d5
DB
9056 verbose(env, "\nfrom %d to %d%s: safe\n",
9057 env->prev_insn_idx, env->insn_idx,
9058 env->cur_state->speculative ?
9059 " (speculative execution)" : "");
f1bca824 9060 else
c08435ec 9061 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
9062 }
9063 goto process_bpf_exit;
9064 }
9065
c3494801
AS
9066 if (signal_pending(current))
9067 return -EAGAIN;
9068
3c2ce60b
DB
9069 if (need_resched())
9070 cond_resched();
9071
06ee7115
AS
9072 if (env->log.level & BPF_LOG_LEVEL2 ||
9073 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9074 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 9075 verbose(env, "%d:", env->insn_idx);
c5fc9692 9076 else
979d63d5
DB
9077 verbose(env, "\nfrom %d to %d%s:",
9078 env->prev_insn_idx, env->insn_idx,
9079 env->cur_state->speculative ?
9080 " (speculative execution)" : "");
f4d7e40a 9081 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
9082 do_print_state = false;
9083 }
9084
06ee7115 9085 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
9086 const struct bpf_insn_cbs cbs = {
9087 .cb_print = verbose,
abe08840 9088 .private_data = env,
7105e828
DB
9089 };
9090
c08435ec
DB
9091 verbose_linfo(env, env->insn_idx, "; ");
9092 verbose(env, "%d: ", env->insn_idx);
abe08840 9093 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
9094 }
9095
cae1927c 9096 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
9097 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9098 env->prev_insn_idx);
cae1927c
JK
9099 if (err)
9100 return err;
9101 }
13a27dfc 9102
638f5b90 9103 regs = cur_regs(env);
51c39bb1 9104 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
b5dc0163 9105 prev_insn_idx = env->insn_idx;
fd978bf7 9106
17a52670 9107 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 9108 err = check_alu_op(env, insn);
17a52670
AS
9109 if (err)
9110 return err;
9111
9112 } else if (class == BPF_LDX) {
3df126f3 9113 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
9114
9115 /* check for reserved fields is already done */
9116
17a52670 9117 /* check src operand */
dc503a8a 9118 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9119 if (err)
9120 return err;
9121
dc503a8a 9122 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
9123 if (err)
9124 return err;
9125
725f9dcd
AS
9126 src_reg_type = regs[insn->src_reg].type;
9127
17a52670
AS
9128 /* check that memory (src_reg + off) is readable,
9129 * the state of dst_reg will be updated by this func
9130 */
c08435ec
DB
9131 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9132 insn->off, BPF_SIZE(insn->code),
9133 BPF_READ, insn->dst_reg, false);
17a52670
AS
9134 if (err)
9135 return err;
9136
c08435ec 9137 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9138
9139 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
9140 /* saw a valid insn
9141 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 9142 * save type to validate intersecting paths
9bac3d6d 9143 */
3df126f3 9144 *prev_src_type = src_reg_type;
9bac3d6d 9145
c64b7983 9146 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
9147 /* ABuser program is trying to use the same insn
9148 * dst_reg = *(u32*) (src_reg + off)
9149 * with different pointer types:
9150 * src_reg == ctx in one branch and
9151 * src_reg == stack|map in some other branch.
9152 * Reject it.
9153 */
61bd5218 9154 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
9155 return -EINVAL;
9156 }
9157
17a52670 9158 } else if (class == BPF_STX) {
3df126f3 9159 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 9160
17a52670 9161 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 9162 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
9163 if (err)
9164 return err;
c08435ec 9165 env->insn_idx++;
17a52670
AS
9166 continue;
9167 }
9168
17a52670 9169 /* check src1 operand */
dc503a8a 9170 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
9171 if (err)
9172 return err;
9173 /* check src2 operand */
dc503a8a 9174 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9175 if (err)
9176 return err;
9177
d691f9e8
AS
9178 dst_reg_type = regs[insn->dst_reg].type;
9179
17a52670 9180 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9181 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9182 insn->off, BPF_SIZE(insn->code),
9183 BPF_WRITE, insn->src_reg, false);
17a52670
AS
9184 if (err)
9185 return err;
9186
c08435ec 9187 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
9188
9189 if (*prev_dst_type == NOT_INIT) {
9190 *prev_dst_type = dst_reg_type;
c64b7983 9191 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 9192 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
9193 return -EINVAL;
9194 }
9195
17a52670
AS
9196 } else if (class == BPF_ST) {
9197 if (BPF_MODE(insn->code) != BPF_MEM ||
9198 insn->src_reg != BPF_REG_0) {
61bd5218 9199 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
9200 return -EINVAL;
9201 }
9202 /* check src operand */
dc503a8a 9203 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
9204 if (err)
9205 return err;
9206
f37a8cb8 9207 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 9208 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
9209 insn->dst_reg,
9210 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
9211 return -EACCES;
9212 }
9213
17a52670 9214 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
9215 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9216 insn->off, BPF_SIZE(insn->code),
9217 BPF_WRITE, -1, false);
17a52670
AS
9218 if (err)
9219 return err;
9220
092ed096 9221 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
9222 u8 opcode = BPF_OP(insn->code);
9223
2589726d 9224 env->jmps_processed++;
17a52670
AS
9225 if (opcode == BPF_CALL) {
9226 if (BPF_SRC(insn->code) != BPF_K ||
9227 insn->off != 0 ||
f4d7e40a
AS
9228 (insn->src_reg != BPF_REG_0 &&
9229 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
9230 insn->dst_reg != BPF_REG_0 ||
9231 class == BPF_JMP32) {
61bd5218 9232 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
9233 return -EINVAL;
9234 }
9235
d83525ca
AS
9236 if (env->cur_state->active_spin_lock &&
9237 (insn->src_reg == BPF_PSEUDO_CALL ||
9238 insn->imm != BPF_FUNC_spin_unlock)) {
9239 verbose(env, "function calls are not allowed while holding a lock\n");
9240 return -EINVAL;
9241 }
f4d7e40a 9242 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 9243 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 9244 else
c08435ec 9245 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
9246 if (err)
9247 return err;
9248
9249 } else if (opcode == BPF_JA) {
9250 if (BPF_SRC(insn->code) != BPF_K ||
9251 insn->imm != 0 ||
9252 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9253 insn->dst_reg != BPF_REG_0 ||
9254 class == BPF_JMP32) {
61bd5218 9255 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
9256 return -EINVAL;
9257 }
9258
c08435ec 9259 env->insn_idx += insn->off + 1;
17a52670
AS
9260 continue;
9261
9262 } else if (opcode == BPF_EXIT) {
9263 if (BPF_SRC(insn->code) != BPF_K ||
9264 insn->imm != 0 ||
9265 insn->src_reg != BPF_REG_0 ||
092ed096
JW
9266 insn->dst_reg != BPF_REG_0 ||
9267 class == BPF_JMP32) {
61bd5218 9268 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
9269 return -EINVAL;
9270 }
9271
d83525ca
AS
9272 if (env->cur_state->active_spin_lock) {
9273 verbose(env, "bpf_spin_unlock is missing\n");
9274 return -EINVAL;
9275 }
9276
f4d7e40a
AS
9277 if (state->curframe) {
9278 /* exit from nested function */
c08435ec 9279 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
9280 if (err)
9281 return err;
9282 do_print_state = true;
9283 continue;
9284 }
9285
fd978bf7
JS
9286 err = check_reference_leak(env);
9287 if (err)
9288 return err;
9289
390ee7e2
AS
9290 err = check_return_code(env);
9291 if (err)
9292 return err;
f1bca824 9293process_bpf_exit:
2589726d 9294 update_branch_counts(env, env->cur_state);
b5dc0163 9295 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 9296 &env->insn_idx, pop_log);
638f5b90
AS
9297 if (err < 0) {
9298 if (err != -ENOENT)
9299 return err;
17a52670
AS
9300 break;
9301 } else {
9302 do_print_state = true;
9303 continue;
9304 }
9305 } else {
c08435ec 9306 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
9307 if (err)
9308 return err;
9309 }
9310 } else if (class == BPF_LD) {
9311 u8 mode = BPF_MODE(insn->code);
9312
9313 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
9314 err = check_ld_abs(env, insn);
9315 if (err)
9316 return err;
9317
17a52670
AS
9318 } else if (mode == BPF_IMM) {
9319 err = check_ld_imm(env, insn);
9320 if (err)
9321 return err;
9322
c08435ec 9323 env->insn_idx++;
51c39bb1 9324 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
17a52670 9325 } else {
61bd5218 9326 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
9327 return -EINVAL;
9328 }
9329 } else {
61bd5218 9330 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
9331 return -EINVAL;
9332 }
9333
c08435ec 9334 env->insn_idx++;
17a52670
AS
9335 }
9336
9337 return 0;
9338}
9339
56f668df
MKL
9340static int check_map_prealloc(struct bpf_map *map)
9341{
9342 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
9343 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9344 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
9345 !(map->map_flags & BPF_F_NO_PREALLOC);
9346}
9347
d83525ca
AS
9348static bool is_tracing_prog_type(enum bpf_prog_type type)
9349{
9350 switch (type) {
9351 case BPF_PROG_TYPE_KPROBE:
9352 case BPF_PROG_TYPE_TRACEPOINT:
9353 case BPF_PROG_TYPE_PERF_EVENT:
9354 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9355 return true;
9356 default:
9357 return false;
9358 }
9359}
9360
94dacdbd
TG
9361static bool is_preallocated_map(struct bpf_map *map)
9362{
9363 if (!check_map_prealloc(map))
9364 return false;
9365 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
9366 return false;
9367 return true;
9368}
9369
61bd5218
JK
9370static int check_map_prog_compatibility(struct bpf_verifier_env *env,
9371 struct bpf_map *map,
fdc15d38
AS
9372 struct bpf_prog *prog)
9373
9374{
7e40781c 9375 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
9376 /*
9377 * Validate that trace type programs use preallocated hash maps.
9378 *
9379 * For programs attached to PERF events this is mandatory as the
9380 * perf NMI can hit any arbitrary code sequence.
9381 *
9382 * All other trace types using preallocated hash maps are unsafe as
9383 * well because tracepoint or kprobes can be inside locked regions
9384 * of the memory allocator or at a place where a recursion into the
9385 * memory allocator would see inconsistent state.
9386 *
2ed905c5
TG
9387 * On RT enabled kernels run-time allocation of all trace type
9388 * programs is strictly prohibited due to lock type constraints. On
9389 * !RT kernels it is allowed for backwards compatibility reasons for
9390 * now, but warnings are emitted so developers are made aware of
9391 * the unsafety and can fix their programs before this is enforced.
56f668df 9392 */
7e40781c
UP
9393 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
9394 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 9395 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
9396 return -EINVAL;
9397 }
2ed905c5
TG
9398 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
9399 verbose(env, "trace type programs can only use preallocated hash map\n");
9400 return -EINVAL;
9401 }
94dacdbd
TG
9402 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9403 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 9404 }
a3884572 9405
7e40781c
UP
9406 if ((is_tracing_prog_type(prog_type) ||
9407 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
d83525ca
AS
9408 map_value_has_spin_lock(map)) {
9409 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9410 return -EINVAL;
9411 }
9412
a3884572 9413 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 9414 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
9415 verbose(env, "offload device mismatch between prog and map\n");
9416 return -EINVAL;
9417 }
9418
85d33df3
MKL
9419 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9420 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9421 return -EINVAL;
9422 }
9423
1e6c62a8
AS
9424 if (prog->aux->sleepable)
9425 switch (map->map_type) {
9426 case BPF_MAP_TYPE_HASH:
9427 case BPF_MAP_TYPE_LRU_HASH:
9428 case BPF_MAP_TYPE_ARRAY:
9429 if (!is_preallocated_map(map)) {
9430 verbose(env,
9431 "Sleepable programs can only use preallocated hash maps\n");
9432 return -EINVAL;
9433 }
9434 break;
9435 default:
9436 verbose(env,
9437 "Sleepable programs can only use array and hash maps\n");
9438 return -EINVAL;
9439 }
9440
fdc15d38
AS
9441 return 0;
9442}
9443
b741f163
RG
9444static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9445{
9446 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9447 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9448}
9449
0246e64d
AS
9450/* look for pseudo eBPF instructions that access map FDs and
9451 * replace them with actual map pointers
9452 */
58e2af8b 9453static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
9454{
9455 struct bpf_insn *insn = env->prog->insnsi;
9456 int insn_cnt = env->prog->len;
fdc15d38 9457 int i, j, err;
0246e64d 9458
f1f7714e 9459 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
9460 if (err)
9461 return err;
9462
0246e64d 9463 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 9464 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 9465 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 9466 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
9467 return -EINVAL;
9468 }
9469
d691f9e8
AS
9470 if (BPF_CLASS(insn->code) == BPF_STX &&
9471 ((BPF_MODE(insn->code) != BPF_MEM &&
9472 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 9473 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
9474 return -EINVAL;
9475 }
9476
0246e64d 9477 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 9478 struct bpf_insn_aux_data *aux;
0246e64d
AS
9479 struct bpf_map *map;
9480 struct fd f;
d8eca5bb 9481 u64 addr;
0246e64d
AS
9482
9483 if (i == insn_cnt - 1 || insn[1].code != 0 ||
9484 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9485 insn[1].off != 0) {
61bd5218 9486 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
9487 return -EINVAL;
9488 }
9489
d8eca5bb 9490 if (insn[0].src_reg == 0)
0246e64d
AS
9491 /* valid generic load 64-bit imm */
9492 goto next_insn;
9493
d8eca5bb
DB
9494 /* In final convert_pseudo_ld_imm64() step, this is
9495 * converted into regular 64-bit imm load insn.
9496 */
9497 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9498 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9499 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9500 insn[1].imm != 0)) {
9501 verbose(env,
9502 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
9503 return -EINVAL;
9504 }
9505
20182390 9506 f = fdget(insn[0].imm);
c2101297 9507 map = __bpf_map_get(f);
0246e64d 9508 if (IS_ERR(map)) {
61bd5218 9509 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 9510 insn[0].imm);
0246e64d
AS
9511 return PTR_ERR(map);
9512 }
9513
61bd5218 9514 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
9515 if (err) {
9516 fdput(f);
9517 return err;
9518 }
9519
d8eca5bb
DB
9520 aux = &env->insn_aux_data[i];
9521 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9522 addr = (unsigned long)map;
9523 } else {
9524 u32 off = insn[1].imm;
9525
9526 if (off >= BPF_MAX_VAR_OFF) {
9527 verbose(env, "direct value offset of %u is not allowed\n", off);
9528 fdput(f);
9529 return -EINVAL;
9530 }
9531
9532 if (!map->ops->map_direct_value_addr) {
9533 verbose(env, "no direct value access support for this map type\n");
9534 fdput(f);
9535 return -EINVAL;
9536 }
9537
9538 err = map->ops->map_direct_value_addr(map, &addr, off);
9539 if (err) {
9540 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9541 map->value_size, off);
9542 fdput(f);
9543 return err;
9544 }
9545
9546 aux->map_off = off;
9547 addr += off;
9548 }
9549
9550 insn[0].imm = (u32)addr;
9551 insn[1].imm = addr >> 32;
0246e64d
AS
9552
9553 /* check whether we recorded this map already */
d8eca5bb 9554 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 9555 if (env->used_maps[j] == map) {
d8eca5bb 9556 aux->map_index = j;
0246e64d
AS
9557 fdput(f);
9558 goto next_insn;
9559 }
d8eca5bb 9560 }
0246e64d
AS
9561
9562 if (env->used_map_cnt >= MAX_USED_MAPS) {
9563 fdput(f);
9564 return -E2BIG;
9565 }
9566
0246e64d
AS
9567 /* hold the map. If the program is rejected by verifier,
9568 * the map will be released by release_maps() or it
9569 * will be used by the valid program until it's unloaded
ab7f5bf0 9570 * and all maps are released in free_used_maps()
0246e64d 9571 */
1e0bd5a0 9572 bpf_map_inc(map);
d8eca5bb
DB
9573
9574 aux->map_index = env->used_map_cnt;
92117d84
AS
9575 env->used_maps[env->used_map_cnt++] = map;
9576
b741f163 9577 if (bpf_map_is_cgroup_storage(map) &&
e4730423 9578 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 9579 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
9580 fdput(f);
9581 return -EBUSY;
9582 }
9583
0246e64d
AS
9584 fdput(f);
9585next_insn:
9586 insn++;
9587 i++;
5e581dad
DB
9588 continue;
9589 }
9590
9591 /* Basic sanity check before we invest more work here. */
9592 if (!bpf_opcode_in_insntable(insn->code)) {
9593 verbose(env, "unknown opcode %02x\n", insn->code);
9594 return -EINVAL;
0246e64d
AS
9595 }
9596 }
9597
9598 /* now all pseudo BPF_LD_IMM64 instructions load valid
9599 * 'struct bpf_map *' into a register instead of user map_fd.
9600 * These pointers will be used later by verifier to validate map access.
9601 */
9602 return 0;
9603}
9604
9605/* drop refcnt of maps used by the rejected program */
58e2af8b 9606static void release_maps(struct bpf_verifier_env *env)
0246e64d 9607{
a2ea0746
DB
9608 __bpf_free_used_maps(env->prog->aux, env->used_maps,
9609 env->used_map_cnt);
0246e64d
AS
9610}
9611
9612/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 9613static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
9614{
9615 struct bpf_insn *insn = env->prog->insnsi;
9616 int insn_cnt = env->prog->len;
9617 int i;
9618
9619 for (i = 0; i < insn_cnt; i++, insn++)
9620 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9621 insn->src_reg = 0;
9622}
9623
8041902d
AS
9624/* single env->prog->insni[off] instruction was replaced with the range
9625 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
9626 * [0, off) and [off, end) to new locations, so the patched range stays zero
9627 */
b325fbca
JW
9628static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9629 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
9630{
9631 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
9632 struct bpf_insn *insn = new_prog->insnsi;
9633 u32 prog_len;
c131187d 9634 int i;
8041902d 9635
b325fbca
JW
9636 /* aux info at OFF always needs adjustment, no matter fast path
9637 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9638 * original insn at old prog.
9639 */
9640 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9641
8041902d
AS
9642 if (cnt == 1)
9643 return 0;
b325fbca 9644 prog_len = new_prog->len;
fad953ce
KC
9645 new_data = vzalloc(array_size(prog_len,
9646 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
9647 if (!new_data)
9648 return -ENOMEM;
9649 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9650 memcpy(new_data + off + cnt - 1, old_data + off,
9651 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 9652 for (i = off; i < off + cnt - 1; i++) {
51c39bb1 9653 new_data[i].seen = env->pass_cnt;
b325fbca
JW
9654 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9655 }
8041902d
AS
9656 env->insn_aux_data = new_data;
9657 vfree(old_data);
9658 return 0;
9659}
9660
cc8b0b92
AS
9661static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9662{
9663 int i;
9664
9665 if (len == 1)
9666 return;
4cb3d99c
JW
9667 /* NOTE: fake 'exit' subprog should be updated as well. */
9668 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 9669 if (env->subprog_info[i].start <= off)
cc8b0b92 9670 continue;
9c8105bd 9671 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
9672 }
9673}
9674
a748c697
MF
9675static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
9676{
9677 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
9678 int i, sz = prog->aux->size_poke_tab;
9679 struct bpf_jit_poke_descriptor *desc;
9680
9681 for (i = 0; i < sz; i++) {
9682 desc = &tab[i];
9683 desc->insn_idx += len - 1;
9684 }
9685}
9686
8041902d
AS
9687static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9688 const struct bpf_insn *patch, u32 len)
9689{
9690 struct bpf_prog *new_prog;
9691
9692 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
9693 if (IS_ERR(new_prog)) {
9694 if (PTR_ERR(new_prog) == -ERANGE)
9695 verbose(env,
9696 "insn %d cannot be patched due to 16-bit range\n",
9697 env->insn_aux_data[off].orig_idx);
8041902d 9698 return NULL;
4f73379e 9699 }
b325fbca 9700 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 9701 return NULL;
cc8b0b92 9702 adjust_subprog_starts(env, off, len);
a748c697 9703 adjust_poke_descs(new_prog, len);
8041902d
AS
9704 return new_prog;
9705}
9706
52875a04
JK
9707static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9708 u32 off, u32 cnt)
9709{
9710 int i, j;
9711
9712 /* find first prog starting at or after off (first to remove) */
9713 for (i = 0; i < env->subprog_cnt; i++)
9714 if (env->subprog_info[i].start >= off)
9715 break;
9716 /* find first prog starting at or after off + cnt (first to stay) */
9717 for (j = i; j < env->subprog_cnt; j++)
9718 if (env->subprog_info[j].start >= off + cnt)
9719 break;
9720 /* if j doesn't start exactly at off + cnt, we are just removing
9721 * the front of previous prog
9722 */
9723 if (env->subprog_info[j].start != off + cnt)
9724 j--;
9725
9726 if (j > i) {
9727 struct bpf_prog_aux *aux = env->prog->aux;
9728 int move;
9729
9730 /* move fake 'exit' subprog as well */
9731 move = env->subprog_cnt + 1 - j;
9732
9733 memmove(env->subprog_info + i,
9734 env->subprog_info + j,
9735 sizeof(*env->subprog_info) * move);
9736 env->subprog_cnt -= j - i;
9737
9738 /* remove func_info */
9739 if (aux->func_info) {
9740 move = aux->func_info_cnt - j;
9741
9742 memmove(aux->func_info + i,
9743 aux->func_info + j,
9744 sizeof(*aux->func_info) * move);
9745 aux->func_info_cnt -= j - i;
9746 /* func_info->insn_off is set after all code rewrites,
9747 * in adjust_btf_func() - no need to adjust
9748 */
9749 }
9750 } else {
9751 /* convert i from "first prog to remove" to "first to adjust" */
9752 if (env->subprog_info[i].start == off)
9753 i++;
9754 }
9755
9756 /* update fake 'exit' subprog as well */
9757 for (; i <= env->subprog_cnt; i++)
9758 env->subprog_info[i].start -= cnt;
9759
9760 return 0;
9761}
9762
9763static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9764 u32 cnt)
9765{
9766 struct bpf_prog *prog = env->prog;
9767 u32 i, l_off, l_cnt, nr_linfo;
9768 struct bpf_line_info *linfo;
9769
9770 nr_linfo = prog->aux->nr_linfo;
9771 if (!nr_linfo)
9772 return 0;
9773
9774 linfo = prog->aux->linfo;
9775
9776 /* find first line info to remove, count lines to be removed */
9777 for (i = 0; i < nr_linfo; i++)
9778 if (linfo[i].insn_off >= off)
9779 break;
9780
9781 l_off = i;
9782 l_cnt = 0;
9783 for (; i < nr_linfo; i++)
9784 if (linfo[i].insn_off < off + cnt)
9785 l_cnt++;
9786 else
9787 break;
9788
9789 /* First live insn doesn't match first live linfo, it needs to "inherit"
9790 * last removed linfo. prog is already modified, so prog->len == off
9791 * means no live instructions after (tail of the program was removed).
9792 */
9793 if (prog->len != off && l_cnt &&
9794 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9795 l_cnt--;
9796 linfo[--i].insn_off = off + cnt;
9797 }
9798
9799 /* remove the line info which refer to the removed instructions */
9800 if (l_cnt) {
9801 memmove(linfo + l_off, linfo + i,
9802 sizeof(*linfo) * (nr_linfo - i));
9803
9804 prog->aux->nr_linfo -= l_cnt;
9805 nr_linfo = prog->aux->nr_linfo;
9806 }
9807
9808 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9809 for (i = l_off; i < nr_linfo; i++)
9810 linfo[i].insn_off -= cnt;
9811
9812 /* fix up all subprogs (incl. 'exit') which start >= off */
9813 for (i = 0; i <= env->subprog_cnt; i++)
9814 if (env->subprog_info[i].linfo_idx > l_off) {
9815 /* program may have started in the removed region but
9816 * may not be fully removed
9817 */
9818 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9819 env->subprog_info[i].linfo_idx -= l_cnt;
9820 else
9821 env->subprog_info[i].linfo_idx = l_off;
9822 }
9823
9824 return 0;
9825}
9826
9827static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9828{
9829 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9830 unsigned int orig_prog_len = env->prog->len;
9831 int err;
9832
08ca90af
JK
9833 if (bpf_prog_is_dev_bound(env->prog->aux))
9834 bpf_prog_offload_remove_insns(env, off, cnt);
9835
52875a04
JK
9836 err = bpf_remove_insns(env->prog, off, cnt);
9837 if (err)
9838 return err;
9839
9840 err = adjust_subprog_starts_after_remove(env, off, cnt);
9841 if (err)
9842 return err;
9843
9844 err = bpf_adj_linfo_after_remove(env, off, cnt);
9845 if (err)
9846 return err;
9847
9848 memmove(aux_data + off, aux_data + off + cnt,
9849 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9850
9851 return 0;
9852}
9853
2a5418a1
DB
9854/* The verifier does more data flow analysis than llvm and will not
9855 * explore branches that are dead at run time. Malicious programs can
9856 * have dead code too. Therefore replace all dead at-run-time code
9857 * with 'ja -1'.
9858 *
9859 * Just nops are not optimal, e.g. if they would sit at the end of the
9860 * program and through another bug we would manage to jump there, then
9861 * we'd execute beyond program memory otherwise. Returning exception
9862 * code also wouldn't work since we can have subprogs where the dead
9863 * code could be located.
c131187d
AS
9864 */
9865static void sanitize_dead_code(struct bpf_verifier_env *env)
9866{
9867 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 9868 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
9869 struct bpf_insn *insn = env->prog->insnsi;
9870 const int insn_cnt = env->prog->len;
9871 int i;
9872
9873 for (i = 0; i < insn_cnt; i++) {
9874 if (aux_data[i].seen)
9875 continue;
2a5418a1 9876 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
9877 }
9878}
9879
e2ae4ca2
JK
9880static bool insn_is_cond_jump(u8 code)
9881{
9882 u8 op;
9883
092ed096
JW
9884 if (BPF_CLASS(code) == BPF_JMP32)
9885 return true;
9886
e2ae4ca2
JK
9887 if (BPF_CLASS(code) != BPF_JMP)
9888 return false;
9889
9890 op = BPF_OP(code);
9891 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9892}
9893
9894static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9895{
9896 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9897 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9898 struct bpf_insn *insn = env->prog->insnsi;
9899 const int insn_cnt = env->prog->len;
9900 int i;
9901
9902 for (i = 0; i < insn_cnt; i++, insn++) {
9903 if (!insn_is_cond_jump(insn->code))
9904 continue;
9905
9906 if (!aux_data[i + 1].seen)
9907 ja.off = insn->off;
9908 else if (!aux_data[i + 1 + insn->off].seen)
9909 ja.off = 0;
9910 else
9911 continue;
9912
08ca90af
JK
9913 if (bpf_prog_is_dev_bound(env->prog->aux))
9914 bpf_prog_offload_replace_insn(env, i, &ja);
9915
e2ae4ca2
JK
9916 memcpy(insn, &ja, sizeof(ja));
9917 }
9918}
9919
52875a04
JK
9920static int opt_remove_dead_code(struct bpf_verifier_env *env)
9921{
9922 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9923 int insn_cnt = env->prog->len;
9924 int i, err;
9925
9926 for (i = 0; i < insn_cnt; i++) {
9927 int j;
9928
9929 j = 0;
9930 while (i + j < insn_cnt && !aux_data[i + j].seen)
9931 j++;
9932 if (!j)
9933 continue;
9934
9935 err = verifier_remove_insns(env, i, j);
9936 if (err)
9937 return err;
9938 insn_cnt = env->prog->len;
9939 }
9940
9941 return 0;
9942}
9943
a1b14abc
JK
9944static int opt_remove_nops(struct bpf_verifier_env *env)
9945{
9946 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9947 struct bpf_insn *insn = env->prog->insnsi;
9948 int insn_cnt = env->prog->len;
9949 int i, err;
9950
9951 for (i = 0; i < insn_cnt; i++) {
9952 if (memcmp(&insn[i], &ja, sizeof(ja)))
9953 continue;
9954
9955 err = verifier_remove_insns(env, i, 1);
9956 if (err)
9957 return err;
9958 insn_cnt--;
9959 i--;
9960 }
9961
9962 return 0;
9963}
9964
d6c2308c
JW
9965static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
9966 const union bpf_attr *attr)
a4b1d3c1 9967{
d6c2308c 9968 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 9969 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 9970 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 9971 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 9972 struct bpf_prog *new_prog;
d6c2308c 9973 bool rnd_hi32;
a4b1d3c1 9974
d6c2308c 9975 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 9976 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
9977 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
9978 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
9979 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
9980 for (i = 0; i < len; i++) {
9981 int adj_idx = i + delta;
9982 struct bpf_insn insn;
9983
d6c2308c
JW
9984 insn = insns[adj_idx];
9985 if (!aux[adj_idx].zext_dst) {
9986 u8 code, class;
9987 u32 imm_rnd;
9988
9989 if (!rnd_hi32)
9990 continue;
9991
9992 code = insn.code;
9993 class = BPF_CLASS(code);
9994 if (insn_no_def(&insn))
9995 continue;
9996
9997 /* NOTE: arg "reg" (the fourth one) is only used for
9998 * BPF_STX which has been ruled out in above
9999 * check, it is safe to pass NULL here.
10000 */
10001 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10002 if (class == BPF_LD &&
10003 BPF_MODE(code) == BPF_IMM)
10004 i++;
10005 continue;
10006 }
10007
10008 /* ctx load could be transformed into wider load. */
10009 if (class == BPF_LDX &&
10010 aux[adj_idx].ptr_type == PTR_TO_CTX)
10011 continue;
10012
10013 imm_rnd = get_random_int();
10014 rnd_hi32_patch[0] = insn;
10015 rnd_hi32_patch[1].imm = imm_rnd;
10016 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10017 patch = rnd_hi32_patch;
10018 patch_len = 4;
10019 goto apply_patch_buffer;
10020 }
10021
10022 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
10023 continue;
10024
a4b1d3c1
JW
10025 zext_patch[0] = insn;
10026 zext_patch[1].dst_reg = insn.dst_reg;
10027 zext_patch[1].src_reg = insn.dst_reg;
d6c2308c
JW
10028 patch = zext_patch;
10029 patch_len = 2;
10030apply_patch_buffer:
10031 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
10032 if (!new_prog)
10033 return -ENOMEM;
10034 env->prog = new_prog;
10035 insns = new_prog->insnsi;
10036 aux = env->insn_aux_data;
d6c2308c 10037 delta += patch_len - 1;
a4b1d3c1
JW
10038 }
10039
10040 return 0;
10041}
10042
c64b7983
JS
10043/* convert load instructions that access fields of a context type into a
10044 * sequence of instructions that access fields of the underlying structure:
10045 * struct __sk_buff -> struct sk_buff
10046 * struct bpf_sock_ops -> struct sock
9bac3d6d 10047 */
58e2af8b 10048static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 10049{
00176a34 10050 const struct bpf_verifier_ops *ops = env->ops;
f96da094 10051 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 10052 const int insn_cnt = env->prog->len;
36bbef52 10053 struct bpf_insn insn_buf[16], *insn;
46f53a65 10054 u32 target_size, size_default, off;
9bac3d6d 10055 struct bpf_prog *new_prog;
d691f9e8 10056 enum bpf_access_type type;
f96da094 10057 bool is_narrower_load;
9bac3d6d 10058
b09928b9
DB
10059 if (ops->gen_prologue || env->seen_direct_write) {
10060 if (!ops->gen_prologue) {
10061 verbose(env, "bpf verifier is misconfigured\n");
10062 return -EINVAL;
10063 }
36bbef52
DB
10064 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10065 env->prog);
10066 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 10067 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
10068 return -EINVAL;
10069 } else if (cnt) {
8041902d 10070 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
10071 if (!new_prog)
10072 return -ENOMEM;
8041902d 10073
36bbef52 10074 env->prog = new_prog;
3df126f3 10075 delta += cnt - 1;
36bbef52
DB
10076 }
10077 }
10078
c64b7983 10079 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
10080 return 0;
10081
3df126f3 10082 insn = env->prog->insnsi + delta;
36bbef52 10083
9bac3d6d 10084 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
10085 bpf_convert_ctx_access_t convert_ctx_access;
10086
62c7989b
DB
10087 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
10088 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
10089 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 10090 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 10091 type = BPF_READ;
62c7989b
DB
10092 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
10093 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
10094 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 10095 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
10096 type = BPF_WRITE;
10097 else
9bac3d6d
AS
10098 continue;
10099
af86ca4e
AS
10100 if (type == BPF_WRITE &&
10101 env->insn_aux_data[i + delta].sanitize_stack_off) {
10102 struct bpf_insn patch[] = {
10103 /* Sanitize suspicious stack slot with zero.
10104 * There are no memory dependencies for this store,
10105 * since it's only using frame pointer and immediate
10106 * constant of zero
10107 */
10108 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
10109 env->insn_aux_data[i + delta].sanitize_stack_off,
10110 0),
10111 /* the original STX instruction will immediately
10112 * overwrite the same stack slot with appropriate value
10113 */
10114 *insn,
10115 };
10116
10117 cnt = ARRAY_SIZE(patch);
10118 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
10119 if (!new_prog)
10120 return -ENOMEM;
10121
10122 delta += cnt - 1;
10123 env->prog = new_prog;
10124 insn = new_prog->insnsi + i + delta;
10125 continue;
10126 }
10127
c64b7983
JS
10128 switch (env->insn_aux_data[i + delta].ptr_type) {
10129 case PTR_TO_CTX:
10130 if (!ops->convert_ctx_access)
10131 continue;
10132 convert_ctx_access = ops->convert_ctx_access;
10133 break;
10134 case PTR_TO_SOCKET:
46f8bc92 10135 case PTR_TO_SOCK_COMMON:
c64b7983
JS
10136 convert_ctx_access = bpf_sock_convert_ctx_access;
10137 break;
655a51e5
MKL
10138 case PTR_TO_TCP_SOCK:
10139 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
10140 break;
fada7fdc
JL
10141 case PTR_TO_XDP_SOCK:
10142 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
10143 break;
2a02759e 10144 case PTR_TO_BTF_ID:
27ae7997
MKL
10145 if (type == BPF_READ) {
10146 insn->code = BPF_LDX | BPF_PROBE_MEM |
10147 BPF_SIZE((insn)->code);
10148 env->prog->aux->num_exentries++;
7e40781c 10149 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
10150 verbose(env, "Writes through BTF pointers are not allowed\n");
10151 return -EINVAL;
10152 }
2a02759e 10153 continue;
c64b7983 10154 default:
9bac3d6d 10155 continue;
c64b7983 10156 }
9bac3d6d 10157
31fd8581 10158 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 10159 size = BPF_LDST_BYTES(insn);
31fd8581
YS
10160
10161 /* If the read access is a narrower load of the field,
10162 * convert to a 4/8-byte load, to minimum program type specific
10163 * convert_ctx_access changes. If conversion is successful,
10164 * we will apply proper mask to the result.
10165 */
f96da094 10166 is_narrower_load = size < ctx_field_size;
46f53a65
AI
10167 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
10168 off = insn->off;
31fd8581 10169 if (is_narrower_load) {
f96da094
DB
10170 u8 size_code;
10171
10172 if (type == BPF_WRITE) {
61bd5218 10173 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
10174 return -EINVAL;
10175 }
31fd8581 10176
f96da094 10177 size_code = BPF_H;
31fd8581
YS
10178 if (ctx_field_size == 4)
10179 size_code = BPF_W;
10180 else if (ctx_field_size == 8)
10181 size_code = BPF_DW;
f96da094 10182
bc23105c 10183 insn->off = off & ~(size_default - 1);
31fd8581
YS
10184 insn->code = BPF_LDX | BPF_MEM | size_code;
10185 }
f96da094
DB
10186
10187 target_size = 0;
c64b7983
JS
10188 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
10189 &target_size);
f96da094
DB
10190 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
10191 (ctx_field_size && !target_size)) {
61bd5218 10192 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
10193 return -EINVAL;
10194 }
f96da094
DB
10195
10196 if (is_narrower_load && size < target_size) {
d895a0f1
IL
10197 u8 shift = bpf_ctx_narrow_access_offset(
10198 off, size, size_default) * 8;
46f53a65
AI
10199 if (ctx_field_size <= 4) {
10200 if (shift)
10201 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
10202 insn->dst_reg,
10203 shift);
31fd8581 10204 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 10205 (1 << size * 8) - 1);
46f53a65
AI
10206 } else {
10207 if (shift)
10208 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
10209 insn->dst_reg,
10210 shift);
31fd8581 10211 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 10212 (1ULL << size * 8) - 1);
46f53a65 10213 }
31fd8581 10214 }
9bac3d6d 10215
8041902d 10216 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
10217 if (!new_prog)
10218 return -ENOMEM;
10219
3df126f3 10220 delta += cnt - 1;
9bac3d6d
AS
10221
10222 /* keep walking new program and skip insns we just inserted */
10223 env->prog = new_prog;
3df126f3 10224 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
10225 }
10226
10227 return 0;
10228}
10229
1c2a088a
AS
10230static int jit_subprogs(struct bpf_verifier_env *env)
10231{
10232 struct bpf_prog *prog = env->prog, **func, *tmp;
10233 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 10234 struct bpf_map *map_ptr;
7105e828 10235 struct bpf_insn *insn;
1c2a088a 10236 void *old_bpf_func;
c4c0bdc0 10237 int err, num_exentries;
1c2a088a 10238
f910cefa 10239 if (env->subprog_cnt <= 1)
1c2a088a
AS
10240 return 0;
10241
7105e828 10242 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
10243 if (insn->code != (BPF_JMP | BPF_CALL) ||
10244 insn->src_reg != BPF_PSEUDO_CALL)
10245 continue;
c7a89784
DB
10246 /* Upon error here we cannot fall back to interpreter but
10247 * need a hard reject of the program. Thus -EFAULT is
10248 * propagated in any case.
10249 */
1c2a088a
AS
10250 subprog = find_subprog(env, i + insn->imm + 1);
10251 if (subprog < 0) {
10252 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
10253 i + insn->imm + 1);
10254 return -EFAULT;
10255 }
10256 /* temporarily remember subprog id inside insn instead of
10257 * aux_data, since next loop will split up all insns into funcs
10258 */
f910cefa 10259 insn->off = subprog;
1c2a088a
AS
10260 /* remember original imm in case JIT fails and fallback
10261 * to interpreter will be needed
10262 */
10263 env->insn_aux_data[i].call_imm = insn->imm;
10264 /* point imm to __bpf_call_base+1 from JITs point of view */
10265 insn->imm = 1;
10266 }
10267
c454a46b
MKL
10268 err = bpf_prog_alloc_jited_linfo(prog);
10269 if (err)
10270 goto out_undo_insn;
10271
10272 err = -ENOMEM;
6396bb22 10273 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 10274 if (!func)
c7a89784 10275 goto out_undo_insn;
1c2a088a 10276
f910cefa 10277 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 10278 subprog_start = subprog_end;
4cb3d99c 10279 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
10280
10281 len = subprog_end - subprog_start;
492ecee8
AS
10282 /* BPF_PROG_RUN doesn't call subprogs directly,
10283 * hence main prog stats include the runtime of subprogs.
10284 * subprogs don't have IDs and not reachable via prog_get_next_id
10285 * func[i]->aux->stats will never be accessed and stays NULL
10286 */
10287 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
10288 if (!func[i])
10289 goto out_free;
10290 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
10291 len * sizeof(struct bpf_insn));
4f74d809 10292 func[i]->type = prog->type;
1c2a088a 10293 func[i]->len = len;
4f74d809
DB
10294 if (bpf_prog_calc_tag(func[i]))
10295 goto out_free;
1c2a088a 10296 func[i]->is_func = 1;
ba64e7d8
YS
10297 func[i]->aux->func_idx = i;
10298 /* the btf and func_info will be freed only at prog->aux */
10299 func[i]->aux->btf = prog->aux->btf;
10300 func[i]->aux->func_info = prog->aux->func_info;
10301
a748c697
MF
10302 for (j = 0; j < prog->aux->size_poke_tab; j++) {
10303 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
10304 int ret;
10305
10306 if (!(insn_idx >= subprog_start &&
10307 insn_idx <= subprog_end))
10308 continue;
10309
10310 ret = bpf_jit_add_poke_descriptor(func[i],
10311 &prog->aux->poke_tab[j]);
10312 if (ret < 0) {
10313 verbose(env, "adding tail call poke descriptor failed\n");
10314 goto out_free;
10315 }
10316
10317 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
10318
10319 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
10320 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
10321 if (ret < 0) {
10322 verbose(env, "tracking tail call prog failed\n");
10323 goto out_free;
10324 }
10325 }
10326
1c2a088a
AS
10327 /* Use bpf_prog_F_tag to indicate functions in stack traces.
10328 * Long term would need debug info to populate names
10329 */
10330 func[i]->aux->name[0] = 'F';
9c8105bd 10331 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 10332 func[i]->jit_requested = 1;
c454a46b
MKL
10333 func[i]->aux->linfo = prog->aux->linfo;
10334 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
10335 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
10336 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
10337 num_exentries = 0;
10338 insn = func[i]->insnsi;
10339 for (j = 0; j < func[i]->len; j++, insn++) {
10340 if (BPF_CLASS(insn->code) == BPF_LDX &&
10341 BPF_MODE(insn->code) == BPF_PROBE_MEM)
10342 num_exentries++;
10343 }
10344 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 10345 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
10346 func[i] = bpf_int_jit_compile(func[i]);
10347 if (!func[i]->jited) {
10348 err = -ENOTSUPP;
10349 goto out_free;
10350 }
10351 cond_resched();
10352 }
a748c697
MF
10353
10354 /* Untrack main program's aux structs so that during map_poke_run()
10355 * we will not stumble upon the unfilled poke descriptors; each
10356 * of the main program's poke descs got distributed across subprogs
10357 * and got tracked onto map, so we are sure that none of them will
10358 * be missed after the operation below
10359 */
10360 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10361 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10362
10363 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
10364 }
10365
1c2a088a
AS
10366 /* at this point all bpf functions were successfully JITed
10367 * now populate all bpf_calls with correct addresses and
10368 * run last pass of JIT
10369 */
f910cefa 10370 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10371 insn = func[i]->insnsi;
10372 for (j = 0; j < func[i]->len; j++, insn++) {
10373 if (insn->code != (BPF_JMP | BPF_CALL) ||
10374 insn->src_reg != BPF_PSEUDO_CALL)
10375 continue;
10376 subprog = insn->off;
0d306c31
PB
10377 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
10378 __bpf_call_base;
1c2a088a 10379 }
2162fed4
SD
10380
10381 /* we use the aux data to keep a list of the start addresses
10382 * of the JITed images for each function in the program
10383 *
10384 * for some architectures, such as powerpc64, the imm field
10385 * might not be large enough to hold the offset of the start
10386 * address of the callee's JITed image from __bpf_call_base
10387 *
10388 * in such cases, we can lookup the start address of a callee
10389 * by using its subprog id, available from the off field of
10390 * the call instruction, as an index for this list
10391 */
10392 func[i]->aux->func = func;
10393 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 10394 }
f910cefa 10395 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10396 old_bpf_func = func[i]->bpf_func;
10397 tmp = bpf_int_jit_compile(func[i]);
10398 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
10399 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 10400 err = -ENOTSUPP;
1c2a088a
AS
10401 goto out_free;
10402 }
10403 cond_resched();
10404 }
10405
10406 /* finally lock prog and jit images for all functions and
10407 * populate kallsysm
10408 */
f910cefa 10409 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
10410 bpf_prog_lock_ro(func[i]);
10411 bpf_prog_kallsyms_add(func[i]);
10412 }
7105e828
DB
10413
10414 /* Last step: make now unused interpreter insns from main
10415 * prog consistent for later dump requests, so they can
10416 * later look the same as if they were interpreted only.
10417 */
10418 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
10419 if (insn->code != (BPF_JMP | BPF_CALL) ||
10420 insn->src_reg != BPF_PSEUDO_CALL)
10421 continue;
10422 insn->off = env->insn_aux_data[i].call_imm;
10423 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 10424 insn->imm = subprog;
7105e828
DB
10425 }
10426
1c2a088a
AS
10427 prog->jited = 1;
10428 prog->bpf_func = func[0]->bpf_func;
10429 prog->aux->func = func;
f910cefa 10430 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 10431 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
10432 return 0;
10433out_free:
a748c697
MF
10434 for (i = 0; i < env->subprog_cnt; i++) {
10435 if (!func[i])
10436 continue;
10437
10438 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
10439 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
10440 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
10441 }
10442 bpf_jit_free(func[i]);
10443 }
1c2a088a 10444 kfree(func);
c7a89784 10445out_undo_insn:
1c2a088a
AS
10446 /* cleanup main prog to be interpreted */
10447 prog->jit_requested = 0;
10448 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
10449 if (insn->code != (BPF_JMP | BPF_CALL) ||
10450 insn->src_reg != BPF_PSEUDO_CALL)
10451 continue;
10452 insn->off = 0;
10453 insn->imm = env->insn_aux_data[i].call_imm;
10454 }
c454a46b 10455 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
10456 return err;
10457}
10458
1ea47e01
AS
10459static int fixup_call_args(struct bpf_verifier_env *env)
10460{
19d28fbd 10461#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
10462 struct bpf_prog *prog = env->prog;
10463 struct bpf_insn *insn = prog->insnsi;
10464 int i, depth;
19d28fbd 10465#endif
e4052d06 10466 int err = 0;
1ea47e01 10467
e4052d06
QM
10468 if (env->prog->jit_requested &&
10469 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
10470 err = jit_subprogs(env);
10471 if (err == 0)
1c2a088a 10472 return 0;
c7a89784
DB
10473 if (err == -EFAULT)
10474 return err;
19d28fbd
DM
10475 }
10476#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e411901c
MF
10477 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
10478 /* When JIT fails the progs with bpf2bpf calls and tail_calls
10479 * have to be rejected, since interpreter doesn't support them yet.
10480 */
10481 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
10482 return -EINVAL;
10483 }
1ea47e01
AS
10484 for (i = 0; i < prog->len; i++, insn++) {
10485 if (insn->code != (BPF_JMP | BPF_CALL) ||
10486 insn->src_reg != BPF_PSEUDO_CALL)
10487 continue;
10488 depth = get_callee_stack_depth(env, insn, i);
10489 if (depth < 0)
10490 return depth;
10491 bpf_patch_call_args(insn, depth);
10492 }
19d28fbd
DM
10493 err = 0;
10494#endif
10495 return err;
1ea47e01
AS
10496}
10497
79741b3b 10498/* fixup insn->imm field of bpf_call instructions
81ed18ab 10499 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
10500 *
10501 * this function is called after eBPF program passed verification
10502 */
79741b3b 10503static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 10504{
79741b3b 10505 struct bpf_prog *prog = env->prog;
d2e4c1e6 10506 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 10507 struct bpf_insn *insn = prog->insnsi;
e245c5c6 10508 const struct bpf_func_proto *fn;
79741b3b 10509 const int insn_cnt = prog->len;
09772d92 10510 const struct bpf_map_ops *ops;
c93552c4 10511 struct bpf_insn_aux_data *aux;
81ed18ab
AS
10512 struct bpf_insn insn_buf[16];
10513 struct bpf_prog *new_prog;
10514 struct bpf_map *map_ptr;
d2e4c1e6 10515 int i, ret, cnt, delta = 0;
e245c5c6 10516
79741b3b 10517 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
10518 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10519 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10520 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 10521 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
10522 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10523 struct bpf_insn mask_and_div[] = {
10524 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10525 /* Rx div 0 -> 0 */
10526 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10527 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10528 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10529 *insn,
10530 };
10531 struct bpf_insn mask_and_mod[] = {
10532 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10533 /* Rx mod 0 -> Rx */
10534 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10535 *insn,
10536 };
10537 struct bpf_insn *patchlet;
10538
10539 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10540 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10541 patchlet = mask_and_div + (is64 ? 1 : 0);
10542 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10543 } else {
10544 patchlet = mask_and_mod + (is64 ? 1 : 0);
10545 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10546 }
10547
10548 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
10549 if (!new_prog)
10550 return -ENOMEM;
10551
10552 delta += cnt - 1;
10553 env->prog = prog = new_prog;
10554 insn = new_prog->insnsi + i + delta;
10555 continue;
10556 }
10557
e0cea7ce
DB
10558 if (BPF_CLASS(insn->code) == BPF_LD &&
10559 (BPF_MODE(insn->code) == BPF_ABS ||
10560 BPF_MODE(insn->code) == BPF_IND)) {
10561 cnt = env->ops->gen_ld_abs(insn, insn_buf);
10562 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10563 verbose(env, "bpf verifier is misconfigured\n");
10564 return -EINVAL;
10565 }
10566
10567 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10568 if (!new_prog)
10569 return -ENOMEM;
10570
10571 delta += cnt - 1;
10572 env->prog = prog = new_prog;
10573 insn = new_prog->insnsi + i + delta;
10574 continue;
10575 }
10576
979d63d5
DB
10577 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10578 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10579 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10580 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10581 struct bpf_insn insn_buf[16];
10582 struct bpf_insn *patch = &insn_buf[0];
10583 bool issrc, isneg;
10584 u32 off_reg;
10585
10586 aux = &env->insn_aux_data[i + delta];
3612af78
DB
10587 if (!aux->alu_state ||
10588 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
10589 continue;
10590
10591 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10592 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10593 BPF_ALU_SANITIZE_SRC;
10594
10595 off_reg = issrc ? insn->src_reg : insn->dst_reg;
10596 if (isneg)
10597 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10598 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10599 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10600 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10601 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10602 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10603 if (issrc) {
10604 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10605 off_reg);
10606 insn->src_reg = BPF_REG_AX;
10607 } else {
10608 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10609 BPF_REG_AX);
10610 }
10611 if (isneg)
10612 insn->code = insn->code == code_add ?
10613 code_sub : code_add;
10614 *patch++ = *insn;
10615 if (issrc && isneg)
10616 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10617 cnt = patch - insn_buf;
10618
10619 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10620 if (!new_prog)
10621 return -ENOMEM;
10622
10623 delta += cnt - 1;
10624 env->prog = prog = new_prog;
10625 insn = new_prog->insnsi + i + delta;
10626 continue;
10627 }
10628
79741b3b
AS
10629 if (insn->code != (BPF_JMP | BPF_CALL))
10630 continue;
cc8b0b92
AS
10631 if (insn->src_reg == BPF_PSEUDO_CALL)
10632 continue;
e245c5c6 10633
79741b3b
AS
10634 if (insn->imm == BPF_FUNC_get_route_realm)
10635 prog->dst_needed = 1;
10636 if (insn->imm == BPF_FUNC_get_prandom_u32)
10637 bpf_user_rnd_init_once();
9802d865
JB
10638 if (insn->imm == BPF_FUNC_override_return)
10639 prog->kprobe_override = 1;
79741b3b 10640 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
10641 /* If we tail call into other programs, we
10642 * cannot make any assumptions since they can
10643 * be replaced dynamically during runtime in
10644 * the program array.
10645 */
10646 prog->cb_access = 1;
e411901c
MF
10647 if (!allow_tail_call_in_subprogs(env))
10648 prog->aux->stack_depth = MAX_BPF_STACK;
10649 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 10650
79741b3b
AS
10651 /* mark bpf_tail_call as different opcode to avoid
10652 * conditional branch in the interpeter for every normal
10653 * call and to prevent accidental JITing by JIT compiler
10654 * that doesn't support bpf_tail_call yet
e245c5c6 10655 */
79741b3b 10656 insn->imm = 0;
71189fa9 10657 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 10658
c93552c4 10659 aux = &env->insn_aux_data[i + delta];
2c78ee89 10660 if (env->bpf_capable && !expect_blinding &&
cc52d914 10661 prog->jit_requested &&
d2e4c1e6
DB
10662 !bpf_map_key_poisoned(aux) &&
10663 !bpf_map_ptr_poisoned(aux) &&
10664 !bpf_map_ptr_unpriv(aux)) {
10665 struct bpf_jit_poke_descriptor desc = {
10666 .reason = BPF_POKE_REASON_TAIL_CALL,
10667 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10668 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 10669 .insn_idx = i + delta,
d2e4c1e6
DB
10670 };
10671
10672 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10673 if (ret < 0) {
10674 verbose(env, "adding tail call poke descriptor failed\n");
10675 return ret;
10676 }
10677
10678 insn->imm = ret + 1;
10679 continue;
10680 }
10681
c93552c4
DB
10682 if (!bpf_map_ptr_unpriv(aux))
10683 continue;
10684
b2157399
AS
10685 /* instead of changing every JIT dealing with tail_call
10686 * emit two extra insns:
10687 * if (index >= max_entries) goto out;
10688 * index &= array->index_mask;
10689 * to avoid out-of-bounds cpu speculation
10690 */
c93552c4 10691 if (bpf_map_ptr_poisoned(aux)) {
40950343 10692 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
10693 return -EINVAL;
10694 }
c93552c4 10695
d2e4c1e6 10696 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
10697 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10698 map_ptr->max_entries, 2);
10699 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10700 container_of(map_ptr,
10701 struct bpf_array,
10702 map)->index_mask);
10703 insn_buf[2] = *insn;
10704 cnt = 3;
10705 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10706 if (!new_prog)
10707 return -ENOMEM;
10708
10709 delta += cnt - 1;
10710 env->prog = prog = new_prog;
10711 insn = new_prog->insnsi + i + delta;
79741b3b
AS
10712 continue;
10713 }
e245c5c6 10714
89c63074 10715 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
10716 * and other inlining handlers are currently limited to 64 bit
10717 * only.
89c63074 10718 */
60b58afc 10719 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
10720 (insn->imm == BPF_FUNC_map_lookup_elem ||
10721 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
10722 insn->imm == BPF_FUNC_map_delete_elem ||
10723 insn->imm == BPF_FUNC_map_push_elem ||
10724 insn->imm == BPF_FUNC_map_pop_elem ||
10725 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
10726 aux = &env->insn_aux_data[i + delta];
10727 if (bpf_map_ptr_poisoned(aux))
10728 goto patch_call_imm;
10729
d2e4c1e6 10730 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
10731 ops = map_ptr->ops;
10732 if (insn->imm == BPF_FUNC_map_lookup_elem &&
10733 ops->map_gen_lookup) {
10734 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10735 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10736 verbose(env, "bpf verifier is misconfigured\n");
10737 return -EINVAL;
10738 }
81ed18ab 10739
09772d92
DB
10740 new_prog = bpf_patch_insn_data(env, i + delta,
10741 insn_buf, cnt);
10742 if (!new_prog)
10743 return -ENOMEM;
81ed18ab 10744
09772d92
DB
10745 delta += cnt - 1;
10746 env->prog = prog = new_prog;
10747 insn = new_prog->insnsi + i + delta;
10748 continue;
10749 }
81ed18ab 10750
09772d92
DB
10751 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10752 (void *(*)(struct bpf_map *map, void *key))NULL));
10753 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10754 (int (*)(struct bpf_map *map, void *key))NULL));
10755 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10756 (int (*)(struct bpf_map *map, void *key, void *value,
10757 u64 flags))NULL));
84430d42
DB
10758 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10759 (int (*)(struct bpf_map *map, void *value,
10760 u64 flags))NULL));
10761 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10762 (int (*)(struct bpf_map *map, void *value))NULL));
10763 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10764 (int (*)(struct bpf_map *map, void *value))NULL));
10765
09772d92
DB
10766 switch (insn->imm) {
10767 case BPF_FUNC_map_lookup_elem:
10768 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10769 __bpf_call_base;
10770 continue;
10771 case BPF_FUNC_map_update_elem:
10772 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10773 __bpf_call_base;
10774 continue;
10775 case BPF_FUNC_map_delete_elem:
10776 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10777 __bpf_call_base;
10778 continue;
84430d42
DB
10779 case BPF_FUNC_map_push_elem:
10780 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10781 __bpf_call_base;
10782 continue;
10783 case BPF_FUNC_map_pop_elem:
10784 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10785 __bpf_call_base;
10786 continue;
10787 case BPF_FUNC_map_peek_elem:
10788 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10789 __bpf_call_base;
10790 continue;
09772d92 10791 }
81ed18ab 10792
09772d92 10793 goto patch_call_imm;
81ed18ab
AS
10794 }
10795
5576b991
MKL
10796 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10797 insn->imm == BPF_FUNC_jiffies64) {
10798 struct bpf_insn ld_jiffies_addr[2] = {
10799 BPF_LD_IMM64(BPF_REG_0,
10800 (unsigned long)&jiffies),
10801 };
10802
10803 insn_buf[0] = ld_jiffies_addr[0];
10804 insn_buf[1] = ld_jiffies_addr[1];
10805 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10806 BPF_REG_0, 0);
10807 cnt = 3;
10808
10809 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10810 cnt);
10811 if (!new_prog)
10812 return -ENOMEM;
10813
10814 delta += cnt - 1;
10815 env->prog = prog = new_prog;
10816 insn = new_prog->insnsi + i + delta;
10817 continue;
10818 }
10819
81ed18ab 10820patch_call_imm:
5e43f899 10821 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
10822 /* all functions that have prototype and verifier allowed
10823 * programs to call them, must be real in-kernel functions
10824 */
10825 if (!fn->func) {
61bd5218
JK
10826 verbose(env,
10827 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
10828 func_id_name(insn->imm), insn->imm);
10829 return -EFAULT;
e245c5c6 10830 }
79741b3b 10831 insn->imm = fn->func - __bpf_call_base;
e245c5c6 10832 }
e245c5c6 10833
d2e4c1e6
DB
10834 /* Since poke tab is now finalized, publish aux to tracker. */
10835 for (i = 0; i < prog->aux->size_poke_tab; i++) {
10836 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10837 if (!map_ptr->ops->map_poke_track ||
10838 !map_ptr->ops->map_poke_untrack ||
10839 !map_ptr->ops->map_poke_run) {
10840 verbose(env, "bpf verifier is misconfigured\n");
10841 return -EINVAL;
10842 }
10843
10844 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10845 if (ret < 0) {
10846 verbose(env, "tracking tail call prog failed\n");
10847 return ret;
10848 }
10849 }
10850
79741b3b
AS
10851 return 0;
10852}
e245c5c6 10853
58e2af8b 10854static void free_states(struct bpf_verifier_env *env)
f1bca824 10855{
58e2af8b 10856 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
10857 int i;
10858
9f4686c4
AS
10859 sl = env->free_list;
10860 while (sl) {
10861 sln = sl->next;
10862 free_verifier_state(&sl->state, false);
10863 kfree(sl);
10864 sl = sln;
10865 }
51c39bb1 10866 env->free_list = NULL;
9f4686c4 10867
f1bca824
AS
10868 if (!env->explored_states)
10869 return;
10870
dc2a4ebc 10871 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
10872 sl = env->explored_states[i];
10873
a8f500af
AS
10874 while (sl) {
10875 sln = sl->next;
10876 free_verifier_state(&sl->state, false);
10877 kfree(sl);
10878 sl = sln;
10879 }
51c39bb1 10880 env->explored_states[i] = NULL;
f1bca824 10881 }
51c39bb1 10882}
f1bca824 10883
51c39bb1
AS
10884/* The verifier is using insn_aux_data[] to store temporary data during
10885 * verification and to store information for passes that run after the
10886 * verification like dead code sanitization. do_check_common() for subprogram N
10887 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10888 * temporary data after do_check_common() finds that subprogram N cannot be
10889 * verified independently. pass_cnt counts the number of times
10890 * do_check_common() was run and insn->aux->seen tells the pass number
10891 * insn_aux_data was touched. These variables are compared to clear temporary
10892 * data from failed pass. For testing and experiments do_check_common() can be
10893 * run multiple times even when prior attempt to verify is unsuccessful.
10894 */
10895static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10896{
10897 struct bpf_insn *insn = env->prog->insnsi;
10898 struct bpf_insn_aux_data *aux;
10899 int i, class;
10900
10901 for (i = 0; i < env->prog->len; i++) {
10902 class = BPF_CLASS(insn[i].code);
10903 if (class != BPF_LDX && class != BPF_STX)
10904 continue;
10905 aux = &env->insn_aux_data[i];
10906 if (aux->seen != env->pass_cnt)
10907 continue;
10908 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10909 }
f1bca824
AS
10910}
10911
51c39bb1
AS
10912static int do_check_common(struct bpf_verifier_env *env, int subprog)
10913{
6f8a57cc 10914 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
10915 struct bpf_verifier_state *state;
10916 struct bpf_reg_state *regs;
10917 int ret, i;
10918
10919 env->prev_linfo = NULL;
10920 env->pass_cnt++;
10921
10922 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10923 if (!state)
10924 return -ENOMEM;
10925 state->curframe = 0;
10926 state->speculative = false;
10927 state->branches = 1;
10928 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10929 if (!state->frame[0]) {
10930 kfree(state);
10931 return -ENOMEM;
10932 }
10933 env->cur_state = state;
10934 init_func_state(env, state->frame[0],
10935 BPF_MAIN_FUNC /* callsite */,
10936 0 /* frameno */,
10937 subprog);
10938
10939 regs = state->frame[state->curframe]->regs;
be8704ff 10940 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
10941 ret = btf_prepare_func_args(env, subprog, regs);
10942 if (ret)
10943 goto out;
10944 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
10945 if (regs[i].type == PTR_TO_CTX)
10946 mark_reg_known_zero(env, regs, i);
10947 else if (regs[i].type == SCALAR_VALUE)
10948 mark_reg_unknown(env, regs, i);
10949 }
10950 } else {
10951 /* 1st arg to a function */
10952 regs[BPF_REG_1].type = PTR_TO_CTX;
10953 mark_reg_known_zero(env, regs, BPF_REG_1);
10954 ret = btf_check_func_arg_match(env, subprog, regs);
10955 if (ret == -EFAULT)
10956 /* unlikely verifier bug. abort.
10957 * ret == 0 and ret < 0 are sadly acceptable for
10958 * main() function due to backward compatibility.
10959 * Like socket filter program may be written as:
10960 * int bpf_prog(struct pt_regs *ctx)
10961 * and never dereference that ctx in the program.
10962 * 'struct pt_regs' is a type mismatch for socket
10963 * filter that should be using 'struct __sk_buff'.
10964 */
10965 goto out;
10966 }
10967
10968 ret = do_check(env);
10969out:
f59bbfc2
AS
10970 /* check for NULL is necessary, since cur_state can be freed inside
10971 * do_check() under memory pressure.
10972 */
10973 if (env->cur_state) {
10974 free_verifier_state(env->cur_state, true);
10975 env->cur_state = NULL;
10976 }
6f8a57cc
AN
10977 while (!pop_stack(env, NULL, NULL, false));
10978 if (!ret && pop_log)
10979 bpf_vlog_reset(&env->log, 0);
51c39bb1
AS
10980 free_states(env);
10981 if (ret)
10982 /* clean aux data in case subprog was rejected */
10983 sanitize_insn_aux_data(env);
10984 return ret;
10985}
10986
10987/* Verify all global functions in a BPF program one by one based on their BTF.
10988 * All global functions must pass verification. Otherwise the whole program is rejected.
10989 * Consider:
10990 * int bar(int);
10991 * int foo(int f)
10992 * {
10993 * return bar(f);
10994 * }
10995 * int bar(int b)
10996 * {
10997 * ...
10998 * }
10999 * foo() will be verified first for R1=any_scalar_value. During verification it
11000 * will be assumed that bar() already verified successfully and call to bar()
11001 * from foo() will be checked for type match only. Later bar() will be verified
11002 * independently to check that it's safe for R1=any_scalar_value.
11003 */
11004static int do_check_subprogs(struct bpf_verifier_env *env)
11005{
11006 struct bpf_prog_aux *aux = env->prog->aux;
11007 int i, ret;
11008
11009 if (!aux->func_info)
11010 return 0;
11011
11012 for (i = 1; i < env->subprog_cnt; i++) {
11013 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11014 continue;
11015 env->insn_idx = env->subprog_info[i].start;
11016 WARN_ON_ONCE(env->insn_idx == 0);
11017 ret = do_check_common(env, i);
11018 if (ret) {
11019 return ret;
11020 } else if (env->log.level & BPF_LOG_LEVEL) {
11021 verbose(env,
11022 "Func#%d is safe for any args that match its prototype\n",
11023 i);
11024 }
11025 }
11026 return 0;
11027}
11028
11029static int do_check_main(struct bpf_verifier_env *env)
11030{
11031 int ret;
11032
11033 env->insn_idx = 0;
11034 ret = do_check_common(env, 0);
11035 if (!ret)
11036 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11037 return ret;
11038}
11039
11040
06ee7115
AS
11041static void print_verification_stats(struct bpf_verifier_env *env)
11042{
11043 int i;
11044
11045 if (env->log.level & BPF_LOG_STATS) {
11046 verbose(env, "verification time %lld usec\n",
11047 div_u64(env->verification_time, 1000));
11048 verbose(env, "stack depth ");
11049 for (i = 0; i < env->subprog_cnt; i++) {
11050 u32 depth = env->subprog_info[i].stack_depth;
11051
11052 verbose(env, "%d", depth);
11053 if (i + 1 < env->subprog_cnt)
11054 verbose(env, "+");
11055 }
11056 verbose(env, "\n");
11057 }
11058 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11059 "total_states %d peak_states %d mark_read %d\n",
11060 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11061 env->max_states_per_insn, env->total_states,
11062 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
11063}
11064
27ae7997
MKL
11065static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11066{
11067 const struct btf_type *t, *func_proto;
11068 const struct bpf_struct_ops *st_ops;
11069 const struct btf_member *member;
11070 struct bpf_prog *prog = env->prog;
11071 u32 btf_id, member_idx;
11072 const char *mname;
11073
11074 btf_id = prog->aux->attach_btf_id;
11075 st_ops = bpf_struct_ops_find(btf_id);
11076 if (!st_ops) {
11077 verbose(env, "attach_btf_id %u is not a supported struct\n",
11078 btf_id);
11079 return -ENOTSUPP;
11080 }
11081
11082 t = st_ops->type;
11083 member_idx = prog->expected_attach_type;
11084 if (member_idx >= btf_type_vlen(t)) {
11085 verbose(env, "attach to invalid member idx %u of struct %s\n",
11086 member_idx, st_ops->name);
11087 return -EINVAL;
11088 }
11089
11090 member = &btf_type_member(t)[member_idx];
11091 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11092 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11093 NULL);
11094 if (!func_proto) {
11095 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11096 mname, member_idx, st_ops->name);
11097 return -EINVAL;
11098 }
11099
11100 if (st_ops->check_member) {
11101 int err = st_ops->check_member(t, member);
11102
11103 if (err) {
11104 verbose(env, "attach to unsupported member %s of struct %s\n",
11105 mname, st_ops->name);
11106 return err;
11107 }
11108 }
11109
11110 prog->aux->attach_func_proto = func_proto;
11111 prog->aux->attach_func_name = mname;
11112 env->ops = st_ops->verifier_ops;
11113
11114 return 0;
11115}
6ba43b76
KS
11116#define SECURITY_PREFIX "security_"
11117
18644cec 11118static int check_attach_modify_return(struct bpf_prog *prog, unsigned long addr)
6ba43b76 11119{
69191754
KS
11120 if (within_error_injection_list(addr) ||
11121 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
11122 sizeof(SECURITY_PREFIX) - 1))
6ba43b76 11123 return 0;
6ba43b76 11124
6ba43b76
KS
11125 return -EINVAL;
11126}
27ae7997 11127
1e6c62a8
AS
11128/* non exhaustive list of sleepable bpf_lsm_*() functions */
11129BTF_SET_START(btf_sleepable_lsm_hooks)
11130#ifdef CONFIG_BPF_LSM
1e6c62a8 11131BTF_ID(func, bpf_lsm_bprm_committed_creds)
29523c5e
AS
11132#else
11133BTF_ID_UNUSED
1e6c62a8
AS
11134#endif
11135BTF_SET_END(btf_sleepable_lsm_hooks)
11136
11137static int check_sleepable_lsm_hook(u32 btf_id)
11138{
11139 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
11140}
11141
11142/* list of non-sleepable functions that are otherwise on
11143 * ALLOW_ERROR_INJECTION list
11144 */
11145BTF_SET_START(btf_non_sleepable_error_inject)
11146/* Three functions below can be called from sleepable and non-sleepable context.
11147 * Assume non-sleepable from bpf safety point of view.
11148 */
11149BTF_ID(func, __add_to_page_cache_locked)
11150BTF_ID(func, should_fail_alloc_page)
11151BTF_ID(func, should_failslab)
11152BTF_SET_END(btf_non_sleepable_error_inject)
11153
11154static int check_non_sleepable_error_inject(u32 btf_id)
11155{
11156 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
11157}
11158
38207291
MKL
11159static int check_attach_btf_id(struct bpf_verifier_env *env)
11160{
11161 struct bpf_prog *prog = env->prog;
be8704ff 11162 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
5b92a28a 11163 struct bpf_prog *tgt_prog = prog->aux->linked_prog;
38207291 11164 u32 btf_id = prog->aux->attach_btf_id;
f1b9509c 11165 const char prefix[] = "btf_trace_";
15d83c4d 11166 struct btf_func_model fmodel;
5b92a28a 11167 int ret = 0, subprog = -1, i;
fec56f58 11168 struct bpf_trampoline *tr;
38207291 11169 const struct btf_type *t;
5b92a28a 11170 bool conservative = true;
38207291 11171 const char *tname;
5b92a28a 11172 struct btf *btf;
fec56f58 11173 long addr;
5b92a28a 11174 u64 key;
38207291 11175
1e6c62a8
AS
11176 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
11177 prog->type != BPF_PROG_TYPE_LSM) {
11178 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
11179 return -EINVAL;
11180 }
11181
27ae7997
MKL
11182 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
11183 return check_struct_ops_btf_id(env);
11184
9e4e01df
KS
11185 if (prog->type != BPF_PROG_TYPE_TRACING &&
11186 prog->type != BPF_PROG_TYPE_LSM &&
11187 !prog_extension)
f1b9509c 11188 return 0;
38207291 11189
f1b9509c
AS
11190 if (!btf_id) {
11191 verbose(env, "Tracing programs must provide btf_id\n");
11192 return -EINVAL;
11193 }
5b92a28a
AS
11194 btf = bpf_prog_get_target_btf(prog);
11195 if (!btf) {
11196 verbose(env,
11197 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
11198 return -EINVAL;
11199 }
11200 t = btf_type_by_id(btf, btf_id);
f1b9509c
AS
11201 if (!t) {
11202 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
11203 return -EINVAL;
11204 }
5b92a28a 11205 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c
AS
11206 if (!tname) {
11207 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
11208 return -EINVAL;
11209 }
5b92a28a
AS
11210 if (tgt_prog) {
11211 struct bpf_prog_aux *aux = tgt_prog->aux;
11212
11213 for (i = 0; i < aux->func_info_cnt; i++)
11214 if (aux->func_info[i].type_id == btf_id) {
11215 subprog = i;
11216 break;
11217 }
11218 if (subprog == -1) {
11219 verbose(env, "Subprog %s doesn't exist\n", tname);
11220 return -EINVAL;
11221 }
11222 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
11223 if (prog_extension) {
11224 if (conservative) {
11225 verbose(env,
11226 "Cannot replace static functions\n");
11227 return -EINVAL;
11228 }
11229 if (!prog->jit_requested) {
11230 verbose(env,
11231 "Extension programs should be JITed\n");
11232 return -EINVAL;
11233 }
11234 env->ops = bpf_verifier_ops[tgt_prog->type];
03f87c0b 11235 prog->expected_attach_type = tgt_prog->expected_attach_type;
be8704ff
AS
11236 }
11237 if (!tgt_prog->jited) {
11238 verbose(env, "Can attach to only JITed progs\n");
11239 return -EINVAL;
11240 }
11241 if (tgt_prog->type == prog->type) {
11242 /* Cannot fentry/fexit another fentry/fexit program.
11243 * Cannot attach program extension to another extension.
11244 * It's ok to attach fentry/fexit to extension program.
11245 */
11246 verbose(env, "Cannot recursively attach\n");
11247 return -EINVAL;
11248 }
11249 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
11250 prog_extension &&
11251 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
11252 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
11253 /* Program extensions can extend all program types
11254 * except fentry/fexit. The reason is the following.
11255 * The fentry/fexit programs are used for performance
11256 * analysis, stats and can be attached to any program
11257 * type except themselves. When extension program is
11258 * replacing XDP function it is necessary to allow
11259 * performance analysis of all functions. Both original
11260 * XDP program and its program extension. Hence
11261 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
11262 * allowed. If extending of fentry/fexit was allowed it
11263 * would be possible to create long call chain
11264 * fentry->extension->fentry->extension beyond
11265 * reasonable stack size. Hence extending fentry is not
11266 * allowed.
11267 */
11268 verbose(env, "Cannot extend fentry/fexit\n");
11269 return -EINVAL;
11270 }
5b92a28a
AS
11271 key = ((u64)aux->id) << 32 | btf_id;
11272 } else {
be8704ff
AS
11273 if (prog_extension) {
11274 verbose(env, "Cannot replace kernel functions\n");
11275 return -EINVAL;
11276 }
5b92a28a
AS
11277 key = btf_id;
11278 }
f1b9509c
AS
11279
11280 switch (prog->expected_attach_type) {
11281 case BPF_TRACE_RAW_TP:
5b92a28a
AS
11282 if (tgt_prog) {
11283 verbose(env,
11284 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
11285 return -EINVAL;
11286 }
38207291
MKL
11287 if (!btf_type_is_typedef(t)) {
11288 verbose(env, "attach_btf_id %u is not a typedef\n",
11289 btf_id);
11290 return -EINVAL;
11291 }
f1b9509c 11292 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
38207291
MKL
11293 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
11294 btf_id, tname);
11295 return -EINVAL;
11296 }
11297 tname += sizeof(prefix) - 1;
5b92a28a 11298 t = btf_type_by_id(btf, t->type);
38207291
MKL
11299 if (!btf_type_is_ptr(t))
11300 /* should never happen in valid vmlinux build */
11301 return -EINVAL;
5b92a28a 11302 t = btf_type_by_id(btf, t->type);
38207291
MKL
11303 if (!btf_type_is_func_proto(t))
11304 /* should never happen in valid vmlinux build */
11305 return -EINVAL;
11306
11307 /* remember two read only pointers that are valid for
11308 * the life time of the kernel
11309 */
11310 prog->aux->attach_func_name = tname;
11311 prog->aux->attach_func_proto = t;
11312 prog->aux->attach_btf_trace = true;
f1b9509c 11313 return 0;
15d83c4d
YS
11314 case BPF_TRACE_ITER:
11315 if (!btf_type_is_func(t)) {
11316 verbose(env, "attach_btf_id %u is not a function\n",
11317 btf_id);
11318 return -EINVAL;
11319 }
11320 t = btf_type_by_id(btf, t->type);
11321 if (!btf_type_is_func_proto(t))
11322 return -EINVAL;
11323 prog->aux->attach_func_name = tname;
11324 prog->aux->attach_func_proto = t;
11325 if (!bpf_iter_prog_supported(prog))
11326 return -EINVAL;
11327 ret = btf_distill_func_proto(&env->log, btf, t,
11328 tname, &fmodel);
11329 return ret;
be8704ff
AS
11330 default:
11331 if (!prog_extension)
11332 return -EINVAL;
11333 /* fallthrough */
ae240823 11334 case BPF_MODIFY_RETURN:
9e4e01df 11335 case BPF_LSM_MAC:
fec56f58
AS
11336 case BPF_TRACE_FENTRY:
11337 case BPF_TRACE_FEXIT:
9e4e01df
KS
11338 prog->aux->attach_func_name = tname;
11339 if (prog->type == BPF_PROG_TYPE_LSM) {
11340 ret = bpf_lsm_verify_prog(&env->log, prog);
11341 if (ret < 0)
11342 return ret;
11343 }
11344
fec56f58
AS
11345 if (!btf_type_is_func(t)) {
11346 verbose(env, "attach_btf_id %u is not a function\n",
11347 btf_id);
11348 return -EINVAL;
11349 }
be8704ff
AS
11350 if (prog_extension &&
11351 btf_check_type_match(env, prog, btf, t))
11352 return -EINVAL;
5b92a28a 11353 t = btf_type_by_id(btf, t->type);
fec56f58
AS
11354 if (!btf_type_is_func_proto(t))
11355 return -EINVAL;
5b92a28a 11356 tr = bpf_trampoline_lookup(key);
fec56f58
AS
11357 if (!tr)
11358 return -ENOMEM;
5b92a28a 11359 /* t is either vmlinux type or another program's type */
fec56f58
AS
11360 prog->aux->attach_func_proto = t;
11361 mutex_lock(&tr->mutex);
11362 if (tr->func.addr) {
11363 prog->aux->trampoline = tr;
11364 goto out;
11365 }
5b92a28a
AS
11366 if (tgt_prog && conservative) {
11367 prog->aux->attach_func_proto = NULL;
11368 t = NULL;
11369 }
11370 ret = btf_distill_func_proto(&env->log, btf, t,
fec56f58
AS
11371 tname, &tr->func.model);
11372 if (ret < 0)
11373 goto out;
5b92a28a 11374 if (tgt_prog) {
e9eeec58
YS
11375 if (subprog == 0)
11376 addr = (long) tgt_prog->bpf_func;
11377 else
11378 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
11379 } else {
11380 addr = kallsyms_lookup_name(tname);
11381 if (!addr) {
11382 verbose(env,
11383 "The address of function %s cannot be found\n",
11384 tname);
11385 ret = -ENOENT;
11386 goto out;
11387 }
fec56f58 11388 }
18644cec 11389
1e6c62a8
AS
11390 if (prog->aux->sleepable) {
11391 ret = -EINVAL;
11392 switch (prog->type) {
11393 case BPF_PROG_TYPE_TRACING:
11394 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
11395 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
11396 */
11397 if (!check_non_sleepable_error_inject(btf_id) &&
11398 within_error_injection_list(addr))
11399 ret = 0;
11400 break;
11401 case BPF_PROG_TYPE_LSM:
11402 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
11403 * Only some of them are sleepable.
11404 */
11405 if (check_sleepable_lsm_hook(btf_id))
11406 ret = 0;
11407 break;
11408 default:
11409 break;
11410 }
11411 if (ret)
11412 verbose(env, "%s is not sleepable\n",
11413 prog->aux->attach_func_name);
11414 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
18644cec
AS
11415 ret = check_attach_modify_return(prog, addr);
11416 if (ret)
11417 verbose(env, "%s() is not modifiable\n",
11418 prog->aux->attach_func_name);
11419 }
18644cec
AS
11420 if (ret)
11421 goto out;
fec56f58
AS
11422 tr->func.addr = (void *)addr;
11423 prog->aux->trampoline = tr;
11424out:
11425 mutex_unlock(&tr->mutex);
11426 if (ret)
11427 bpf_trampoline_put(tr);
11428 return ret;
38207291 11429 }
38207291
MKL
11430}
11431
838e9690
YS
11432int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
11433 union bpf_attr __user *uattr)
51580e79 11434{
06ee7115 11435 u64 start_time = ktime_get_ns();
58e2af8b 11436 struct bpf_verifier_env *env;
b9193c1b 11437 struct bpf_verifier_log *log;
9e4c24e7 11438 int i, len, ret = -EINVAL;
e2ae4ca2 11439 bool is_priv;
51580e79 11440
eba0c929
AB
11441 /* no program is valid */
11442 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
11443 return -EINVAL;
11444
58e2af8b 11445 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
11446 * allocate/free it every time bpf_check() is called
11447 */
58e2af8b 11448 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
11449 if (!env)
11450 return -ENOMEM;
61bd5218 11451 log = &env->log;
cbd35700 11452
9e4c24e7 11453 len = (*prog)->len;
fad953ce 11454 env->insn_aux_data =
9e4c24e7 11455 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
11456 ret = -ENOMEM;
11457 if (!env->insn_aux_data)
11458 goto err_free_env;
9e4c24e7
JK
11459 for (i = 0; i < len; i++)
11460 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 11461 env->prog = *prog;
00176a34 11462 env->ops = bpf_verifier_ops[env->prog->type];
2c78ee89 11463 is_priv = bpf_capable();
0246e64d 11464
8580ac94
AS
11465 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
11466 mutex_lock(&bpf_verifier_lock);
11467 if (!btf_vmlinux)
11468 btf_vmlinux = btf_parse_vmlinux();
11469 mutex_unlock(&bpf_verifier_lock);
11470 }
11471
cbd35700 11472 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
11473 if (!is_priv)
11474 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
11475
11476 if (attr->log_level || attr->log_buf || attr->log_size) {
11477 /* user requested verbose verifier output
11478 * and supplied buffer to store the verification trace
11479 */
e7bf8249
JK
11480 log->level = attr->log_level;
11481 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
11482 log->len_total = attr->log_size;
cbd35700
AS
11483
11484 ret = -EINVAL;
e7bf8249 11485 /* log attributes have to be sane */
7a9f5c65 11486 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 11487 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 11488 goto err_unlock;
cbd35700 11489 }
1ad2f583 11490
8580ac94
AS
11491 if (IS_ERR(btf_vmlinux)) {
11492 /* Either gcc or pahole or kernel are broken. */
11493 verbose(env, "in-kernel BTF is malformed\n");
11494 ret = PTR_ERR(btf_vmlinux);
38207291 11495 goto skip_full_check;
8580ac94
AS
11496 }
11497
1ad2f583
DB
11498 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
11499 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 11500 env->strict_alignment = true;
e9ee9efc
DM
11501 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
11502 env->strict_alignment = false;
cbd35700 11503
2c78ee89 11504 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
41c48f3a 11505 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
11506 env->bypass_spec_v1 = bpf_bypass_spec_v1();
11507 env->bypass_spec_v4 = bpf_bypass_spec_v4();
11508 env->bpf_capable = bpf_capable();
e2ae4ca2 11509
10d274e8
AS
11510 if (is_priv)
11511 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
11512
f4e3ec0d
JK
11513 ret = replace_map_fd_with_map_ptr(env);
11514 if (ret < 0)
11515 goto skip_full_check;
11516
cae1927c 11517 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 11518 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 11519 if (ret)
f4e3ec0d 11520 goto skip_full_check;
ab3f0063
JK
11521 }
11522
dc2a4ebc 11523 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 11524 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
11525 GFP_USER);
11526 ret = -ENOMEM;
11527 if (!env->explored_states)
11528 goto skip_full_check;
11529
d9762e84 11530 ret = check_subprogs(env);
475fb78f
AS
11531 if (ret < 0)
11532 goto skip_full_check;
11533
c454a46b 11534 ret = check_btf_info(env, attr, uattr);
838e9690
YS
11535 if (ret < 0)
11536 goto skip_full_check;
11537
be8704ff
AS
11538 ret = check_attach_btf_id(env);
11539 if (ret)
11540 goto skip_full_check;
11541
d9762e84
MKL
11542 ret = check_cfg(env);
11543 if (ret < 0)
11544 goto skip_full_check;
11545
51c39bb1
AS
11546 ret = do_check_subprogs(env);
11547 ret = ret ?: do_check_main(env);
cbd35700 11548
c941ce9c
QM
11549 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11550 ret = bpf_prog_offload_finalize(env);
11551
0246e64d 11552skip_full_check:
51c39bb1 11553 kvfree(env->explored_states);
0246e64d 11554
c131187d 11555 if (ret == 0)
9b38c405 11556 ret = check_max_stack_depth(env);
c131187d 11557
9b38c405 11558 /* instruction rewrites happen after this point */
e2ae4ca2
JK
11559 if (is_priv) {
11560 if (ret == 0)
11561 opt_hard_wire_dead_code_branches(env);
52875a04
JK
11562 if (ret == 0)
11563 ret = opt_remove_dead_code(env);
a1b14abc
JK
11564 if (ret == 0)
11565 ret = opt_remove_nops(env);
52875a04
JK
11566 } else {
11567 if (ret == 0)
11568 sanitize_dead_code(env);
e2ae4ca2
JK
11569 }
11570
9bac3d6d
AS
11571 if (ret == 0)
11572 /* program is valid, convert *(u32*)(ctx + off) accesses */
11573 ret = convert_ctx_accesses(env);
11574
e245c5c6 11575 if (ret == 0)
79741b3b 11576 ret = fixup_bpf_calls(env);
e245c5c6 11577
a4b1d3c1
JW
11578 /* do 32-bit optimization after insn patching has done so those patched
11579 * insns could be handled correctly.
11580 */
d6c2308c
JW
11581 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11582 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11583 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11584 : false;
a4b1d3c1
JW
11585 }
11586
1ea47e01
AS
11587 if (ret == 0)
11588 ret = fixup_call_args(env);
11589
06ee7115
AS
11590 env->verification_time = ktime_get_ns() - start_time;
11591 print_verification_stats(env);
11592
a2a7d570 11593 if (log->level && bpf_verifier_log_full(log))
cbd35700 11594 ret = -ENOSPC;
a2a7d570 11595 if (log->level && !log->ubuf) {
cbd35700 11596 ret = -EFAULT;
a2a7d570 11597 goto err_release_maps;
cbd35700
AS
11598 }
11599
0246e64d
AS
11600 if (ret == 0 && env->used_map_cnt) {
11601 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
11602 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11603 sizeof(env->used_maps[0]),
11604 GFP_KERNEL);
0246e64d 11605
9bac3d6d 11606 if (!env->prog->aux->used_maps) {
0246e64d 11607 ret = -ENOMEM;
a2a7d570 11608 goto err_release_maps;
0246e64d
AS
11609 }
11610
9bac3d6d 11611 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 11612 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 11613 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
11614
11615 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11616 * bpf_ld_imm64 instructions
11617 */
11618 convert_pseudo_ld_imm64(env);
11619 }
cbd35700 11620
ba64e7d8
YS
11621 if (ret == 0)
11622 adjust_btf_func(env);
11623
a2a7d570 11624err_release_maps:
9bac3d6d 11625 if (!env->prog->aux->used_maps)
0246e64d 11626 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 11627 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
11628 */
11629 release_maps(env);
03f87c0b
THJ
11630
11631 /* extension progs temporarily inherit the attach_type of their targets
11632 for verification purposes, so set it back to zero before returning
11633 */
11634 if (env->prog->type == BPF_PROG_TYPE_EXT)
11635 env->prog->expected_attach_type = 0;
11636
9bac3d6d 11637 *prog = env->prog;
3df126f3 11638err_unlock:
45a73c17
AS
11639 if (!is_priv)
11640 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
11641 vfree(env->insn_aux_data);
11642err_free_env:
11643 kfree(env);
51580e79
AS
11644 return ret;
11645}