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