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