bpf: Annotate context types
[linux-2.6-block.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 25static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 26#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
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 4149 for (i = 0; i < 5; i++) {
9cc31b3a
AS
4150 err = btf_resolve_helper_id(&env->log, fn, i);
4151 if (err > 0)
4152 meta.btf_id = err;
a7658e1a
AS
4153 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4154 if (err)
4155 return err;
4156 }
17a52670 4157
c93552c4
DB
4158 err = record_func_map(env, &meta, func_id, insn_idx);
4159 if (err)
4160 return err;
4161
435faee1
DB
4162 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4163 * is inferred from register state.
4164 */
4165 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
4166 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4167 BPF_WRITE, -1, false);
435faee1
DB
4168 if (err)
4169 return err;
4170 }
4171
fd978bf7
JS
4172 if (func_id == BPF_FUNC_tail_call) {
4173 err = check_reference_leak(env);
4174 if (err) {
4175 verbose(env, "tail_call would lead to reference leak\n");
4176 return err;
4177 }
4178 } else if (is_release_function(func_id)) {
1b986589 4179 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
4180 if (err) {
4181 verbose(env, "func %s#%d reference has not been acquired before\n",
4182 func_id_name(func_id), func_id);
fd978bf7 4183 return err;
46f8bc92 4184 }
fd978bf7
JS
4185 }
4186
638f5b90 4187 regs = cur_regs(env);
cd339431
RG
4188
4189 /* check that flags argument in get_local_storage(map, flags) is 0,
4190 * this is required because get_local_storage() can't return an error.
4191 */
4192 if (func_id == BPF_FUNC_get_local_storage &&
4193 !register_is_null(&regs[BPF_REG_2])) {
4194 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4195 return -EINVAL;
4196 }
4197
17a52670 4198 /* reset caller saved regs */
dc503a8a 4199 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 4200 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
4201 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4202 }
17a52670 4203
5327ed3d
JW
4204 /* helper call returns 64-bit value. */
4205 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4206
dc503a8a 4207 /* update return register (already marked as written above) */
17a52670 4208 if (fn->ret_type == RET_INTEGER) {
f1174f77 4209 /* sets type to SCALAR_VALUE */
61bd5218 4210 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
4211 } else if (fn->ret_type == RET_VOID) {
4212 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
4213 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4214 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 4215 /* There is no offset yet applied, variable or fixed */
61bd5218 4216 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
4217 /* remember map_ptr, so that check_map_access()
4218 * can check 'value_size' boundary of memory access
4219 * to map element returned from bpf_map_lookup_elem()
4220 */
33ff9823 4221 if (meta.map_ptr == NULL) {
61bd5218
JK
4222 verbose(env,
4223 "kernel subsystem misconfigured verifier\n");
17a52670
AS
4224 return -EINVAL;
4225 }
33ff9823 4226 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
4227 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4228 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
4229 if (map_value_has_spin_lock(meta.map_ptr))
4230 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
4231 } else {
4232 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4233 regs[BPF_REG_0].id = ++env->id_gen;
4234 }
c64b7983
JS
4235 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4236 mark_reg_known_zero(env, regs, BPF_REG_0);
4237 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
0f3adc28 4238 regs[BPF_REG_0].id = ++env->id_gen;
85a51f8c
LB
4239 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4240 mark_reg_known_zero(env, regs, BPF_REG_0);
4241 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4242 regs[BPF_REG_0].id = ++env->id_gen;
655a51e5
MKL
4243 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4244 mark_reg_known_zero(env, regs, BPF_REG_0);
4245 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4246 regs[BPF_REG_0].id = ++env->id_gen;
17a52670 4247 } else {
61bd5218 4248 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 4249 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
4250 return -EINVAL;
4251 }
04fd61ab 4252
0f3adc28 4253 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
4254 /* For release_reference() */
4255 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
0f3adc28
LB
4256 } else if (is_acquire_function(func_id)) {
4257 int id = acquire_reference_state(env, insn_idx);
4258
4259 if (id < 0)
4260 return id;
4261 /* For mark_ptr_or_null_reg() */
4262 regs[BPF_REG_0].id = id;
4263 /* For release_reference() */
4264 regs[BPF_REG_0].ref_obj_id = id;
4265 }
1b986589 4266
849fa506
YS
4267 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4268
61bd5218 4269 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
4270 if (err)
4271 return err;
04fd61ab 4272
c195651e
YS
4273 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4274 const char *err_str;
4275
4276#ifdef CONFIG_PERF_EVENTS
4277 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4278 err_str = "cannot get callchain buffer for func %s#%d\n";
4279#else
4280 err = -ENOTSUPP;
4281 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4282#endif
4283 if (err) {
4284 verbose(env, err_str, func_id_name(func_id), func_id);
4285 return err;
4286 }
4287
4288 env->prog->has_callchain_buf = true;
4289 }
4290
969bf05e
AS
4291 if (changes_data)
4292 clear_all_pkt_pointers(env);
4293 return 0;
4294}
4295
b03c9f9f
EC
4296static bool signed_add_overflows(s64 a, s64 b)
4297{
4298 /* Do the add in u64, where overflow is well-defined */
4299 s64 res = (s64)((u64)a + (u64)b);
4300
4301 if (b < 0)
4302 return res > a;
4303 return res < a;
4304}
4305
4306static bool signed_sub_overflows(s64 a, s64 b)
4307{
4308 /* Do the sub in u64, where overflow is well-defined */
4309 s64 res = (s64)((u64)a - (u64)b);
4310
4311 if (b < 0)
4312 return res < a;
4313 return res > a;
969bf05e
AS
4314}
4315
bb7f0f98
AS
4316static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4317 const struct bpf_reg_state *reg,
4318 enum bpf_reg_type type)
4319{
4320 bool known = tnum_is_const(reg->var_off);
4321 s64 val = reg->var_off.value;
4322 s64 smin = reg->smin_value;
4323
4324 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4325 verbose(env, "math between %s pointer and %lld is not allowed\n",
4326 reg_type_str[type], val);
4327 return false;
4328 }
4329
4330 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4331 verbose(env, "%s pointer offset %d is not allowed\n",
4332 reg_type_str[type], reg->off);
4333 return false;
4334 }
4335
4336 if (smin == S64_MIN) {
4337 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4338 reg_type_str[type]);
4339 return false;
4340 }
4341
4342 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4343 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4344 smin, reg_type_str[type]);
4345 return false;
4346 }
4347
4348 return true;
4349}
4350
979d63d5
DB
4351static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4352{
4353 return &env->insn_aux_data[env->insn_idx];
4354}
4355
4356static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4357 u32 *ptr_limit, u8 opcode, bool off_is_neg)
4358{
4359 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
4360 (opcode == BPF_SUB && !off_is_neg);
4361 u32 off;
4362
4363 switch (ptr_reg->type) {
4364 case PTR_TO_STACK:
088ec26d
AI
4365 /* Indirect variable offset stack access is prohibited in
4366 * unprivileged mode so it's not handled here.
4367 */
979d63d5
DB
4368 off = ptr_reg->off + ptr_reg->var_off.value;
4369 if (mask_to_left)
4370 *ptr_limit = MAX_BPF_STACK + off;
4371 else
4372 *ptr_limit = -off;
4373 return 0;
4374 case PTR_TO_MAP_VALUE:
4375 if (mask_to_left) {
4376 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4377 } else {
4378 off = ptr_reg->smin_value + ptr_reg->off;
4379 *ptr_limit = ptr_reg->map_ptr->value_size - off;
4380 }
4381 return 0;
4382 default:
4383 return -EINVAL;
4384 }
4385}
4386
d3bd7413
DB
4387static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4388 const struct bpf_insn *insn)
4389{
4390 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
4391}
4392
4393static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4394 u32 alu_state, u32 alu_limit)
4395{
4396 /* If we arrived here from different branches with different
4397 * state or limits to sanitize, then this won't work.
4398 */
4399 if (aux->alu_state &&
4400 (aux->alu_state != alu_state ||
4401 aux->alu_limit != alu_limit))
4402 return -EACCES;
4403
4404 /* Corresponding fixup done in fixup_bpf_calls(). */
4405 aux->alu_state = alu_state;
4406 aux->alu_limit = alu_limit;
4407 return 0;
4408}
4409
4410static int sanitize_val_alu(struct bpf_verifier_env *env,
4411 struct bpf_insn *insn)
4412{
4413 struct bpf_insn_aux_data *aux = cur_aux(env);
4414
4415 if (can_skip_alu_sanitation(env, insn))
4416 return 0;
4417
4418 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4419}
4420
979d63d5
DB
4421static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4422 struct bpf_insn *insn,
4423 const struct bpf_reg_state *ptr_reg,
4424 struct bpf_reg_state *dst_reg,
4425 bool off_is_neg)
4426{
4427 struct bpf_verifier_state *vstate = env->cur_state;
4428 struct bpf_insn_aux_data *aux = cur_aux(env);
4429 bool ptr_is_dst_reg = ptr_reg == dst_reg;
4430 u8 opcode = BPF_OP(insn->code);
4431 u32 alu_state, alu_limit;
4432 struct bpf_reg_state tmp;
4433 bool ret;
4434
d3bd7413 4435 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
4436 return 0;
4437
4438 /* We already marked aux for masking from non-speculative
4439 * paths, thus we got here in the first place. We only care
4440 * to explore bad access from here.
4441 */
4442 if (vstate->speculative)
4443 goto do_sim;
4444
4445 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4446 alu_state |= ptr_is_dst_reg ?
4447 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4448
4449 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4450 return 0;
d3bd7413 4451 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
979d63d5 4452 return -EACCES;
979d63d5
DB
4453do_sim:
4454 /* Simulate and find potential out-of-bounds access under
4455 * speculative execution from truncation as a result of
4456 * masking when off was not within expected range. If off
4457 * sits in dst, then we temporarily need to move ptr there
4458 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4459 * for cases where we use K-based arithmetic in one direction
4460 * and truncated reg-based in the other in order to explore
4461 * bad access.
4462 */
4463 if (!ptr_is_dst_reg) {
4464 tmp = *dst_reg;
4465 *dst_reg = *ptr_reg;
4466 }
4467 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
0803278b 4468 if (!ptr_is_dst_reg && ret)
979d63d5
DB
4469 *dst_reg = tmp;
4470 return !ret ? -EFAULT : 0;
4471}
4472
f1174f77 4473/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
4474 * Caller should also handle BPF_MOV case separately.
4475 * If we return -EACCES, caller may want to try again treating pointer as a
4476 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
4477 */
4478static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
4479 struct bpf_insn *insn,
4480 const struct bpf_reg_state *ptr_reg,
4481 const struct bpf_reg_state *off_reg)
969bf05e 4482{
f4d7e40a
AS
4483 struct bpf_verifier_state *vstate = env->cur_state;
4484 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4485 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 4486 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
4487 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
4488 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
4489 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
4490 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
9d7eceed 4491 u32 dst = insn->dst_reg, src = insn->src_reg;
969bf05e 4492 u8 opcode = BPF_OP(insn->code);
979d63d5 4493 int ret;
969bf05e 4494
f1174f77 4495 dst_reg = &regs[dst];
969bf05e 4496
6f16101e
DB
4497 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
4498 smin_val > smax_val || umin_val > umax_val) {
4499 /* Taint dst register if offset had invalid bounds derived from
4500 * e.g. dead branches.
4501 */
4502 __mark_reg_unknown(dst_reg);
4503 return 0;
f1174f77
EC
4504 }
4505
4506 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4507 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
82abbf8d
AS
4508 verbose(env,
4509 "R%d 32-bit pointer arithmetic prohibited\n",
4510 dst);
f1174f77 4511 return -EACCES;
969bf05e
AS
4512 }
4513
aad2eeaf
JS
4514 switch (ptr_reg->type) {
4515 case PTR_TO_MAP_VALUE_OR_NULL:
4516 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4517 dst, reg_type_str[ptr_reg->type]);
f1174f77 4518 return -EACCES;
aad2eeaf
JS
4519 case CONST_PTR_TO_MAP:
4520 case PTR_TO_PACKET_END:
c64b7983
JS
4521 case PTR_TO_SOCKET:
4522 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
4523 case PTR_TO_SOCK_COMMON:
4524 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
4525 case PTR_TO_TCP_SOCK:
4526 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 4527 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
4528 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
4529 dst, reg_type_str[ptr_reg->type]);
f1174f77 4530 return -EACCES;
9d7eceed
DB
4531 case PTR_TO_MAP_VALUE:
4532 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
4533 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
4534 off_reg == dst_reg ? dst : src);
4535 return -EACCES;
4536 }
4537 /* fall-through */
aad2eeaf
JS
4538 default:
4539 break;
f1174f77
EC
4540 }
4541
4542 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4543 * The id may be overwritten later if we create a new variable offset.
969bf05e 4544 */
f1174f77
EC
4545 dst_reg->type = ptr_reg->type;
4546 dst_reg->id = ptr_reg->id;
969bf05e 4547
bb7f0f98
AS
4548 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
4549 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
4550 return -EINVAL;
4551
f1174f77
EC
4552 switch (opcode) {
4553 case BPF_ADD:
979d63d5
DB
4554 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4555 if (ret < 0) {
4556 verbose(env, "R%d tried to add from different maps or paths\n", dst);
4557 return ret;
4558 }
f1174f77
EC
4559 /* We can take a fixed offset as long as it doesn't overflow
4560 * the s32 'off' field
969bf05e 4561 */
b03c9f9f
EC
4562 if (known && (ptr_reg->off + smin_val ==
4563 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 4564 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
4565 dst_reg->smin_value = smin_ptr;
4566 dst_reg->smax_value = smax_ptr;
4567 dst_reg->umin_value = umin_ptr;
4568 dst_reg->umax_value = umax_ptr;
f1174f77 4569 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 4570 dst_reg->off = ptr_reg->off + smin_val;
0962590e 4571 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
4572 break;
4573 }
f1174f77
EC
4574 /* A new variable offset is created. Note that off_reg->off
4575 * == 0, since it's a scalar.
4576 * dst_reg gets the pointer type and since some positive
4577 * integer value was added to the pointer, give it a new 'id'
4578 * if it's a PTR_TO_PACKET.
4579 * this creates a new 'base' pointer, off_reg (variable) gets
4580 * added into the variable offset, and we copy the fixed offset
4581 * from ptr_reg.
969bf05e 4582 */
b03c9f9f
EC
4583 if (signed_add_overflows(smin_ptr, smin_val) ||
4584 signed_add_overflows(smax_ptr, smax_val)) {
4585 dst_reg->smin_value = S64_MIN;
4586 dst_reg->smax_value = S64_MAX;
4587 } else {
4588 dst_reg->smin_value = smin_ptr + smin_val;
4589 dst_reg->smax_value = smax_ptr + smax_val;
4590 }
4591 if (umin_ptr + umin_val < umin_ptr ||
4592 umax_ptr + umax_val < umax_ptr) {
4593 dst_reg->umin_value = 0;
4594 dst_reg->umax_value = U64_MAX;
4595 } else {
4596 dst_reg->umin_value = umin_ptr + umin_val;
4597 dst_reg->umax_value = umax_ptr + umax_val;
4598 }
f1174f77
EC
4599 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
4600 dst_reg->off = ptr_reg->off;
0962590e 4601 dst_reg->raw = ptr_reg->raw;
de8f3a83 4602 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
4603 dst_reg->id = ++env->id_gen;
4604 /* something was added to pkt_ptr, set range to zero */
0962590e 4605 dst_reg->raw = 0;
f1174f77
EC
4606 }
4607 break;
4608 case BPF_SUB:
979d63d5
DB
4609 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4610 if (ret < 0) {
4611 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
4612 return ret;
4613 }
f1174f77
EC
4614 if (dst_reg == off_reg) {
4615 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
4616 verbose(env, "R%d tried to subtract pointer from scalar\n",
4617 dst);
f1174f77
EC
4618 return -EACCES;
4619 }
4620 /* We don't allow subtraction from FP, because (according to
4621 * test_verifier.c test "invalid fp arithmetic", JITs might not
4622 * be able to deal with it.
969bf05e 4623 */
f1174f77 4624 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
4625 verbose(env, "R%d subtraction from stack pointer prohibited\n",
4626 dst);
f1174f77
EC
4627 return -EACCES;
4628 }
b03c9f9f
EC
4629 if (known && (ptr_reg->off - smin_val ==
4630 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 4631 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
4632 dst_reg->smin_value = smin_ptr;
4633 dst_reg->smax_value = smax_ptr;
4634 dst_reg->umin_value = umin_ptr;
4635 dst_reg->umax_value = umax_ptr;
f1174f77
EC
4636 dst_reg->var_off = ptr_reg->var_off;
4637 dst_reg->id = ptr_reg->id;
b03c9f9f 4638 dst_reg->off = ptr_reg->off - smin_val;
0962590e 4639 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
4640 break;
4641 }
f1174f77
EC
4642 /* A new variable offset is created. If the subtrahend is known
4643 * nonnegative, then any reg->range we had before is still good.
969bf05e 4644 */
b03c9f9f
EC
4645 if (signed_sub_overflows(smin_ptr, smax_val) ||
4646 signed_sub_overflows(smax_ptr, smin_val)) {
4647 /* Overflow possible, we know nothing */
4648 dst_reg->smin_value = S64_MIN;
4649 dst_reg->smax_value = S64_MAX;
4650 } else {
4651 dst_reg->smin_value = smin_ptr - smax_val;
4652 dst_reg->smax_value = smax_ptr - smin_val;
4653 }
4654 if (umin_ptr < umax_val) {
4655 /* Overflow possible, we know nothing */
4656 dst_reg->umin_value = 0;
4657 dst_reg->umax_value = U64_MAX;
4658 } else {
4659 /* Cannot overflow (as long as bounds are consistent) */
4660 dst_reg->umin_value = umin_ptr - umax_val;
4661 dst_reg->umax_value = umax_ptr - umin_val;
4662 }
f1174f77
EC
4663 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
4664 dst_reg->off = ptr_reg->off;
0962590e 4665 dst_reg->raw = ptr_reg->raw;
de8f3a83 4666 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
4667 dst_reg->id = ++env->id_gen;
4668 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 4669 if (smin_val < 0)
0962590e 4670 dst_reg->raw = 0;
43188702 4671 }
f1174f77
EC
4672 break;
4673 case BPF_AND:
4674 case BPF_OR:
4675 case BPF_XOR:
82abbf8d
AS
4676 /* bitwise ops on pointers are troublesome, prohibit. */
4677 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
4678 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
4679 return -EACCES;
4680 default:
4681 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
4682 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
4683 dst, bpf_alu_string[opcode >> 4]);
f1174f77 4684 return -EACCES;
43188702
JF
4685 }
4686
bb7f0f98
AS
4687 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
4688 return -EINVAL;
4689
b03c9f9f
EC
4690 __update_reg_bounds(dst_reg);
4691 __reg_deduce_bounds(dst_reg);
4692 __reg_bound_offset(dst_reg);
0d6303db
DB
4693
4694 /* For unprivileged we require that resulting offset must be in bounds
4695 * in order to be able to sanitize access later on.
4696 */
e4298d25
DB
4697 if (!env->allow_ptr_leaks) {
4698 if (dst_reg->type == PTR_TO_MAP_VALUE &&
4699 check_map_access(env, dst, dst_reg->off, 1, false)) {
4700 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
4701 "prohibited for !root\n", dst);
4702 return -EACCES;
4703 } else if (dst_reg->type == PTR_TO_STACK &&
4704 check_stack_access(env, dst_reg, dst_reg->off +
4705 dst_reg->var_off.value, 1)) {
4706 verbose(env, "R%d stack pointer arithmetic goes out of range, "
4707 "prohibited for !root\n", dst);
4708 return -EACCES;
4709 }
0d6303db
DB
4710 }
4711
43188702
JF
4712 return 0;
4713}
4714
468f6eaf
JH
4715/* WARNING: This function does calculations on 64-bit values, but the actual
4716 * execution may occur on 32-bit values. Therefore, things like bitshifts
4717 * need extra checks in the 32-bit case.
4718 */
f1174f77
EC
4719static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
4720 struct bpf_insn *insn,
4721 struct bpf_reg_state *dst_reg,
4722 struct bpf_reg_state src_reg)
969bf05e 4723{
638f5b90 4724 struct bpf_reg_state *regs = cur_regs(env);
48461135 4725 u8 opcode = BPF_OP(insn->code);
f1174f77 4726 bool src_known, dst_known;
b03c9f9f
EC
4727 s64 smin_val, smax_val;
4728 u64 umin_val, umax_val;
468f6eaf 4729 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
d3bd7413
DB
4730 u32 dst = insn->dst_reg;
4731 int ret;
48461135 4732
b799207e
JH
4733 if (insn_bitness == 32) {
4734 /* Relevant for 32-bit RSH: Information can propagate towards
4735 * LSB, so it isn't sufficient to only truncate the output to
4736 * 32 bits.
4737 */
4738 coerce_reg_to_size(dst_reg, 4);
4739 coerce_reg_to_size(&src_reg, 4);
4740 }
4741
b03c9f9f
EC
4742 smin_val = src_reg.smin_value;
4743 smax_val = src_reg.smax_value;
4744 umin_val = src_reg.umin_value;
4745 umax_val = src_reg.umax_value;
f1174f77
EC
4746 src_known = tnum_is_const(src_reg.var_off);
4747 dst_known = tnum_is_const(dst_reg->var_off);
f23cc643 4748
6f16101e
DB
4749 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
4750 smin_val > smax_val || umin_val > umax_val) {
4751 /* Taint dst register if offset had invalid bounds derived from
4752 * e.g. dead branches.
4753 */
4754 __mark_reg_unknown(dst_reg);
4755 return 0;
4756 }
4757
bb7f0f98
AS
4758 if (!src_known &&
4759 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
4760 __mark_reg_unknown(dst_reg);
4761 return 0;
4762 }
4763
48461135
JB
4764 switch (opcode) {
4765 case BPF_ADD:
d3bd7413
DB
4766 ret = sanitize_val_alu(env, insn);
4767 if (ret < 0) {
4768 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
4769 return ret;
4770 }
b03c9f9f
EC
4771 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
4772 signed_add_overflows(dst_reg->smax_value, smax_val)) {
4773 dst_reg->smin_value = S64_MIN;
4774 dst_reg->smax_value = S64_MAX;
4775 } else {
4776 dst_reg->smin_value += smin_val;
4777 dst_reg->smax_value += smax_val;
4778 }
4779 if (dst_reg->umin_value + umin_val < umin_val ||
4780 dst_reg->umax_value + umax_val < umax_val) {
4781 dst_reg->umin_value = 0;
4782 dst_reg->umax_value = U64_MAX;
4783 } else {
4784 dst_reg->umin_value += umin_val;
4785 dst_reg->umax_value += umax_val;
4786 }
f1174f77 4787 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
4788 break;
4789 case BPF_SUB:
d3bd7413
DB
4790 ret = sanitize_val_alu(env, insn);
4791 if (ret < 0) {
4792 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
4793 return ret;
4794 }
b03c9f9f
EC
4795 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
4796 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
4797 /* Overflow possible, we know nothing */
4798 dst_reg->smin_value = S64_MIN;
4799 dst_reg->smax_value = S64_MAX;
4800 } else {
4801 dst_reg->smin_value -= smax_val;
4802 dst_reg->smax_value -= smin_val;
4803 }
4804 if (dst_reg->umin_value < umax_val) {
4805 /* Overflow possible, we know nothing */
4806 dst_reg->umin_value = 0;
4807 dst_reg->umax_value = U64_MAX;
4808 } else {
4809 /* Cannot overflow (as long as bounds are consistent) */
4810 dst_reg->umin_value -= umax_val;
4811 dst_reg->umax_value -= umin_val;
4812 }
f1174f77 4813 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
4814 break;
4815 case BPF_MUL:
b03c9f9f
EC
4816 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
4817 if (smin_val < 0 || dst_reg->smin_value < 0) {
f1174f77 4818 /* Ain't nobody got time to multiply that sign */
b03c9f9f
EC
4819 __mark_reg_unbounded(dst_reg);
4820 __update_reg_bounds(dst_reg);
f1174f77
EC
4821 break;
4822 }
b03c9f9f
EC
4823 /* Both values are positive, so we can work with unsigned and
4824 * copy the result to signed (unless it exceeds S64_MAX).
f1174f77 4825 */
b03c9f9f
EC
4826 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
4827 /* Potential overflow, we know nothing */
4828 __mark_reg_unbounded(dst_reg);
4829 /* (except what we can learn from the var_off) */
4830 __update_reg_bounds(dst_reg);
4831 break;
4832 }
4833 dst_reg->umin_value *= umin_val;
4834 dst_reg->umax_value *= umax_val;
4835 if (dst_reg->umax_value > S64_MAX) {
4836 /* Overflow possible, we know nothing */
4837 dst_reg->smin_value = S64_MIN;
4838 dst_reg->smax_value = S64_MAX;
4839 } else {
4840 dst_reg->smin_value = dst_reg->umin_value;
4841 dst_reg->smax_value = dst_reg->umax_value;
4842 }
48461135
JB
4843 break;
4844 case BPF_AND:
f1174f77 4845 if (src_known && dst_known) {
b03c9f9f
EC
4846 __mark_reg_known(dst_reg, dst_reg->var_off.value &
4847 src_reg.var_off.value);
f1174f77
EC
4848 break;
4849 }
b03c9f9f
EC
4850 /* We get our minimum from the var_off, since that's inherently
4851 * bitwise. Our maximum is the minimum of the operands' maxima.
f23cc643 4852 */
f1174f77 4853 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
4854 dst_reg->umin_value = dst_reg->var_off.value;
4855 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
4856 if (dst_reg->smin_value < 0 || smin_val < 0) {
4857 /* Lose signed bounds when ANDing negative numbers,
4858 * ain't nobody got time for that.
4859 */
4860 dst_reg->smin_value = S64_MIN;
4861 dst_reg->smax_value = S64_MAX;
4862 } else {
4863 /* ANDing two positives gives a positive, so safe to
4864 * cast result into s64.
4865 */
4866 dst_reg->smin_value = dst_reg->umin_value;
4867 dst_reg->smax_value = dst_reg->umax_value;
4868 }
4869 /* We may learn something more from the var_off */
4870 __update_reg_bounds(dst_reg);
f1174f77
EC
4871 break;
4872 case BPF_OR:
4873 if (src_known && dst_known) {
b03c9f9f
EC
4874 __mark_reg_known(dst_reg, dst_reg->var_off.value |
4875 src_reg.var_off.value);
f1174f77
EC
4876 break;
4877 }
b03c9f9f
EC
4878 /* We get our maximum from the var_off, and our minimum is the
4879 * maximum of the operands' minima
f1174f77
EC
4880 */
4881 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
b03c9f9f
EC
4882 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4883 dst_reg->umax_value = dst_reg->var_off.value |
4884 dst_reg->var_off.mask;
4885 if (dst_reg->smin_value < 0 || smin_val < 0) {
4886 /* Lose signed bounds when ORing negative numbers,
4887 * ain't nobody got time for that.
4888 */
4889 dst_reg->smin_value = S64_MIN;
4890 dst_reg->smax_value = S64_MAX;
f1174f77 4891 } else {
b03c9f9f
EC
4892 /* ORing two positives gives a positive, so safe to
4893 * cast result into s64.
4894 */
4895 dst_reg->smin_value = dst_reg->umin_value;
4896 dst_reg->smax_value = dst_reg->umax_value;
f1174f77 4897 }
b03c9f9f
EC
4898 /* We may learn something more from the var_off */
4899 __update_reg_bounds(dst_reg);
48461135
JB
4900 break;
4901 case BPF_LSH:
468f6eaf
JH
4902 if (umax_val >= insn_bitness) {
4903 /* Shifts greater than 31 or 63 are undefined.
4904 * This includes shifts by a negative number.
b03c9f9f 4905 */
61bd5218 4906 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
4907 break;
4908 }
b03c9f9f
EC
4909 /* We lose all sign bit information (except what we can pick
4910 * up from var_off)
48461135 4911 */
b03c9f9f
EC
4912 dst_reg->smin_value = S64_MIN;
4913 dst_reg->smax_value = S64_MAX;
4914 /* If we might shift our top bit out, then we know nothing */
4915 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
4916 dst_reg->umin_value = 0;
4917 dst_reg->umax_value = U64_MAX;
d1174416 4918 } else {
b03c9f9f
EC
4919 dst_reg->umin_value <<= umin_val;
4920 dst_reg->umax_value <<= umax_val;
d1174416 4921 }
afbe1a5b 4922 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
b03c9f9f
EC
4923 /* We may learn something more from the var_off */
4924 __update_reg_bounds(dst_reg);
48461135
JB
4925 break;
4926 case BPF_RSH:
468f6eaf
JH
4927 if (umax_val >= insn_bitness) {
4928 /* Shifts greater than 31 or 63 are undefined.
4929 * This includes shifts by a negative number.
b03c9f9f 4930 */
61bd5218 4931 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
4932 break;
4933 }
4374f256
EC
4934 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
4935 * be negative, then either:
4936 * 1) src_reg might be zero, so the sign bit of the result is
4937 * unknown, so we lose our signed bounds
4938 * 2) it's known negative, thus the unsigned bounds capture the
4939 * signed bounds
4940 * 3) the signed bounds cross zero, so they tell us nothing
4941 * about the result
4942 * If the value in dst_reg is known nonnegative, then again the
4943 * unsigned bounts capture the signed bounds.
4944 * Thus, in all cases it suffices to blow away our signed bounds
4945 * and rely on inferring new ones from the unsigned bounds and
4946 * var_off of the result.
4947 */
4948 dst_reg->smin_value = S64_MIN;
4949 dst_reg->smax_value = S64_MAX;
afbe1a5b 4950 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
b03c9f9f
EC
4951 dst_reg->umin_value >>= umax_val;
4952 dst_reg->umax_value >>= umin_val;
4953 /* We may learn something more from the var_off */
4954 __update_reg_bounds(dst_reg);
48461135 4955 break;
9cbe1f5a
YS
4956 case BPF_ARSH:
4957 if (umax_val >= insn_bitness) {
4958 /* Shifts greater than 31 or 63 are undefined.
4959 * This includes shifts by a negative number.
4960 */
4961 mark_reg_unknown(env, regs, insn->dst_reg);
4962 break;
4963 }
4964
4965 /* Upon reaching here, src_known is true and
4966 * umax_val is equal to umin_val.
4967 */
4968 dst_reg->smin_value >>= umin_val;
4969 dst_reg->smax_value >>= umin_val;
4970 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
4971
4972 /* blow away the dst_reg umin_value/umax_value and rely on
4973 * dst_reg var_off to refine the result.
4974 */
4975 dst_reg->umin_value = 0;
4976 dst_reg->umax_value = U64_MAX;
4977 __update_reg_bounds(dst_reg);
4978 break;
48461135 4979 default:
61bd5218 4980 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
4981 break;
4982 }
4983
468f6eaf
JH
4984 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4985 /* 32-bit ALU ops are (32,32)->32 */
4986 coerce_reg_to_size(dst_reg, 4);
468f6eaf
JH
4987 }
4988
b03c9f9f
EC
4989 __reg_deduce_bounds(dst_reg);
4990 __reg_bound_offset(dst_reg);
f1174f77
EC
4991 return 0;
4992}
4993
4994/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
4995 * and var_off.
4996 */
4997static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
4998 struct bpf_insn *insn)
4999{
f4d7e40a
AS
5000 struct bpf_verifier_state *vstate = env->cur_state;
5001 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5002 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
5003 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5004 u8 opcode = BPF_OP(insn->code);
b5dc0163 5005 int err;
f1174f77
EC
5006
5007 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
5008 src_reg = NULL;
5009 if (dst_reg->type != SCALAR_VALUE)
5010 ptr_reg = dst_reg;
5011 if (BPF_SRC(insn->code) == BPF_X) {
5012 src_reg = &regs[insn->src_reg];
f1174f77
EC
5013 if (src_reg->type != SCALAR_VALUE) {
5014 if (dst_reg->type != SCALAR_VALUE) {
5015 /* Combining two pointers by any ALU op yields
82abbf8d
AS
5016 * an arbitrary scalar. Disallow all math except
5017 * pointer subtraction
f1174f77 5018 */
dd066823 5019 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
5020 mark_reg_unknown(env, regs, insn->dst_reg);
5021 return 0;
f1174f77 5022 }
82abbf8d
AS
5023 verbose(env, "R%d pointer %s pointer prohibited\n",
5024 insn->dst_reg,
5025 bpf_alu_string[opcode >> 4]);
5026 return -EACCES;
f1174f77
EC
5027 } else {
5028 /* scalar += pointer
5029 * This is legal, but we have to reverse our
5030 * src/dest handling in computing the range
5031 */
b5dc0163
AS
5032 err = mark_chain_precision(env, insn->dst_reg);
5033 if (err)
5034 return err;
82abbf8d
AS
5035 return adjust_ptr_min_max_vals(env, insn,
5036 src_reg, dst_reg);
f1174f77
EC
5037 }
5038 } else if (ptr_reg) {
5039 /* pointer += scalar */
b5dc0163
AS
5040 err = mark_chain_precision(env, insn->src_reg);
5041 if (err)
5042 return err;
82abbf8d
AS
5043 return adjust_ptr_min_max_vals(env, insn,
5044 dst_reg, src_reg);
f1174f77
EC
5045 }
5046 } else {
5047 /* Pretend the src is a reg with a known value, since we only
5048 * need to be able to read from this state.
5049 */
5050 off_reg.type = SCALAR_VALUE;
b03c9f9f 5051 __mark_reg_known(&off_reg, insn->imm);
f1174f77 5052 src_reg = &off_reg;
82abbf8d
AS
5053 if (ptr_reg) /* pointer += K */
5054 return adjust_ptr_min_max_vals(env, insn,
5055 ptr_reg, src_reg);
f1174f77
EC
5056 }
5057
5058 /* Got here implies adding two SCALAR_VALUEs */
5059 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 5060 print_verifier_state(env, state);
61bd5218 5061 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
5062 return -EINVAL;
5063 }
5064 if (WARN_ON(!src_reg)) {
f4d7e40a 5065 print_verifier_state(env, state);
61bd5218 5066 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
5067 return -EINVAL;
5068 }
5069 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
5070}
5071
17a52670 5072/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 5073static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 5074{
638f5b90 5075 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
5076 u8 opcode = BPF_OP(insn->code);
5077 int err;
5078
5079 if (opcode == BPF_END || opcode == BPF_NEG) {
5080 if (opcode == BPF_NEG) {
5081 if (BPF_SRC(insn->code) != 0 ||
5082 insn->src_reg != BPF_REG_0 ||
5083 insn->off != 0 || insn->imm != 0) {
61bd5218 5084 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
5085 return -EINVAL;
5086 }
5087 } else {
5088 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
5089 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
5090 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 5091 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
5092 return -EINVAL;
5093 }
5094 }
5095
5096 /* check src operand */
dc503a8a 5097 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
5098 if (err)
5099 return err;
5100
1be7f75d 5101 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 5102 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
5103 insn->dst_reg);
5104 return -EACCES;
5105 }
5106
17a52670 5107 /* check dest operand */
dc503a8a 5108 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
5109 if (err)
5110 return err;
5111
5112 } else if (opcode == BPF_MOV) {
5113
5114 if (BPF_SRC(insn->code) == BPF_X) {
5115 if (insn->imm != 0 || insn->off != 0) {
61bd5218 5116 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
5117 return -EINVAL;
5118 }
5119
5120 /* check src operand */
dc503a8a 5121 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
5122 if (err)
5123 return err;
5124 } else {
5125 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 5126 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
5127 return -EINVAL;
5128 }
5129 }
5130
fbeb1603
AF
5131 /* check dest operand, mark as required later */
5132 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
5133 if (err)
5134 return err;
5135
5136 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
5137 struct bpf_reg_state *src_reg = regs + insn->src_reg;
5138 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
5139
17a52670
AS
5140 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5141 /* case: R1 = R2
5142 * copy register state to dest reg
5143 */
e434b8cd
JW
5144 *dst_reg = *src_reg;
5145 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 5146 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 5147 } else {
f1174f77 5148 /* R1 = (u32) R2 */
1be7f75d 5149 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
5150 verbose(env,
5151 "R%d partial copy of pointer\n",
1be7f75d
AS
5152 insn->src_reg);
5153 return -EACCES;
e434b8cd
JW
5154 } else if (src_reg->type == SCALAR_VALUE) {
5155 *dst_reg = *src_reg;
5156 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 5157 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
5158 } else {
5159 mark_reg_unknown(env, regs,
5160 insn->dst_reg);
1be7f75d 5161 }
e434b8cd 5162 coerce_reg_to_size(dst_reg, 4);
17a52670
AS
5163 }
5164 } else {
5165 /* case: R = imm
5166 * remember the value we stored into this reg
5167 */
fbeb1603
AF
5168 /* clear any state __mark_reg_known doesn't set */
5169 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 5170 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
5171 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5172 __mark_reg_known(regs + insn->dst_reg,
5173 insn->imm);
5174 } else {
5175 __mark_reg_known(regs + insn->dst_reg,
5176 (u32)insn->imm);
5177 }
17a52670
AS
5178 }
5179
5180 } else if (opcode > BPF_END) {
61bd5218 5181 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
5182 return -EINVAL;
5183
5184 } else { /* all other ALU ops: and, sub, xor, add, ... */
5185
17a52670
AS
5186 if (BPF_SRC(insn->code) == BPF_X) {
5187 if (insn->imm != 0 || insn->off != 0) {
61bd5218 5188 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
5189 return -EINVAL;
5190 }
5191 /* check src1 operand */
dc503a8a 5192 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
5193 if (err)
5194 return err;
5195 } else {
5196 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 5197 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
5198 return -EINVAL;
5199 }
5200 }
5201
5202 /* check src2 operand */
dc503a8a 5203 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
5204 if (err)
5205 return err;
5206
5207 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
5208 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 5209 verbose(env, "div by zero\n");
17a52670
AS
5210 return -EINVAL;
5211 }
5212
229394e8
RV
5213 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
5214 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
5215 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
5216
5217 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 5218 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
5219 return -EINVAL;
5220 }
5221 }
5222
1a0dc1ac 5223 /* check dest operand */
dc503a8a 5224 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
5225 if (err)
5226 return err;
5227
f1174f77 5228 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
5229 }
5230
5231 return 0;
5232}
5233
c6a9efa1
PC
5234static void __find_good_pkt_pointers(struct bpf_func_state *state,
5235 struct bpf_reg_state *dst_reg,
5236 enum bpf_reg_type type, u16 new_range)
5237{
5238 struct bpf_reg_state *reg;
5239 int i;
5240
5241 for (i = 0; i < MAX_BPF_REG; i++) {
5242 reg = &state->regs[i];
5243 if (reg->type == type && reg->id == dst_reg->id)
5244 /* keep the maximum range already checked */
5245 reg->range = max(reg->range, new_range);
5246 }
5247
5248 bpf_for_each_spilled_reg(i, state, reg) {
5249 if (!reg)
5250 continue;
5251 if (reg->type == type && reg->id == dst_reg->id)
5252 reg->range = max(reg->range, new_range);
5253 }
5254}
5255
f4d7e40a 5256static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 5257 struct bpf_reg_state *dst_reg,
f8ddadc4 5258 enum bpf_reg_type type,
fb2a311a 5259 bool range_right_open)
969bf05e 5260{
fb2a311a 5261 u16 new_range;
c6a9efa1 5262 int i;
2d2be8ca 5263
fb2a311a
DB
5264 if (dst_reg->off < 0 ||
5265 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
5266 /* This doesn't give us any range */
5267 return;
5268
b03c9f9f
EC
5269 if (dst_reg->umax_value > MAX_PACKET_OFF ||
5270 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
5271 /* Risk of overflow. For instance, ptr + (1<<63) may be less
5272 * than pkt_end, but that's because it's also less than pkt.
5273 */
5274 return;
5275
fb2a311a
DB
5276 new_range = dst_reg->off;
5277 if (range_right_open)
5278 new_range--;
5279
5280 /* Examples for register markings:
2d2be8ca 5281 *
fb2a311a 5282 * pkt_data in dst register:
2d2be8ca
DB
5283 *
5284 * r2 = r3;
5285 * r2 += 8;
5286 * if (r2 > pkt_end) goto <handle exception>
5287 * <access okay>
5288 *
b4e432f1
DB
5289 * r2 = r3;
5290 * r2 += 8;
5291 * if (r2 < pkt_end) goto <access okay>
5292 * <handle exception>
5293 *
2d2be8ca
DB
5294 * Where:
5295 * r2 == dst_reg, pkt_end == src_reg
5296 * r2=pkt(id=n,off=8,r=0)
5297 * r3=pkt(id=n,off=0,r=0)
5298 *
fb2a311a 5299 * pkt_data in src register:
2d2be8ca
DB
5300 *
5301 * r2 = r3;
5302 * r2 += 8;
5303 * if (pkt_end >= r2) goto <access okay>
5304 * <handle exception>
5305 *
b4e432f1
DB
5306 * r2 = r3;
5307 * r2 += 8;
5308 * if (pkt_end <= r2) goto <handle exception>
5309 * <access okay>
5310 *
2d2be8ca
DB
5311 * Where:
5312 * pkt_end == dst_reg, r2 == src_reg
5313 * r2=pkt(id=n,off=8,r=0)
5314 * r3=pkt(id=n,off=0,r=0)
5315 *
5316 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
5317 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
5318 * and [r3, r3 + 8-1) respectively is safe to access depending on
5319 * the check.
969bf05e 5320 */
2d2be8ca 5321
f1174f77
EC
5322 /* If our ids match, then we must have the same max_value. And we
5323 * don't care about the other reg's fixed offset, since if it's too big
5324 * the range won't allow anything.
5325 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
5326 */
c6a9efa1
PC
5327 for (i = 0; i <= vstate->curframe; i++)
5328 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
5329 new_range);
969bf05e
AS
5330}
5331
4f7b3e82
AS
5332/* compute branch direction of the expression "if (reg opcode val) goto target;"
5333 * and return:
5334 * 1 - branch will be taken and "goto target" will be executed
5335 * 0 - branch will not be taken and fall-through to next insn
5336 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
5337 */
092ed096
JW
5338static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
5339 bool is_jmp32)
4f7b3e82 5340{
092ed096 5341 struct bpf_reg_state reg_lo;
a72dafaf
JW
5342 s64 sval;
5343
4f7b3e82
AS
5344 if (__is_pointer_value(false, reg))
5345 return -1;
5346
092ed096
JW
5347 if (is_jmp32) {
5348 reg_lo = *reg;
5349 reg = &reg_lo;
5350 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
5351 * could truncate high bits and update umin/umax according to
5352 * information of low bits.
5353 */
5354 coerce_reg_to_size(reg, 4);
5355 /* smin/smax need special handling. For example, after coerce,
5356 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
5357 * used as operand to JMP32. It is a negative number from s32's
5358 * point of view, while it is a positive number when seen as
5359 * s64. The smin/smax are kept as s64, therefore, when used with
5360 * JMP32, they need to be transformed into s32, then sign
5361 * extended back to s64.
5362 *
5363 * Also, smin/smax were copied from umin/umax. If umin/umax has
5364 * different sign bit, then min/max relationship doesn't
5365 * maintain after casting into s32, for this case, set smin/smax
5366 * to safest range.
5367 */
5368 if ((reg->umax_value ^ reg->umin_value) &
5369 (1ULL << 31)) {
5370 reg->smin_value = S32_MIN;
5371 reg->smax_value = S32_MAX;
5372 }
5373 reg->smin_value = (s64)(s32)reg->smin_value;
5374 reg->smax_value = (s64)(s32)reg->smax_value;
5375
5376 val = (u32)val;
5377 sval = (s64)(s32)val;
5378 } else {
5379 sval = (s64)val;
5380 }
a72dafaf 5381
4f7b3e82
AS
5382 switch (opcode) {
5383 case BPF_JEQ:
5384 if (tnum_is_const(reg->var_off))
5385 return !!tnum_equals_const(reg->var_off, val);
5386 break;
5387 case BPF_JNE:
5388 if (tnum_is_const(reg->var_off))
5389 return !tnum_equals_const(reg->var_off, val);
5390 break;
960ea056
JK
5391 case BPF_JSET:
5392 if ((~reg->var_off.mask & reg->var_off.value) & val)
5393 return 1;
5394 if (!((reg->var_off.mask | reg->var_off.value) & val))
5395 return 0;
5396 break;
4f7b3e82
AS
5397 case BPF_JGT:
5398 if (reg->umin_value > val)
5399 return 1;
5400 else if (reg->umax_value <= val)
5401 return 0;
5402 break;
5403 case BPF_JSGT:
a72dafaf 5404 if (reg->smin_value > sval)
4f7b3e82 5405 return 1;
a72dafaf 5406 else if (reg->smax_value < sval)
4f7b3e82
AS
5407 return 0;
5408 break;
5409 case BPF_JLT:
5410 if (reg->umax_value < val)
5411 return 1;
5412 else if (reg->umin_value >= val)
5413 return 0;
5414 break;
5415 case BPF_JSLT:
a72dafaf 5416 if (reg->smax_value < sval)
4f7b3e82 5417 return 1;
a72dafaf 5418 else if (reg->smin_value >= sval)
4f7b3e82
AS
5419 return 0;
5420 break;
5421 case BPF_JGE:
5422 if (reg->umin_value >= val)
5423 return 1;
5424 else if (reg->umax_value < val)
5425 return 0;
5426 break;
5427 case BPF_JSGE:
a72dafaf 5428 if (reg->smin_value >= sval)
4f7b3e82 5429 return 1;
a72dafaf 5430 else if (reg->smax_value < sval)
4f7b3e82
AS
5431 return 0;
5432 break;
5433 case BPF_JLE:
5434 if (reg->umax_value <= val)
5435 return 1;
5436 else if (reg->umin_value > val)
5437 return 0;
5438 break;
5439 case BPF_JSLE:
a72dafaf 5440 if (reg->smax_value <= sval)
4f7b3e82 5441 return 1;
a72dafaf 5442 else if (reg->smin_value > sval)
4f7b3e82
AS
5443 return 0;
5444 break;
5445 }
5446
5447 return -1;
5448}
5449
092ed096
JW
5450/* Generate min value of the high 32-bit from TNUM info. */
5451static u64 gen_hi_min(struct tnum var)
5452{
5453 return var.value & ~0xffffffffULL;
5454}
5455
5456/* Generate max value of the high 32-bit from TNUM info. */
5457static u64 gen_hi_max(struct tnum var)
5458{
5459 return (var.value | var.mask) & ~0xffffffffULL;
5460}
5461
5462/* Return true if VAL is compared with a s64 sign extended from s32, and they
5463 * are with the same signedness.
5464 */
5465static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
5466{
5467 return ((s32)sval >= 0 &&
5468 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
5469 ((s32)sval < 0 &&
5470 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
5471}
5472
48461135
JB
5473/* Adjusts the register min/max values in the case that the dst_reg is the
5474 * variable register that we are working on, and src_reg is a constant or we're
5475 * simply doing a BPF_K check.
f1174f77 5476 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
5477 */
5478static void reg_set_min_max(struct bpf_reg_state *true_reg,
5479 struct bpf_reg_state *false_reg, u64 val,
092ed096 5480 u8 opcode, bool is_jmp32)
48461135 5481{
a72dafaf
JW
5482 s64 sval;
5483
f1174f77
EC
5484 /* If the dst_reg is a pointer, we can't learn anything about its
5485 * variable offset from the compare (unless src_reg were a pointer into
5486 * the same object, but we don't bother with that.
5487 * Since false_reg and true_reg have the same type by construction, we
5488 * only need to check one of them for pointerness.
5489 */
5490 if (__is_pointer_value(false, false_reg))
5491 return;
4cabc5b1 5492
092ed096
JW
5493 val = is_jmp32 ? (u32)val : val;
5494 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
a72dafaf 5495
48461135
JB
5496 switch (opcode) {
5497 case BPF_JEQ:
48461135 5498 case BPF_JNE:
a72dafaf
JW
5499 {
5500 struct bpf_reg_state *reg =
5501 opcode == BPF_JEQ ? true_reg : false_reg;
5502
5503 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
5504 * if it is true we know the value for sure. Likewise for
5505 * BPF_JNE.
48461135 5506 */
092ed096
JW
5507 if (is_jmp32) {
5508 u64 old_v = reg->var_off.value;
5509 u64 hi_mask = ~0xffffffffULL;
5510
5511 reg->var_off.value = (old_v & hi_mask) | val;
5512 reg->var_off.mask &= hi_mask;
5513 } else {
5514 __mark_reg_known(reg, val);
5515 }
48461135 5516 break;
a72dafaf 5517 }
960ea056
JK
5518 case BPF_JSET:
5519 false_reg->var_off = tnum_and(false_reg->var_off,
5520 tnum_const(~val));
5521 if (is_power_of_2(val))
5522 true_reg->var_off = tnum_or(true_reg->var_off,
5523 tnum_const(val));
5524 break;
48461135 5525 case BPF_JGE:
a72dafaf
JW
5526 case BPF_JGT:
5527 {
5528 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
5529 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
5530
092ed096
JW
5531 if (is_jmp32) {
5532 false_umax += gen_hi_max(false_reg->var_off);
5533 true_umin += gen_hi_min(true_reg->var_off);
5534 }
a72dafaf
JW
5535 false_reg->umax_value = min(false_reg->umax_value, false_umax);
5536 true_reg->umin_value = max(true_reg->umin_value, true_umin);
b03c9f9f 5537 break;
a72dafaf 5538 }
48461135 5539 case BPF_JSGE:
a72dafaf
JW
5540 case BPF_JSGT:
5541 {
5542 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
5543 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
5544
092ed096
JW
5545 /* If the full s64 was not sign-extended from s32 then don't
5546 * deduct further info.
5547 */
5548 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5549 break;
a72dafaf
JW
5550 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5551 true_reg->smin_value = max(true_reg->smin_value, true_smin);
48461135 5552 break;
a72dafaf 5553 }
b4e432f1 5554 case BPF_JLE:
a72dafaf
JW
5555 case BPF_JLT:
5556 {
5557 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
5558 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
5559
092ed096
JW
5560 if (is_jmp32) {
5561 false_umin += gen_hi_min(false_reg->var_off);
5562 true_umax += gen_hi_max(true_reg->var_off);
5563 }
a72dafaf
JW
5564 false_reg->umin_value = max(false_reg->umin_value, false_umin);
5565 true_reg->umax_value = min(true_reg->umax_value, true_umax);
b4e432f1 5566 break;
a72dafaf 5567 }
b4e432f1 5568 case BPF_JSLE:
a72dafaf
JW
5569 case BPF_JSLT:
5570 {
5571 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
5572 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
5573
092ed096
JW
5574 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5575 break;
a72dafaf
JW
5576 false_reg->smin_value = max(false_reg->smin_value, false_smin);
5577 true_reg->smax_value = min(true_reg->smax_value, true_smax);
b4e432f1 5578 break;
a72dafaf 5579 }
48461135
JB
5580 default:
5581 break;
5582 }
5583
b03c9f9f
EC
5584 __reg_deduce_bounds(false_reg);
5585 __reg_deduce_bounds(true_reg);
5586 /* We might have learned some bits from the bounds. */
5587 __reg_bound_offset(false_reg);
5588 __reg_bound_offset(true_reg);
5589 /* Intersecting with the old var_off might have improved our bounds
5590 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5591 * then new var_off is (0; 0x7f...fc) which improves our umax.
5592 */
5593 __update_reg_bounds(false_reg);
5594 __update_reg_bounds(true_reg);
48461135
JB
5595}
5596
f1174f77
EC
5597/* Same as above, but for the case that dst_reg holds a constant and src_reg is
5598 * the variable reg.
48461135
JB
5599 */
5600static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
5601 struct bpf_reg_state *false_reg, u64 val,
092ed096 5602 u8 opcode, bool is_jmp32)
48461135 5603{
a72dafaf
JW
5604 s64 sval;
5605
f1174f77
EC
5606 if (__is_pointer_value(false, false_reg))
5607 return;
4cabc5b1 5608
092ed096
JW
5609 val = is_jmp32 ? (u32)val : val;
5610 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
a72dafaf 5611
48461135
JB
5612 switch (opcode) {
5613 case BPF_JEQ:
48461135 5614 case BPF_JNE:
a72dafaf
JW
5615 {
5616 struct bpf_reg_state *reg =
5617 opcode == BPF_JEQ ? true_reg : false_reg;
5618
092ed096
JW
5619 if (is_jmp32) {
5620 u64 old_v = reg->var_off.value;
5621 u64 hi_mask = ~0xffffffffULL;
5622
5623 reg->var_off.value = (old_v & hi_mask) | val;
5624 reg->var_off.mask &= hi_mask;
5625 } else {
5626 __mark_reg_known(reg, val);
5627 }
48461135 5628 break;
a72dafaf 5629 }
960ea056
JK
5630 case BPF_JSET:
5631 false_reg->var_off = tnum_and(false_reg->var_off,
5632 tnum_const(~val));
5633 if (is_power_of_2(val))
5634 true_reg->var_off = tnum_or(true_reg->var_off,
5635 tnum_const(val));
5636 break;
48461135 5637 case BPF_JGE:
a72dafaf
JW
5638 case BPF_JGT:
5639 {
5640 u64 false_umin = opcode == BPF_JGT ? val : val + 1;
5641 u64 true_umax = opcode == BPF_JGT ? val - 1 : val;
5642
092ed096
JW
5643 if (is_jmp32) {
5644 false_umin += gen_hi_min(false_reg->var_off);
5645 true_umax += gen_hi_max(true_reg->var_off);
5646 }
a72dafaf
JW
5647 false_reg->umin_value = max(false_reg->umin_value, false_umin);
5648 true_reg->umax_value = min(true_reg->umax_value, true_umax);
b03c9f9f 5649 break;
a72dafaf 5650 }
48461135 5651 case BPF_JSGE:
a72dafaf
JW
5652 case BPF_JSGT:
5653 {
5654 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1;
5655 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
5656
092ed096
JW
5657 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5658 break;
a72dafaf
JW
5659 false_reg->smin_value = max(false_reg->smin_value, false_smin);
5660 true_reg->smax_value = min(true_reg->smax_value, true_smax);
48461135 5661 break;
a72dafaf 5662 }
b4e432f1 5663 case BPF_JLE:
a72dafaf
JW
5664 case BPF_JLT:
5665 {
5666 u64 false_umax = opcode == BPF_JLT ? val : val - 1;
5667 u64 true_umin = opcode == BPF_JLT ? val + 1 : val;
5668
092ed096
JW
5669 if (is_jmp32) {
5670 false_umax += gen_hi_max(false_reg->var_off);
5671 true_umin += gen_hi_min(true_reg->var_off);
5672 }
a72dafaf
JW
5673 false_reg->umax_value = min(false_reg->umax_value, false_umax);
5674 true_reg->umin_value = max(true_reg->umin_value, true_umin);
b4e432f1 5675 break;
a72dafaf 5676 }
b4e432f1 5677 case BPF_JSLE:
a72dafaf
JW
5678 case BPF_JSLT:
5679 {
5680 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1;
5681 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
5682
092ed096
JW
5683 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5684 break;
a72dafaf
JW
5685 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5686 true_reg->smin_value = max(true_reg->smin_value, true_smin);
b4e432f1 5687 break;
a72dafaf 5688 }
48461135
JB
5689 default:
5690 break;
5691 }
5692
b03c9f9f
EC
5693 __reg_deduce_bounds(false_reg);
5694 __reg_deduce_bounds(true_reg);
5695 /* We might have learned some bits from the bounds. */
5696 __reg_bound_offset(false_reg);
5697 __reg_bound_offset(true_reg);
5698 /* Intersecting with the old var_off might have improved our bounds
5699 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5700 * then new var_off is (0; 0x7f...fc) which improves our umax.
5701 */
5702 __update_reg_bounds(false_reg);
5703 __update_reg_bounds(true_reg);
f1174f77
EC
5704}
5705
5706/* Regs are known to be equal, so intersect their min/max/var_off */
5707static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
5708 struct bpf_reg_state *dst_reg)
5709{
b03c9f9f
EC
5710 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
5711 dst_reg->umin_value);
5712 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
5713 dst_reg->umax_value);
5714 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
5715 dst_reg->smin_value);
5716 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
5717 dst_reg->smax_value);
f1174f77
EC
5718 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
5719 dst_reg->var_off);
b03c9f9f
EC
5720 /* We might have learned new bounds from the var_off. */
5721 __update_reg_bounds(src_reg);
5722 __update_reg_bounds(dst_reg);
5723 /* We might have learned something about the sign bit. */
5724 __reg_deduce_bounds(src_reg);
5725 __reg_deduce_bounds(dst_reg);
5726 /* We might have learned some bits from the bounds. */
5727 __reg_bound_offset(src_reg);
5728 __reg_bound_offset(dst_reg);
5729 /* Intersecting with the old var_off might have improved our bounds
5730 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5731 * then new var_off is (0; 0x7f...fc) which improves our umax.
5732 */
5733 __update_reg_bounds(src_reg);
5734 __update_reg_bounds(dst_reg);
f1174f77
EC
5735}
5736
5737static void reg_combine_min_max(struct bpf_reg_state *true_src,
5738 struct bpf_reg_state *true_dst,
5739 struct bpf_reg_state *false_src,
5740 struct bpf_reg_state *false_dst,
5741 u8 opcode)
5742{
5743 switch (opcode) {
5744 case BPF_JEQ:
5745 __reg_combine_min_max(true_src, true_dst);
5746 break;
5747 case BPF_JNE:
5748 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 5749 break;
4cabc5b1 5750 }
48461135
JB
5751}
5752
fd978bf7
JS
5753static void mark_ptr_or_null_reg(struct bpf_func_state *state,
5754 struct bpf_reg_state *reg, u32 id,
840b9615 5755 bool is_null)
57a09bf0 5756{
840b9615 5757 if (reg_type_may_be_null(reg->type) && reg->id == id) {
f1174f77
EC
5758 /* Old offset (both fixed and variable parts) should
5759 * have been known-zero, because we don't allow pointer
5760 * arithmetic on pointers that might be NULL.
5761 */
b03c9f9f
EC
5762 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
5763 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 5764 reg->off)) {
b03c9f9f
EC
5765 __mark_reg_known_zero(reg);
5766 reg->off = 0;
f1174f77
EC
5767 }
5768 if (is_null) {
5769 reg->type = SCALAR_VALUE;
840b9615
JS
5770 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
5771 if (reg->map_ptr->inner_map_meta) {
5772 reg->type = CONST_PTR_TO_MAP;
5773 reg->map_ptr = reg->map_ptr->inner_map_meta;
fada7fdc
JL
5774 } else if (reg->map_ptr->map_type ==
5775 BPF_MAP_TYPE_XSKMAP) {
5776 reg->type = PTR_TO_XDP_SOCK;
840b9615
JS
5777 } else {
5778 reg->type = PTR_TO_MAP_VALUE;
5779 }
c64b7983
JS
5780 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
5781 reg->type = PTR_TO_SOCKET;
46f8bc92
MKL
5782 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
5783 reg->type = PTR_TO_SOCK_COMMON;
655a51e5
MKL
5784 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
5785 reg->type = PTR_TO_TCP_SOCK;
56f668df 5786 }
1b986589
MKL
5787 if (is_null) {
5788 /* We don't need id and ref_obj_id from this point
5789 * onwards anymore, thus we should better reset it,
5790 * so that state pruning has chances to take effect.
5791 */
5792 reg->id = 0;
5793 reg->ref_obj_id = 0;
5794 } else if (!reg_may_point_to_spin_lock(reg)) {
5795 /* For not-NULL ptr, reg->ref_obj_id will be reset
5796 * in release_reg_references().
5797 *
5798 * reg->id is still used by spin_lock ptr. Other
5799 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
5800 */
5801 reg->id = 0;
56f668df 5802 }
57a09bf0
TG
5803 }
5804}
5805
c6a9efa1
PC
5806static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
5807 bool is_null)
5808{
5809 struct bpf_reg_state *reg;
5810 int i;
5811
5812 for (i = 0; i < MAX_BPF_REG; i++)
5813 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
5814
5815 bpf_for_each_spilled_reg(i, state, reg) {
5816 if (!reg)
5817 continue;
5818 mark_ptr_or_null_reg(state, reg, id, is_null);
5819 }
5820}
5821
57a09bf0
TG
5822/* The logic is similar to find_good_pkt_pointers(), both could eventually
5823 * be folded together at some point.
5824 */
840b9615
JS
5825static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
5826 bool is_null)
57a09bf0 5827{
f4d7e40a 5828 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 5829 struct bpf_reg_state *regs = state->regs;
1b986589 5830 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 5831 u32 id = regs[regno].id;
c6a9efa1 5832 int i;
57a09bf0 5833
1b986589
MKL
5834 if (ref_obj_id && ref_obj_id == id && is_null)
5835 /* regs[regno] is in the " == NULL" branch.
5836 * No one could have freed the reference state before
5837 * doing the NULL check.
5838 */
5839 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 5840
c6a9efa1
PC
5841 for (i = 0; i <= vstate->curframe; i++)
5842 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
5843}
5844
5beca081
DB
5845static bool try_match_pkt_pointers(const struct bpf_insn *insn,
5846 struct bpf_reg_state *dst_reg,
5847 struct bpf_reg_state *src_reg,
5848 struct bpf_verifier_state *this_branch,
5849 struct bpf_verifier_state *other_branch)
5850{
5851 if (BPF_SRC(insn->code) != BPF_X)
5852 return false;
5853
092ed096
JW
5854 /* Pointers are always 64-bit. */
5855 if (BPF_CLASS(insn->code) == BPF_JMP32)
5856 return false;
5857
5beca081
DB
5858 switch (BPF_OP(insn->code)) {
5859 case BPF_JGT:
5860 if ((dst_reg->type == PTR_TO_PACKET &&
5861 src_reg->type == PTR_TO_PACKET_END) ||
5862 (dst_reg->type == PTR_TO_PACKET_META &&
5863 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5864 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
5865 find_good_pkt_pointers(this_branch, dst_reg,
5866 dst_reg->type, false);
5867 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5868 src_reg->type == PTR_TO_PACKET) ||
5869 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5870 src_reg->type == PTR_TO_PACKET_META)) {
5871 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
5872 find_good_pkt_pointers(other_branch, src_reg,
5873 src_reg->type, true);
5874 } else {
5875 return false;
5876 }
5877 break;
5878 case BPF_JLT:
5879 if ((dst_reg->type == PTR_TO_PACKET &&
5880 src_reg->type == PTR_TO_PACKET_END) ||
5881 (dst_reg->type == PTR_TO_PACKET_META &&
5882 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5883 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
5884 find_good_pkt_pointers(other_branch, dst_reg,
5885 dst_reg->type, true);
5886 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5887 src_reg->type == PTR_TO_PACKET) ||
5888 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5889 src_reg->type == PTR_TO_PACKET_META)) {
5890 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
5891 find_good_pkt_pointers(this_branch, src_reg,
5892 src_reg->type, false);
5893 } else {
5894 return false;
5895 }
5896 break;
5897 case BPF_JGE:
5898 if ((dst_reg->type == PTR_TO_PACKET &&
5899 src_reg->type == PTR_TO_PACKET_END) ||
5900 (dst_reg->type == PTR_TO_PACKET_META &&
5901 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5902 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
5903 find_good_pkt_pointers(this_branch, dst_reg,
5904 dst_reg->type, true);
5905 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5906 src_reg->type == PTR_TO_PACKET) ||
5907 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5908 src_reg->type == PTR_TO_PACKET_META)) {
5909 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
5910 find_good_pkt_pointers(other_branch, src_reg,
5911 src_reg->type, false);
5912 } else {
5913 return false;
5914 }
5915 break;
5916 case BPF_JLE:
5917 if ((dst_reg->type == PTR_TO_PACKET &&
5918 src_reg->type == PTR_TO_PACKET_END) ||
5919 (dst_reg->type == PTR_TO_PACKET_META &&
5920 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
5921 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
5922 find_good_pkt_pointers(other_branch, dst_reg,
5923 dst_reg->type, false);
5924 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
5925 src_reg->type == PTR_TO_PACKET) ||
5926 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
5927 src_reg->type == PTR_TO_PACKET_META)) {
5928 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
5929 find_good_pkt_pointers(this_branch, src_reg,
5930 src_reg->type, true);
5931 } else {
5932 return false;
5933 }
5934 break;
5935 default:
5936 return false;
5937 }
5938
5939 return true;
5940}
5941
58e2af8b 5942static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
5943 struct bpf_insn *insn, int *insn_idx)
5944{
f4d7e40a
AS
5945 struct bpf_verifier_state *this_branch = env->cur_state;
5946 struct bpf_verifier_state *other_branch;
5947 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 5948 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 5949 u8 opcode = BPF_OP(insn->code);
092ed096 5950 bool is_jmp32;
fb8d251e 5951 int pred = -1;
17a52670
AS
5952 int err;
5953
092ed096
JW
5954 /* Only conditional jumps are expected to reach here. */
5955 if (opcode == BPF_JA || opcode > BPF_JSLE) {
5956 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
5957 return -EINVAL;
5958 }
5959
5960 if (BPF_SRC(insn->code) == BPF_X) {
5961 if (insn->imm != 0) {
092ed096 5962 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
5963 return -EINVAL;
5964 }
5965
5966 /* check src1 operand */
dc503a8a 5967 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
5968 if (err)
5969 return err;
1be7f75d
AS
5970
5971 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 5972 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
5973 insn->src_reg);
5974 return -EACCES;
5975 }
fb8d251e 5976 src_reg = &regs[insn->src_reg];
17a52670
AS
5977 } else {
5978 if (insn->src_reg != BPF_REG_0) {
092ed096 5979 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
5980 return -EINVAL;
5981 }
5982 }
5983
5984 /* check src2 operand */
dc503a8a 5985 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
5986 if (err)
5987 return err;
5988
1a0dc1ac 5989 dst_reg = &regs[insn->dst_reg];
092ed096 5990 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 5991
fb8d251e
AS
5992 if (BPF_SRC(insn->code) == BPF_K)
5993 pred = is_branch_taken(dst_reg, insn->imm,
5994 opcode, is_jmp32);
5995 else if (src_reg->type == SCALAR_VALUE &&
5996 tnum_is_const(src_reg->var_off))
5997 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
5998 opcode, is_jmp32);
b5dc0163
AS
5999 if (pred >= 0) {
6000 err = mark_chain_precision(env, insn->dst_reg);
6001 if (BPF_SRC(insn->code) == BPF_X && !err)
6002 err = mark_chain_precision(env, insn->src_reg);
6003 if (err)
6004 return err;
6005 }
fb8d251e
AS
6006 if (pred == 1) {
6007 /* only follow the goto, ignore fall-through */
6008 *insn_idx += insn->off;
6009 return 0;
6010 } else if (pred == 0) {
6011 /* only follow fall-through branch, since
6012 * that's where the program will go
6013 */
6014 return 0;
17a52670
AS
6015 }
6016
979d63d5
DB
6017 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6018 false);
17a52670
AS
6019 if (!other_branch)
6020 return -EFAULT;
f4d7e40a 6021 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 6022
48461135
JB
6023 /* detect if we are comparing against a constant value so we can adjust
6024 * our min/max values for our dst register.
f1174f77
EC
6025 * this is only legit if both are scalars (or pointers to the same
6026 * object, I suppose, but we don't support that right now), because
6027 * otherwise the different base pointers mean the offsets aren't
6028 * comparable.
48461135
JB
6029 */
6030 if (BPF_SRC(insn->code) == BPF_X) {
092ed096
JW
6031 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
6032 struct bpf_reg_state lo_reg0 = *dst_reg;
6033 struct bpf_reg_state lo_reg1 = *src_reg;
6034 struct bpf_reg_state *src_lo, *dst_lo;
6035
6036 dst_lo = &lo_reg0;
6037 src_lo = &lo_reg1;
6038 coerce_reg_to_size(dst_lo, 4);
6039 coerce_reg_to_size(src_lo, 4);
6040
f1174f77 6041 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
6042 src_reg->type == SCALAR_VALUE) {
6043 if (tnum_is_const(src_reg->var_off) ||
6044 (is_jmp32 && tnum_is_const(src_lo->var_off)))
f4d7e40a 6045 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096
JW
6046 dst_reg,
6047 is_jmp32
6048 ? src_lo->var_off.value
6049 : src_reg->var_off.value,
6050 opcode, is_jmp32);
6051 else if (tnum_is_const(dst_reg->var_off) ||
6052 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
f4d7e40a 6053 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096
JW
6054 src_reg,
6055 is_jmp32
6056 ? dst_lo->var_off.value
6057 : dst_reg->var_off.value,
6058 opcode, is_jmp32);
6059 else if (!is_jmp32 &&
6060 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 6061 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
6062 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6063 &other_branch_regs[insn->dst_reg],
092ed096 6064 src_reg, dst_reg, opcode);
f1174f77
EC
6065 }
6066 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 6067 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 6068 dst_reg, insn->imm, opcode, is_jmp32);
48461135
JB
6069 }
6070
092ed096
JW
6071 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6072 * NOTE: these optimizations below are related with pointer comparison
6073 * which will never be JMP32.
6074 */
6075 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 6076 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
6077 reg_type_may_be_null(dst_reg->type)) {
6078 /* Mark all identical registers in each branch as either
57a09bf0
TG
6079 * safe or unknown depending R == 0 or R != 0 conditional.
6080 */
840b9615
JS
6081 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
6082 opcode == BPF_JNE);
6083 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
6084 opcode == BPF_JEQ);
5beca081
DB
6085 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
6086 this_branch, other_branch) &&
6087 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
6088 verbose(env, "R%d pointer comparison prohibited\n",
6089 insn->dst_reg);
1be7f75d 6090 return -EACCES;
17a52670 6091 }
06ee7115 6092 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 6093 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
6094 return 0;
6095}
6096
17a52670 6097/* verify BPF_LD_IMM64 instruction */
58e2af8b 6098static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 6099{
d8eca5bb 6100 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 6101 struct bpf_reg_state *regs = cur_regs(env);
d8eca5bb 6102 struct bpf_map *map;
17a52670
AS
6103 int err;
6104
6105 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 6106 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
6107 return -EINVAL;
6108 }
6109 if (insn->off != 0) {
61bd5218 6110 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
6111 return -EINVAL;
6112 }
6113
dc503a8a 6114 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
6115 if (err)
6116 return err;
6117
6b173873 6118 if (insn->src_reg == 0) {
6b173873
JK
6119 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
6120
f1174f77 6121 regs[insn->dst_reg].type = SCALAR_VALUE;
b03c9f9f 6122 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 6123 return 0;
6b173873 6124 }
17a52670 6125
d8eca5bb
DB
6126 map = env->used_maps[aux->map_index];
6127 mark_reg_known_zero(env, regs, insn->dst_reg);
6128 regs[insn->dst_reg].map_ptr = map;
6129
6130 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
6131 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
6132 regs[insn->dst_reg].off = aux->map_off;
6133 if (map_value_has_spin_lock(map))
6134 regs[insn->dst_reg].id = ++env->id_gen;
6135 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
6136 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
6137 } else {
6138 verbose(env, "bpf verifier is misconfigured\n");
6139 return -EINVAL;
6140 }
17a52670 6141
17a52670
AS
6142 return 0;
6143}
6144
96be4325
DB
6145static bool may_access_skb(enum bpf_prog_type type)
6146{
6147 switch (type) {
6148 case BPF_PROG_TYPE_SOCKET_FILTER:
6149 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 6150 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
6151 return true;
6152 default:
6153 return false;
6154 }
6155}
6156
ddd872bc
AS
6157/* verify safety of LD_ABS|LD_IND instructions:
6158 * - they can only appear in the programs where ctx == skb
6159 * - since they are wrappers of function calls, they scratch R1-R5 registers,
6160 * preserve R6-R9, and store return value into R0
6161 *
6162 * Implicit input:
6163 * ctx == skb == R6 == CTX
6164 *
6165 * Explicit input:
6166 * SRC == any register
6167 * IMM == 32-bit immediate
6168 *
6169 * Output:
6170 * R0 - 8/16/32-bit skb data converted to cpu endianness
6171 */
58e2af8b 6172static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 6173{
638f5b90 6174 struct bpf_reg_state *regs = cur_regs(env);
ddd872bc 6175 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
6176 int i, err;
6177
24701ece 6178 if (!may_access_skb(env->prog->type)) {
61bd5218 6179 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
6180 return -EINVAL;
6181 }
6182
e0cea7ce
DB
6183 if (!env->ops->gen_ld_abs) {
6184 verbose(env, "bpf verifier is misconfigured\n");
6185 return -EINVAL;
6186 }
6187
f910cefa 6188 if (env->subprog_cnt > 1) {
f4d7e40a
AS
6189 /* when program has LD_ABS insn JITs and interpreter assume
6190 * that r1 == ctx == skb which is not the case for callees
6191 * that can have arbitrary arguments. It's problematic
6192 * for main prog as well since JITs would need to analyze
6193 * all functions in order to make proper register save/restore
6194 * decisions in the main prog. Hence disallow LD_ABS with calls
6195 */
6196 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6197 return -EINVAL;
6198 }
6199
ddd872bc 6200 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 6201 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 6202 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 6203 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
6204 return -EINVAL;
6205 }
6206
6207 /* check whether implicit source operand (register R6) is readable */
dc503a8a 6208 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
ddd872bc
AS
6209 if (err)
6210 return err;
6211
fd978bf7
JS
6212 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6213 * gen_ld_abs() may terminate the program at runtime, leading to
6214 * reference leak.
6215 */
6216 err = check_reference_leak(env);
6217 if (err) {
6218 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6219 return err;
6220 }
6221
d83525ca
AS
6222 if (env->cur_state->active_spin_lock) {
6223 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6224 return -EINVAL;
6225 }
6226
ddd872bc 6227 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
61bd5218
JK
6228 verbose(env,
6229 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
6230 return -EINVAL;
6231 }
6232
6233 if (mode == BPF_IND) {
6234 /* check explicit source operand */
dc503a8a 6235 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
6236 if (err)
6237 return err;
6238 }
6239
6240 /* reset caller saved regs to unreadable */
dc503a8a 6241 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 6242 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
6243 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6244 }
ddd872bc
AS
6245
6246 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
6247 * the value fetched from the packet.
6248 * Already marked as written above.
ddd872bc 6249 */
61bd5218 6250 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
6251 /* ld_abs load up to 32-bit skb data. */
6252 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
6253 return 0;
6254}
6255
390ee7e2
AS
6256static int check_return_code(struct bpf_verifier_env *env)
6257{
5cf1e914 6258 struct tnum enforce_attach_type_range = tnum_unknown;
390ee7e2
AS
6259 struct bpf_reg_state *reg;
6260 struct tnum range = tnum_range(0, 1);
6261
6262 switch (env->prog->type) {
983695fa
DB
6263 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
6264 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
6265 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
6266 range = tnum_range(1, 1);
ed4ed404 6267 break;
390ee7e2 6268 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 6269 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
6270 range = tnum_range(0, 3);
6271 enforce_attach_type_range = tnum_range(2, 3);
6272 }
ed4ed404 6273 break;
390ee7e2
AS
6274 case BPF_PROG_TYPE_CGROUP_SOCK:
6275 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 6276 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 6277 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 6278 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 6279 break;
15ab09bd
AS
6280 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6281 if (!env->prog->aux->attach_btf_id)
6282 return 0;
6283 range = tnum_const(0);
6284 break;
390ee7e2
AS
6285 default:
6286 return 0;
6287 }
6288
638f5b90 6289 reg = cur_regs(env) + BPF_REG_0;
390ee7e2 6290 if (reg->type != SCALAR_VALUE) {
61bd5218 6291 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
6292 reg_type_str[reg->type]);
6293 return -EINVAL;
6294 }
6295
6296 if (!tnum_in(range, reg->var_off)) {
5cf1e914 6297 char tn_buf[48];
6298
61bd5218 6299 verbose(env, "At program exit the register R0 ");
390ee7e2 6300 if (!tnum_is_unknown(reg->var_off)) {
390ee7e2 6301 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 6302 verbose(env, "has value %s", tn_buf);
390ee7e2 6303 } else {
61bd5218 6304 verbose(env, "has unknown scalar value");
390ee7e2 6305 }
5cf1e914 6306 tnum_strn(tn_buf, sizeof(tn_buf), range);
983695fa 6307 verbose(env, " should have been in %s\n", tn_buf);
390ee7e2
AS
6308 return -EINVAL;
6309 }
5cf1e914 6310
6311 if (!tnum_is_unknown(enforce_attach_type_range) &&
6312 tnum_in(enforce_attach_type_range, reg->var_off))
6313 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
6314 return 0;
6315}
6316
475fb78f
AS
6317/* non-recursive DFS pseudo code
6318 * 1 procedure DFS-iterative(G,v):
6319 * 2 label v as discovered
6320 * 3 let S be a stack
6321 * 4 S.push(v)
6322 * 5 while S is not empty
6323 * 6 t <- S.pop()
6324 * 7 if t is what we're looking for:
6325 * 8 return t
6326 * 9 for all edges e in G.adjacentEdges(t) do
6327 * 10 if edge e is already labelled
6328 * 11 continue with the next edge
6329 * 12 w <- G.adjacentVertex(t,e)
6330 * 13 if vertex w is not discovered and not explored
6331 * 14 label e as tree-edge
6332 * 15 label w as discovered
6333 * 16 S.push(w)
6334 * 17 continue at 5
6335 * 18 else if vertex w is discovered
6336 * 19 label e as back-edge
6337 * 20 else
6338 * 21 // vertex w is explored
6339 * 22 label e as forward- or cross-edge
6340 * 23 label t as explored
6341 * 24 S.pop()
6342 *
6343 * convention:
6344 * 0x10 - discovered
6345 * 0x11 - discovered and fall-through edge labelled
6346 * 0x12 - discovered and fall-through and branch edges labelled
6347 * 0x20 - explored
6348 */
6349
6350enum {
6351 DISCOVERED = 0x10,
6352 EXPLORED = 0x20,
6353 FALLTHROUGH = 1,
6354 BRANCH = 2,
6355};
6356
dc2a4ebc
AS
6357static u32 state_htab_size(struct bpf_verifier_env *env)
6358{
6359 return env->prog->len;
6360}
6361
5d839021
AS
6362static struct bpf_verifier_state_list **explored_state(
6363 struct bpf_verifier_env *env,
6364 int idx)
6365{
dc2a4ebc
AS
6366 struct bpf_verifier_state *cur = env->cur_state;
6367 struct bpf_func_state *state = cur->frame[cur->curframe];
6368
6369 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
6370}
6371
6372static void init_explored_state(struct bpf_verifier_env *env, int idx)
6373{
a8f500af 6374 env->insn_aux_data[idx].prune_point = true;
5d839021 6375}
f1bca824 6376
475fb78f
AS
6377/* t, w, e - match pseudo-code above:
6378 * t - index of current instruction
6379 * w - next instruction
6380 * e - edge
6381 */
2589726d
AS
6382static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
6383 bool loop_ok)
475fb78f 6384{
7df737e9
AS
6385 int *insn_stack = env->cfg.insn_stack;
6386 int *insn_state = env->cfg.insn_state;
6387
475fb78f
AS
6388 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
6389 return 0;
6390
6391 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
6392 return 0;
6393
6394 if (w < 0 || w >= env->prog->len) {
d9762e84 6395 verbose_linfo(env, t, "%d: ", t);
61bd5218 6396 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
6397 return -EINVAL;
6398 }
6399
f1bca824
AS
6400 if (e == BRANCH)
6401 /* mark branch target for state pruning */
5d839021 6402 init_explored_state(env, w);
f1bca824 6403
475fb78f
AS
6404 if (insn_state[w] == 0) {
6405 /* tree-edge */
6406 insn_state[t] = DISCOVERED | e;
6407 insn_state[w] = DISCOVERED;
7df737e9 6408 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 6409 return -E2BIG;
7df737e9 6410 insn_stack[env->cfg.cur_stack++] = w;
475fb78f
AS
6411 return 1;
6412 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2589726d
AS
6413 if (loop_ok && env->allow_ptr_leaks)
6414 return 0;
d9762e84
MKL
6415 verbose_linfo(env, t, "%d: ", t);
6416 verbose_linfo(env, w, "%d: ", w);
61bd5218 6417 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
6418 return -EINVAL;
6419 } else if (insn_state[w] == EXPLORED) {
6420 /* forward- or cross-edge */
6421 insn_state[t] = DISCOVERED | e;
6422 } else {
61bd5218 6423 verbose(env, "insn state internal bug\n");
475fb78f
AS
6424 return -EFAULT;
6425 }
6426 return 0;
6427}
6428
6429/* non-recursive depth-first-search to detect loops in BPF program
6430 * loop == back-edge in directed graph
6431 */
58e2af8b 6432static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
6433{
6434 struct bpf_insn *insns = env->prog->insnsi;
6435 int insn_cnt = env->prog->len;
7df737e9 6436 int *insn_stack, *insn_state;
475fb78f
AS
6437 int ret = 0;
6438 int i, t;
6439
7df737e9 6440 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
6441 if (!insn_state)
6442 return -ENOMEM;
6443
7df737e9 6444 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 6445 if (!insn_stack) {
71dde681 6446 kvfree(insn_state);
475fb78f
AS
6447 return -ENOMEM;
6448 }
6449
6450 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
6451 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 6452 env->cfg.cur_stack = 1;
475fb78f
AS
6453
6454peek_stack:
7df737e9 6455 if (env->cfg.cur_stack == 0)
475fb78f 6456 goto check_state;
7df737e9 6457 t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 6458
092ed096
JW
6459 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
6460 BPF_CLASS(insns[t].code) == BPF_JMP32) {
475fb78f
AS
6461 u8 opcode = BPF_OP(insns[t].code);
6462
6463 if (opcode == BPF_EXIT) {
6464 goto mark_explored;
6465 } else if (opcode == BPF_CALL) {
2589726d 6466 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
6467 if (ret == 1)
6468 goto peek_stack;
6469 else if (ret < 0)
6470 goto err_free;
07016151 6471 if (t + 1 < insn_cnt)
5d839021 6472 init_explored_state(env, t + 1);
cc8b0b92 6473 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
5d839021 6474 init_explored_state(env, t);
2589726d
AS
6475 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
6476 env, false);
cc8b0b92
AS
6477 if (ret == 1)
6478 goto peek_stack;
6479 else if (ret < 0)
6480 goto err_free;
6481 }
475fb78f
AS
6482 } else if (opcode == BPF_JA) {
6483 if (BPF_SRC(insns[t].code) != BPF_K) {
6484 ret = -EINVAL;
6485 goto err_free;
6486 }
6487 /* unconditional jump with single edge */
6488 ret = push_insn(t, t + insns[t].off + 1,
2589726d 6489 FALLTHROUGH, env, true);
475fb78f
AS
6490 if (ret == 1)
6491 goto peek_stack;
6492 else if (ret < 0)
6493 goto err_free;
b5dc0163
AS
6494 /* unconditional jmp is not a good pruning point,
6495 * but it's marked, since backtracking needs
6496 * to record jmp history in is_state_visited().
6497 */
6498 init_explored_state(env, t + insns[t].off + 1);
f1bca824
AS
6499 /* tell verifier to check for equivalent states
6500 * after every call and jump
6501 */
c3de6317 6502 if (t + 1 < insn_cnt)
5d839021 6503 init_explored_state(env, t + 1);
475fb78f
AS
6504 } else {
6505 /* conditional jump with two edges */
5d839021 6506 init_explored_state(env, t);
2589726d 6507 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
475fb78f
AS
6508 if (ret == 1)
6509 goto peek_stack;
6510 else if (ret < 0)
6511 goto err_free;
6512
2589726d 6513 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
475fb78f
AS
6514 if (ret == 1)
6515 goto peek_stack;
6516 else if (ret < 0)
6517 goto err_free;
6518 }
6519 } else {
6520 /* all other non-branch instructions with single
6521 * fall-through edge
6522 */
2589726d 6523 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
475fb78f
AS
6524 if (ret == 1)
6525 goto peek_stack;
6526 else if (ret < 0)
6527 goto err_free;
6528 }
6529
6530mark_explored:
6531 insn_state[t] = EXPLORED;
7df737e9 6532 if (env->cfg.cur_stack-- <= 0) {
61bd5218 6533 verbose(env, "pop stack internal bug\n");
475fb78f
AS
6534 ret = -EFAULT;
6535 goto err_free;
6536 }
6537 goto peek_stack;
6538
6539check_state:
6540 for (i = 0; i < insn_cnt; i++) {
6541 if (insn_state[i] != EXPLORED) {
61bd5218 6542 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
6543 ret = -EINVAL;
6544 goto err_free;
6545 }
6546 }
6547 ret = 0; /* cfg looks good */
6548
6549err_free:
71dde681
AS
6550 kvfree(insn_state);
6551 kvfree(insn_stack);
7df737e9 6552 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
6553 return ret;
6554}
6555
838e9690
YS
6556/* The minimum supported BTF func info size */
6557#define MIN_BPF_FUNCINFO_SIZE 8
6558#define MAX_FUNCINFO_REC_SIZE 252
6559
c454a46b
MKL
6560static int check_btf_func(struct bpf_verifier_env *env,
6561 const union bpf_attr *attr,
6562 union bpf_attr __user *uattr)
838e9690 6563{
d0b2818e 6564 u32 i, nfuncs, urec_size, min_size;
838e9690 6565 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 6566 struct bpf_func_info *krecord;
838e9690 6567 const struct btf_type *type;
c454a46b
MKL
6568 struct bpf_prog *prog;
6569 const struct btf *btf;
838e9690 6570 void __user *urecord;
d0b2818e 6571 u32 prev_offset = 0;
838e9690
YS
6572 int ret = 0;
6573
6574 nfuncs = attr->func_info_cnt;
6575 if (!nfuncs)
6576 return 0;
6577
6578 if (nfuncs != env->subprog_cnt) {
6579 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
6580 return -EINVAL;
6581 }
6582
6583 urec_size = attr->func_info_rec_size;
6584 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
6585 urec_size > MAX_FUNCINFO_REC_SIZE ||
6586 urec_size % sizeof(u32)) {
6587 verbose(env, "invalid func info rec size %u\n", urec_size);
6588 return -EINVAL;
6589 }
6590
c454a46b
MKL
6591 prog = env->prog;
6592 btf = prog->aux->btf;
838e9690
YS
6593
6594 urecord = u64_to_user_ptr(attr->func_info);
6595 min_size = min_t(u32, krec_size, urec_size);
6596
ba64e7d8 6597 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
6598 if (!krecord)
6599 return -ENOMEM;
ba64e7d8 6600
838e9690
YS
6601 for (i = 0; i < nfuncs; i++) {
6602 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
6603 if (ret) {
6604 if (ret == -E2BIG) {
6605 verbose(env, "nonzero tailing record in func info");
6606 /* set the size kernel expects so loader can zero
6607 * out the rest of the record.
6608 */
6609 if (put_user(min_size, &uattr->func_info_rec_size))
6610 ret = -EFAULT;
6611 }
c454a46b 6612 goto err_free;
838e9690
YS
6613 }
6614
ba64e7d8 6615 if (copy_from_user(&krecord[i], urecord, min_size)) {
838e9690 6616 ret = -EFAULT;
c454a46b 6617 goto err_free;
838e9690
YS
6618 }
6619
d30d42e0 6620 /* check insn_off */
838e9690 6621 if (i == 0) {
d30d42e0 6622 if (krecord[i].insn_off) {
838e9690 6623 verbose(env,
d30d42e0
MKL
6624 "nonzero insn_off %u for the first func info record",
6625 krecord[i].insn_off);
838e9690 6626 ret = -EINVAL;
c454a46b 6627 goto err_free;
838e9690 6628 }
d30d42e0 6629 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
6630 verbose(env,
6631 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 6632 krecord[i].insn_off, prev_offset);
838e9690 6633 ret = -EINVAL;
c454a46b 6634 goto err_free;
838e9690
YS
6635 }
6636
d30d42e0 6637 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690
YS
6638 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
6639 ret = -EINVAL;
c454a46b 6640 goto err_free;
838e9690
YS
6641 }
6642
6643 /* check type_id */
ba64e7d8 6644 type = btf_type_by_id(btf, krecord[i].type_id);
838e9690
YS
6645 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
6646 verbose(env, "invalid type id %d in func info",
ba64e7d8 6647 krecord[i].type_id);
838e9690 6648 ret = -EINVAL;
c454a46b 6649 goto err_free;
838e9690
YS
6650 }
6651
d30d42e0 6652 prev_offset = krecord[i].insn_off;
838e9690
YS
6653 urecord += urec_size;
6654 }
6655
ba64e7d8
YS
6656 prog->aux->func_info = krecord;
6657 prog->aux->func_info_cnt = nfuncs;
838e9690
YS
6658 return 0;
6659
c454a46b 6660err_free:
ba64e7d8 6661 kvfree(krecord);
838e9690
YS
6662 return ret;
6663}
6664
ba64e7d8
YS
6665static void adjust_btf_func(struct bpf_verifier_env *env)
6666{
6667 int i;
6668
6669 if (!env->prog->aux->func_info)
6670 return;
6671
6672 for (i = 0; i < env->subprog_cnt; i++)
d30d42e0 6673 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
6674}
6675
c454a46b
MKL
6676#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
6677 sizeof(((struct bpf_line_info *)(0))->line_col))
6678#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
6679
6680static int check_btf_line(struct bpf_verifier_env *env,
6681 const union bpf_attr *attr,
6682 union bpf_attr __user *uattr)
6683{
6684 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
6685 struct bpf_subprog_info *sub;
6686 struct bpf_line_info *linfo;
6687 struct bpf_prog *prog;
6688 const struct btf *btf;
6689 void __user *ulinfo;
6690 int err;
6691
6692 nr_linfo = attr->line_info_cnt;
6693 if (!nr_linfo)
6694 return 0;
6695
6696 rec_size = attr->line_info_rec_size;
6697 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
6698 rec_size > MAX_LINEINFO_REC_SIZE ||
6699 rec_size & (sizeof(u32) - 1))
6700 return -EINVAL;
6701
6702 /* Need to zero it in case the userspace may
6703 * pass in a smaller bpf_line_info object.
6704 */
6705 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
6706 GFP_KERNEL | __GFP_NOWARN);
6707 if (!linfo)
6708 return -ENOMEM;
6709
6710 prog = env->prog;
6711 btf = prog->aux->btf;
6712
6713 s = 0;
6714 sub = env->subprog_info;
6715 ulinfo = u64_to_user_ptr(attr->line_info);
6716 expected_size = sizeof(struct bpf_line_info);
6717 ncopy = min_t(u32, expected_size, rec_size);
6718 for (i = 0; i < nr_linfo; i++) {
6719 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
6720 if (err) {
6721 if (err == -E2BIG) {
6722 verbose(env, "nonzero tailing record in line_info");
6723 if (put_user(expected_size,
6724 &uattr->line_info_rec_size))
6725 err = -EFAULT;
6726 }
6727 goto err_free;
6728 }
6729
6730 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
6731 err = -EFAULT;
6732 goto err_free;
6733 }
6734
6735 /*
6736 * Check insn_off to ensure
6737 * 1) strictly increasing AND
6738 * 2) bounded by prog->len
6739 *
6740 * The linfo[0].insn_off == 0 check logically falls into
6741 * the later "missing bpf_line_info for func..." case
6742 * because the first linfo[0].insn_off must be the
6743 * first sub also and the first sub must have
6744 * subprog_info[0].start == 0.
6745 */
6746 if ((i && linfo[i].insn_off <= prev_offset) ||
6747 linfo[i].insn_off >= prog->len) {
6748 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
6749 i, linfo[i].insn_off, prev_offset,
6750 prog->len);
6751 err = -EINVAL;
6752 goto err_free;
6753 }
6754
fdbaa0be
MKL
6755 if (!prog->insnsi[linfo[i].insn_off].code) {
6756 verbose(env,
6757 "Invalid insn code at line_info[%u].insn_off\n",
6758 i);
6759 err = -EINVAL;
6760 goto err_free;
6761 }
6762
23127b33
MKL
6763 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
6764 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
6765 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
6766 err = -EINVAL;
6767 goto err_free;
6768 }
6769
6770 if (s != env->subprog_cnt) {
6771 if (linfo[i].insn_off == sub[s].start) {
6772 sub[s].linfo_idx = i;
6773 s++;
6774 } else if (sub[s].start < linfo[i].insn_off) {
6775 verbose(env, "missing bpf_line_info for func#%u\n", s);
6776 err = -EINVAL;
6777 goto err_free;
6778 }
6779 }
6780
6781 prev_offset = linfo[i].insn_off;
6782 ulinfo += rec_size;
6783 }
6784
6785 if (s != env->subprog_cnt) {
6786 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
6787 env->subprog_cnt - s, s);
6788 err = -EINVAL;
6789 goto err_free;
6790 }
6791
6792 prog->aux->linfo = linfo;
6793 prog->aux->nr_linfo = nr_linfo;
6794
6795 return 0;
6796
6797err_free:
6798 kvfree(linfo);
6799 return err;
6800}
6801
6802static int check_btf_info(struct bpf_verifier_env *env,
6803 const union bpf_attr *attr,
6804 union bpf_attr __user *uattr)
6805{
6806 struct btf *btf;
6807 int err;
6808
6809 if (!attr->func_info_cnt && !attr->line_info_cnt)
6810 return 0;
6811
6812 btf = btf_get_by_fd(attr->prog_btf_fd);
6813 if (IS_ERR(btf))
6814 return PTR_ERR(btf);
6815 env->prog->aux->btf = btf;
6816
6817 err = check_btf_func(env, attr, uattr);
6818 if (err)
6819 return err;
6820
6821 err = check_btf_line(env, attr, uattr);
6822 if (err)
6823 return err;
6824
6825 return 0;
ba64e7d8
YS
6826}
6827
f1174f77
EC
6828/* check %cur's range satisfies %old's */
6829static bool range_within(struct bpf_reg_state *old,
6830 struct bpf_reg_state *cur)
6831{
b03c9f9f
EC
6832 return old->umin_value <= cur->umin_value &&
6833 old->umax_value >= cur->umax_value &&
6834 old->smin_value <= cur->smin_value &&
6835 old->smax_value >= cur->smax_value;
f1174f77
EC
6836}
6837
6838/* Maximum number of register states that can exist at once */
6839#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
6840struct idpair {
6841 u32 old;
6842 u32 cur;
6843};
6844
6845/* If in the old state two registers had the same id, then they need to have
6846 * the same id in the new state as well. But that id could be different from
6847 * the old state, so we need to track the mapping from old to new ids.
6848 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
6849 * regs with old id 5 must also have new id 9 for the new state to be safe. But
6850 * regs with a different old id could still have new id 9, we don't care about
6851 * that.
6852 * So we look through our idmap to see if this old id has been seen before. If
6853 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 6854 */
f1174f77 6855static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
969bf05e 6856{
f1174f77 6857 unsigned int i;
969bf05e 6858
f1174f77
EC
6859 for (i = 0; i < ID_MAP_SIZE; i++) {
6860 if (!idmap[i].old) {
6861 /* Reached an empty slot; haven't seen this id before */
6862 idmap[i].old = old_id;
6863 idmap[i].cur = cur_id;
6864 return true;
6865 }
6866 if (idmap[i].old == old_id)
6867 return idmap[i].cur == cur_id;
6868 }
6869 /* We ran out of idmap slots, which should be impossible */
6870 WARN_ON_ONCE(1);
6871 return false;
6872}
6873
9242b5f5
AS
6874static void clean_func_state(struct bpf_verifier_env *env,
6875 struct bpf_func_state *st)
6876{
6877 enum bpf_reg_liveness live;
6878 int i, j;
6879
6880 for (i = 0; i < BPF_REG_FP; i++) {
6881 live = st->regs[i].live;
6882 /* liveness must not touch this register anymore */
6883 st->regs[i].live |= REG_LIVE_DONE;
6884 if (!(live & REG_LIVE_READ))
6885 /* since the register is unused, clear its state
6886 * to make further comparison simpler
6887 */
6888 __mark_reg_not_init(&st->regs[i]);
6889 }
6890
6891 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
6892 live = st->stack[i].spilled_ptr.live;
6893 /* liveness must not touch this stack slot anymore */
6894 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
6895 if (!(live & REG_LIVE_READ)) {
6896 __mark_reg_not_init(&st->stack[i].spilled_ptr);
6897 for (j = 0; j < BPF_REG_SIZE; j++)
6898 st->stack[i].slot_type[j] = STACK_INVALID;
6899 }
6900 }
6901}
6902
6903static void clean_verifier_state(struct bpf_verifier_env *env,
6904 struct bpf_verifier_state *st)
6905{
6906 int i;
6907
6908 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
6909 /* all regs in this state in all frames were already marked */
6910 return;
6911
6912 for (i = 0; i <= st->curframe; i++)
6913 clean_func_state(env, st->frame[i]);
6914}
6915
6916/* the parentage chains form a tree.
6917 * the verifier states are added to state lists at given insn and
6918 * pushed into state stack for future exploration.
6919 * when the verifier reaches bpf_exit insn some of the verifer states
6920 * stored in the state lists have their final liveness state already,
6921 * but a lot of states will get revised from liveness point of view when
6922 * the verifier explores other branches.
6923 * Example:
6924 * 1: r0 = 1
6925 * 2: if r1 == 100 goto pc+1
6926 * 3: r0 = 2
6927 * 4: exit
6928 * when the verifier reaches exit insn the register r0 in the state list of
6929 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
6930 * of insn 2 and goes exploring further. At the insn 4 it will walk the
6931 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
6932 *
6933 * Since the verifier pushes the branch states as it sees them while exploring
6934 * the program the condition of walking the branch instruction for the second
6935 * time means that all states below this branch were already explored and
6936 * their final liveness markes are already propagated.
6937 * Hence when the verifier completes the search of state list in is_state_visited()
6938 * we can call this clean_live_states() function to mark all liveness states
6939 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
6940 * will not be used.
6941 * This function also clears the registers and stack for states that !READ
6942 * to simplify state merging.
6943 *
6944 * Important note here that walking the same branch instruction in the callee
6945 * doesn't meant that the states are DONE. The verifier has to compare
6946 * the callsites
6947 */
6948static void clean_live_states(struct bpf_verifier_env *env, int insn,
6949 struct bpf_verifier_state *cur)
6950{
6951 struct bpf_verifier_state_list *sl;
6952 int i;
6953
5d839021 6954 sl = *explored_state(env, insn);
a8f500af 6955 while (sl) {
2589726d
AS
6956 if (sl->state.branches)
6957 goto next;
dc2a4ebc
AS
6958 if (sl->state.insn_idx != insn ||
6959 sl->state.curframe != cur->curframe)
9242b5f5
AS
6960 goto next;
6961 for (i = 0; i <= cur->curframe; i++)
6962 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
6963 goto next;
6964 clean_verifier_state(env, &sl->state);
6965next:
6966 sl = sl->next;
6967 }
6968}
6969
f1174f77 6970/* Returns true if (rold safe implies rcur safe) */
1b688a19
EC
6971static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
6972 struct idpair *idmap)
f1174f77 6973{
f4d7e40a
AS
6974 bool equal;
6975
dc503a8a
EC
6976 if (!(rold->live & REG_LIVE_READ))
6977 /* explored state didn't use this */
6978 return true;
6979
679c782d 6980 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
6981
6982 if (rold->type == PTR_TO_STACK)
6983 /* two stack pointers are equal only if they're pointing to
6984 * the same stack frame, since fp-8 in foo != fp-8 in bar
6985 */
6986 return equal && rold->frameno == rcur->frameno;
6987
6988 if (equal)
969bf05e
AS
6989 return true;
6990
f1174f77
EC
6991 if (rold->type == NOT_INIT)
6992 /* explored state can't have used this */
969bf05e 6993 return true;
f1174f77
EC
6994 if (rcur->type == NOT_INIT)
6995 return false;
6996 switch (rold->type) {
6997 case SCALAR_VALUE:
6998 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
6999 if (!rold->precise && !rcur->precise)
7000 return true;
f1174f77
EC
7001 /* new val must satisfy old val knowledge */
7002 return range_within(rold, rcur) &&
7003 tnum_in(rold->var_off, rcur->var_off);
7004 } else {
179d1c56
JH
7005 /* We're trying to use a pointer in place of a scalar.
7006 * Even if the scalar was unbounded, this could lead to
7007 * pointer leaks because scalars are allowed to leak
7008 * while pointers are not. We could make this safe in
7009 * special cases if root is calling us, but it's
7010 * probably not worth the hassle.
f1174f77 7011 */
179d1c56 7012 return false;
f1174f77
EC
7013 }
7014 case PTR_TO_MAP_VALUE:
1b688a19
EC
7015 /* If the new min/max/var_off satisfy the old ones and
7016 * everything else matches, we are OK.
d83525ca
AS
7017 * 'id' is not compared, since it's only used for maps with
7018 * bpf_spin_lock inside map element and in such cases if
7019 * the rest of the prog is valid for one map element then
7020 * it's valid for all map elements regardless of the key
7021 * used in bpf_map_lookup()
1b688a19
EC
7022 */
7023 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
7024 range_within(rold, rcur) &&
7025 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
7026 case PTR_TO_MAP_VALUE_OR_NULL:
7027 /* a PTR_TO_MAP_VALUE could be safe to use as a
7028 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7029 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7030 * checked, doing so could have affected others with the same
7031 * id, and we can't check for that because we lost the id when
7032 * we converted to a PTR_TO_MAP_VALUE.
7033 */
7034 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
7035 return false;
7036 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
7037 return false;
7038 /* Check our ids match any regs they're supposed to */
7039 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 7040 case PTR_TO_PACKET_META:
f1174f77 7041 case PTR_TO_PACKET:
de8f3a83 7042 if (rcur->type != rold->type)
f1174f77
EC
7043 return false;
7044 /* We must have at least as much range as the old ptr
7045 * did, so that any accesses which were safe before are
7046 * still safe. This is true even if old range < old off,
7047 * since someone could have accessed through (ptr - k), or
7048 * even done ptr -= k in a register, to get a safe access.
7049 */
7050 if (rold->range > rcur->range)
7051 return false;
7052 /* If the offsets don't match, we can't trust our alignment;
7053 * nor can we be sure that we won't fall out of range.
7054 */
7055 if (rold->off != rcur->off)
7056 return false;
7057 /* id relations must be preserved */
7058 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
7059 return false;
7060 /* new val must satisfy old val knowledge */
7061 return range_within(rold, rcur) &&
7062 tnum_in(rold->var_off, rcur->var_off);
7063 case PTR_TO_CTX:
7064 case CONST_PTR_TO_MAP:
f1174f77 7065 case PTR_TO_PACKET_END:
d58e468b 7066 case PTR_TO_FLOW_KEYS:
c64b7983
JS
7067 case PTR_TO_SOCKET:
7068 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
7069 case PTR_TO_SOCK_COMMON:
7070 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
7071 case PTR_TO_TCP_SOCK:
7072 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 7073 case PTR_TO_XDP_SOCK:
f1174f77
EC
7074 /* Only valid matches are exact, which memcmp() above
7075 * would have accepted
7076 */
7077 default:
7078 /* Don't know what's going on, just say it's not safe */
7079 return false;
7080 }
969bf05e 7081
f1174f77
EC
7082 /* Shouldn't get here; if we do, say it's not safe */
7083 WARN_ON_ONCE(1);
969bf05e
AS
7084 return false;
7085}
7086
f4d7e40a
AS
7087static bool stacksafe(struct bpf_func_state *old,
7088 struct bpf_func_state *cur,
638f5b90
AS
7089 struct idpair *idmap)
7090{
7091 int i, spi;
7092
638f5b90
AS
7093 /* walk slots of the explored stack and ignore any additional
7094 * slots in the current stack, since explored(safe) state
7095 * didn't use them
7096 */
7097 for (i = 0; i < old->allocated_stack; i++) {
7098 spi = i / BPF_REG_SIZE;
7099
b233920c
AS
7100 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
7101 i += BPF_REG_SIZE - 1;
cc2b14d5 7102 /* explored state didn't use this */
fd05e57b 7103 continue;
b233920c 7104 }
cc2b14d5 7105
638f5b90
AS
7106 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
7107 continue;
19e2dbb7
AS
7108
7109 /* explored stack has more populated slots than current stack
7110 * and these slots were used
7111 */
7112 if (i >= cur->allocated_stack)
7113 return false;
7114
cc2b14d5
AS
7115 /* if old state was safe with misc data in the stack
7116 * it will be safe with zero-initialized stack.
7117 * The opposite is not true
7118 */
7119 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
7120 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
7121 continue;
638f5b90
AS
7122 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
7123 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
7124 /* Ex: old explored (safe) state has STACK_SPILL in
7125 * this stack slot, but current has has STACK_MISC ->
7126 * this verifier states are not equivalent,
7127 * return false to continue verification of this path
7128 */
7129 return false;
7130 if (i % BPF_REG_SIZE)
7131 continue;
7132 if (old->stack[spi].slot_type[0] != STACK_SPILL)
7133 continue;
7134 if (!regsafe(&old->stack[spi].spilled_ptr,
7135 &cur->stack[spi].spilled_ptr,
7136 idmap))
7137 /* when explored and current stack slot are both storing
7138 * spilled registers, check that stored pointers types
7139 * are the same as well.
7140 * Ex: explored safe path could have stored
7141 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7142 * but current path has stored:
7143 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7144 * such verifier states are not equivalent.
7145 * return false to continue verification of this path
7146 */
7147 return false;
7148 }
7149 return true;
7150}
7151
fd978bf7
JS
7152static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
7153{
7154 if (old->acquired_refs != cur->acquired_refs)
7155 return false;
7156 return !memcmp(old->refs, cur->refs,
7157 sizeof(*old->refs) * old->acquired_refs);
7158}
7159
f1bca824
AS
7160/* compare two verifier states
7161 *
7162 * all states stored in state_list are known to be valid, since
7163 * verifier reached 'bpf_exit' instruction through them
7164 *
7165 * this function is called when verifier exploring different branches of
7166 * execution popped from the state stack. If it sees an old state that has
7167 * more strict register state and more strict stack state then this execution
7168 * branch doesn't need to be explored further, since verifier already
7169 * concluded that more strict state leads to valid finish.
7170 *
7171 * Therefore two states are equivalent if register state is more conservative
7172 * and explored stack state is more conservative than the current one.
7173 * Example:
7174 * explored current
7175 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7176 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7177 *
7178 * In other words if current stack state (one being explored) has more
7179 * valid slots than old one that already passed validation, it means
7180 * the verifier can stop exploring and conclude that current state is valid too
7181 *
7182 * Similarly with registers. If explored state has register type as invalid
7183 * whereas register type in current state is meaningful, it means that
7184 * the current state will reach 'bpf_exit' instruction safely
7185 */
f4d7e40a
AS
7186static bool func_states_equal(struct bpf_func_state *old,
7187 struct bpf_func_state *cur)
f1bca824 7188{
f1174f77
EC
7189 struct idpair *idmap;
7190 bool ret = false;
f1bca824
AS
7191 int i;
7192
f1174f77
EC
7193 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
7194 /* If we failed to allocate the idmap, just say it's not safe */
7195 if (!idmap)
1a0dc1ac 7196 return false;
f1174f77
EC
7197
7198 for (i = 0; i < MAX_BPF_REG; i++) {
1b688a19 7199 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
f1174f77 7200 goto out_free;
f1bca824
AS
7201 }
7202
638f5b90
AS
7203 if (!stacksafe(old, cur, idmap))
7204 goto out_free;
fd978bf7
JS
7205
7206 if (!refsafe(old, cur))
7207 goto out_free;
f1174f77
EC
7208 ret = true;
7209out_free:
7210 kfree(idmap);
7211 return ret;
f1bca824
AS
7212}
7213
f4d7e40a
AS
7214static bool states_equal(struct bpf_verifier_env *env,
7215 struct bpf_verifier_state *old,
7216 struct bpf_verifier_state *cur)
7217{
7218 int i;
7219
7220 if (old->curframe != cur->curframe)
7221 return false;
7222
979d63d5
DB
7223 /* Verification state from speculative execution simulation
7224 * must never prune a non-speculative execution one.
7225 */
7226 if (old->speculative && !cur->speculative)
7227 return false;
7228
d83525ca
AS
7229 if (old->active_spin_lock != cur->active_spin_lock)
7230 return false;
7231
f4d7e40a
AS
7232 /* for states to be equal callsites have to be the same
7233 * and all frame states need to be equivalent
7234 */
7235 for (i = 0; i <= old->curframe; i++) {
7236 if (old->frame[i]->callsite != cur->frame[i]->callsite)
7237 return false;
7238 if (!func_states_equal(old->frame[i], cur->frame[i]))
7239 return false;
7240 }
7241 return true;
7242}
7243
5327ed3d
JW
7244/* Return 0 if no propagation happened. Return negative error code if error
7245 * happened. Otherwise, return the propagated bit.
7246 */
55e7f3b5
JW
7247static int propagate_liveness_reg(struct bpf_verifier_env *env,
7248 struct bpf_reg_state *reg,
7249 struct bpf_reg_state *parent_reg)
7250{
5327ed3d
JW
7251 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
7252 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
7253 int err;
7254
5327ed3d
JW
7255 /* When comes here, read flags of PARENT_REG or REG could be any of
7256 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
7257 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
7258 */
7259 if (parent_flag == REG_LIVE_READ64 ||
7260 /* Or if there is no read flag from REG. */
7261 !flag ||
7262 /* Or if the read flag from REG is the same as PARENT_REG. */
7263 parent_flag == flag)
55e7f3b5
JW
7264 return 0;
7265
5327ed3d 7266 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
7267 if (err)
7268 return err;
7269
5327ed3d 7270 return flag;
55e7f3b5
JW
7271}
7272
8e9cd9ce 7273/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
7274 * straight-line code between a state and its parent. When we arrive at an
7275 * equivalent state (jump target or such) we didn't arrive by the straight-line
7276 * code, so read marks in the state must propagate to the parent regardless
7277 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 7278 * in mark_reg_read() is for.
8e9cd9ce 7279 */
f4d7e40a
AS
7280static int propagate_liveness(struct bpf_verifier_env *env,
7281 const struct bpf_verifier_state *vstate,
7282 struct bpf_verifier_state *vparent)
dc503a8a 7283{
3f8cafa4 7284 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 7285 struct bpf_func_state *state, *parent;
3f8cafa4 7286 int i, frame, err = 0;
dc503a8a 7287
f4d7e40a
AS
7288 if (vparent->curframe != vstate->curframe) {
7289 WARN(1, "propagate_live: parent frame %d current frame %d\n",
7290 vparent->curframe, vstate->curframe);
7291 return -EFAULT;
7292 }
dc503a8a
EC
7293 /* Propagate read liveness of registers... */
7294 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 7295 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
7296 parent = vparent->frame[frame];
7297 state = vstate->frame[frame];
7298 parent_reg = parent->regs;
7299 state_reg = state->regs;
83d16312
JK
7300 /* We don't need to worry about FP liveness, it's read-only */
7301 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
7302 err = propagate_liveness_reg(env, &state_reg[i],
7303 &parent_reg[i]);
5327ed3d 7304 if (err < 0)
3f8cafa4 7305 return err;
5327ed3d
JW
7306 if (err == REG_LIVE_READ64)
7307 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 7308 }
f4d7e40a 7309
1b04aee7 7310 /* Propagate stack slots. */
f4d7e40a
AS
7311 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
7312 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
7313 parent_reg = &parent->stack[i].spilled_ptr;
7314 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
7315 err = propagate_liveness_reg(env, state_reg,
7316 parent_reg);
5327ed3d 7317 if (err < 0)
3f8cafa4 7318 return err;
dc503a8a
EC
7319 }
7320 }
5327ed3d 7321 return 0;
dc503a8a
EC
7322}
7323
a3ce685d
AS
7324/* find precise scalars in the previous equivalent state and
7325 * propagate them into the current state
7326 */
7327static int propagate_precision(struct bpf_verifier_env *env,
7328 const struct bpf_verifier_state *old)
7329{
7330 struct bpf_reg_state *state_reg;
7331 struct bpf_func_state *state;
7332 int i, err = 0;
7333
7334 state = old->frame[old->curframe];
7335 state_reg = state->regs;
7336 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
7337 if (state_reg->type != SCALAR_VALUE ||
7338 !state_reg->precise)
7339 continue;
7340 if (env->log.level & BPF_LOG_LEVEL2)
7341 verbose(env, "propagating r%d\n", i);
7342 err = mark_chain_precision(env, i);
7343 if (err < 0)
7344 return err;
7345 }
7346
7347 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
7348 if (state->stack[i].slot_type[0] != STACK_SPILL)
7349 continue;
7350 state_reg = &state->stack[i].spilled_ptr;
7351 if (state_reg->type != SCALAR_VALUE ||
7352 !state_reg->precise)
7353 continue;
7354 if (env->log.level & BPF_LOG_LEVEL2)
7355 verbose(env, "propagating fp%d\n",
7356 (-i - 1) * BPF_REG_SIZE);
7357 err = mark_chain_precision_stack(env, i);
7358 if (err < 0)
7359 return err;
7360 }
7361 return 0;
7362}
7363
2589726d
AS
7364static bool states_maybe_looping(struct bpf_verifier_state *old,
7365 struct bpf_verifier_state *cur)
7366{
7367 struct bpf_func_state *fold, *fcur;
7368 int i, fr = cur->curframe;
7369
7370 if (old->curframe != fr)
7371 return false;
7372
7373 fold = old->frame[fr];
7374 fcur = cur->frame[fr];
7375 for (i = 0; i < MAX_BPF_REG; i++)
7376 if (memcmp(&fold->regs[i], &fcur->regs[i],
7377 offsetof(struct bpf_reg_state, parent)))
7378 return false;
7379 return true;
7380}
7381
7382
58e2af8b 7383static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 7384{
58e2af8b 7385 struct bpf_verifier_state_list *new_sl;
9f4686c4 7386 struct bpf_verifier_state_list *sl, **pprev;
679c782d 7387 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 7388 int i, j, err, states_cnt = 0;
10d274e8 7389 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 7390
b5dc0163 7391 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 7392 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
7393 /* this 'insn_idx' instruction wasn't marked, so we will not
7394 * be doing state search here
7395 */
7396 return 0;
7397
2589726d
AS
7398 /* bpf progs typically have pruning point every 4 instructions
7399 * http://vger.kernel.org/bpfconf2019.html#session-1
7400 * Do not add new state for future pruning if the verifier hasn't seen
7401 * at least 2 jumps and at least 8 instructions.
7402 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
7403 * In tests that amounts to up to 50% reduction into total verifier
7404 * memory consumption and 20% verifier time speedup.
7405 */
7406 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
7407 env->insn_processed - env->prev_insn_processed >= 8)
7408 add_new_state = true;
7409
a8f500af
AS
7410 pprev = explored_state(env, insn_idx);
7411 sl = *pprev;
7412
9242b5f5
AS
7413 clean_live_states(env, insn_idx, cur);
7414
a8f500af 7415 while (sl) {
dc2a4ebc
AS
7416 states_cnt++;
7417 if (sl->state.insn_idx != insn_idx)
7418 goto next;
2589726d
AS
7419 if (sl->state.branches) {
7420 if (states_maybe_looping(&sl->state, cur) &&
7421 states_equal(env, &sl->state, cur)) {
7422 verbose_linfo(env, insn_idx, "; ");
7423 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
7424 return -EINVAL;
7425 }
7426 /* if the verifier is processing a loop, avoid adding new state
7427 * too often, since different loop iterations have distinct
7428 * states and may not help future pruning.
7429 * This threshold shouldn't be too low to make sure that
7430 * a loop with large bound will be rejected quickly.
7431 * The most abusive loop will be:
7432 * r1 += 1
7433 * if r1 < 1000000 goto pc-2
7434 * 1M insn_procssed limit / 100 == 10k peak states.
7435 * This threshold shouldn't be too high either, since states
7436 * at the end of the loop are likely to be useful in pruning.
7437 */
7438 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
7439 env->insn_processed - env->prev_insn_processed < 100)
7440 add_new_state = false;
7441 goto miss;
7442 }
638f5b90 7443 if (states_equal(env, &sl->state, cur)) {
9f4686c4 7444 sl->hit_cnt++;
f1bca824 7445 /* reached equivalent register/stack state,
dc503a8a
EC
7446 * prune the search.
7447 * Registers read by the continuation are read by us.
8e9cd9ce
EC
7448 * If we have any write marks in env->cur_state, they
7449 * will prevent corresponding reads in the continuation
7450 * from reaching our parent (an explored_state). Our
7451 * own state will get the read marks recorded, but
7452 * they'll be immediately forgotten as we're pruning
7453 * this state and will pop a new one.
f1bca824 7454 */
f4d7e40a 7455 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
7456
7457 /* if previous state reached the exit with precision and
7458 * current state is equivalent to it (except precsion marks)
7459 * the precision needs to be propagated back in
7460 * the current state.
7461 */
7462 err = err ? : push_jmp_history(env, cur);
7463 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
7464 if (err)
7465 return err;
f1bca824 7466 return 1;
dc503a8a 7467 }
2589726d
AS
7468miss:
7469 /* when new state is not going to be added do not increase miss count.
7470 * Otherwise several loop iterations will remove the state
7471 * recorded earlier. The goal of these heuristics is to have
7472 * states from some iterations of the loop (some in the beginning
7473 * and some at the end) to help pruning.
7474 */
7475 if (add_new_state)
7476 sl->miss_cnt++;
9f4686c4
AS
7477 /* heuristic to determine whether this state is beneficial
7478 * to keep checking from state equivalence point of view.
7479 * Higher numbers increase max_states_per_insn and verification time,
7480 * but do not meaningfully decrease insn_processed.
7481 */
7482 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
7483 /* the state is unlikely to be useful. Remove it to
7484 * speed up verification
7485 */
7486 *pprev = sl->next;
7487 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
7488 u32 br = sl->state.branches;
7489
7490 WARN_ONCE(br,
7491 "BUG live_done but branches_to_explore %d\n",
7492 br);
9f4686c4
AS
7493 free_verifier_state(&sl->state, false);
7494 kfree(sl);
7495 env->peak_states--;
7496 } else {
7497 /* cannot free this state, since parentage chain may
7498 * walk it later. Add it for free_list instead to
7499 * be freed at the end of verification
7500 */
7501 sl->next = env->free_list;
7502 env->free_list = sl;
7503 }
7504 sl = *pprev;
7505 continue;
7506 }
dc2a4ebc 7507next:
9f4686c4
AS
7508 pprev = &sl->next;
7509 sl = *pprev;
f1bca824
AS
7510 }
7511
06ee7115
AS
7512 if (env->max_states_per_insn < states_cnt)
7513 env->max_states_per_insn = states_cnt;
7514
ceefbc96 7515 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 7516 return push_jmp_history(env, cur);
ceefbc96 7517
2589726d 7518 if (!add_new_state)
b5dc0163 7519 return push_jmp_history(env, cur);
ceefbc96 7520
2589726d
AS
7521 /* There were no equivalent states, remember the current one.
7522 * Technically the current state is not proven to be safe yet,
f4d7e40a 7523 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 7524 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 7525 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
7526 * again on the way to bpf_exit.
7527 * When looping the sl->state.branches will be > 0 and this state
7528 * will not be considered for equivalence until branches == 0.
f1bca824 7529 */
638f5b90 7530 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
7531 if (!new_sl)
7532 return -ENOMEM;
06ee7115
AS
7533 env->total_states++;
7534 env->peak_states++;
2589726d
AS
7535 env->prev_jmps_processed = env->jmps_processed;
7536 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
7537
7538 /* add new state to the head of linked list */
679c782d
EC
7539 new = &new_sl->state;
7540 err = copy_verifier_state(new, cur);
1969db47 7541 if (err) {
679c782d 7542 free_verifier_state(new, false);
1969db47
AS
7543 kfree(new_sl);
7544 return err;
7545 }
dc2a4ebc 7546 new->insn_idx = insn_idx;
2589726d
AS
7547 WARN_ONCE(new->branches != 1,
7548 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 7549
2589726d 7550 cur->parent = new;
b5dc0163
AS
7551 cur->first_insn_idx = insn_idx;
7552 clear_jmp_history(cur);
5d839021
AS
7553 new_sl->next = *explored_state(env, insn_idx);
7554 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
7555 /* connect new state to parentage chain. Current frame needs all
7556 * registers connected. Only r6 - r9 of the callers are alive (pushed
7557 * to the stack implicitly by JITs) so in callers' frames connect just
7558 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
7559 * the state of the call instruction (with WRITTEN set), and r0 comes
7560 * from callee with its full parentage chain, anyway.
7561 */
8e9cd9ce
EC
7562 /* clear write marks in current state: the writes we did are not writes
7563 * our child did, so they don't screen off its reads from us.
7564 * (There are no read marks in current state, because reads always mark
7565 * their parent and current state never has children yet. Only
7566 * explored_states can get read marks.)
7567 */
eea1c227
AS
7568 for (j = 0; j <= cur->curframe; j++) {
7569 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
7570 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
7571 for (i = 0; i < BPF_REG_FP; i++)
7572 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
7573 }
f4d7e40a
AS
7574
7575 /* all stack frames are accessible from callee, clear them all */
7576 for (j = 0; j <= cur->curframe; j++) {
7577 struct bpf_func_state *frame = cur->frame[j];
679c782d 7578 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 7579
679c782d 7580 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 7581 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
7582 frame->stack[i].spilled_ptr.parent =
7583 &newframe->stack[i].spilled_ptr;
7584 }
f4d7e40a 7585 }
f1bca824
AS
7586 return 0;
7587}
7588
c64b7983
JS
7589/* Return true if it's OK to have the same insn return a different type. */
7590static bool reg_type_mismatch_ok(enum bpf_reg_type type)
7591{
7592 switch (type) {
7593 case PTR_TO_CTX:
7594 case PTR_TO_SOCKET:
7595 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
7596 case PTR_TO_SOCK_COMMON:
7597 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
7598 case PTR_TO_TCP_SOCK:
7599 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 7600 case PTR_TO_XDP_SOCK:
2a02759e 7601 case PTR_TO_BTF_ID:
c64b7983
JS
7602 return false;
7603 default:
7604 return true;
7605 }
7606}
7607
7608/* If an instruction was previously used with particular pointer types, then we
7609 * need to be careful to avoid cases such as the below, where it may be ok
7610 * for one branch accessing the pointer, but not ok for the other branch:
7611 *
7612 * R1 = sock_ptr
7613 * goto X;
7614 * ...
7615 * R1 = some_other_valid_ptr;
7616 * goto X;
7617 * ...
7618 * R2 = *(u32 *)(R1 + 0);
7619 */
7620static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
7621{
7622 return src != prev && (!reg_type_mismatch_ok(src) ||
7623 !reg_type_mismatch_ok(prev));
7624}
7625
58e2af8b 7626static int do_check(struct bpf_verifier_env *env)
17a52670 7627{
638f5b90 7628 struct bpf_verifier_state *state;
17a52670 7629 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 7630 struct bpf_reg_state *regs;
06ee7115 7631 int insn_cnt = env->prog->len;
17a52670 7632 bool do_print_state = false;
b5dc0163 7633 int prev_insn_idx = -1;
17a52670 7634
d9762e84
MKL
7635 env->prev_linfo = NULL;
7636
638f5b90
AS
7637 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
7638 if (!state)
7639 return -ENOMEM;
f4d7e40a 7640 state->curframe = 0;
979d63d5 7641 state->speculative = false;
2589726d 7642 state->branches = 1;
f4d7e40a
AS
7643 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
7644 if (!state->frame[0]) {
7645 kfree(state);
7646 return -ENOMEM;
7647 }
7648 env->cur_state = state;
7649 init_func_state(env, state->frame[0],
7650 BPF_MAIN_FUNC /* callsite */,
7651 0 /* frameno */,
7652 0 /* subprogno, zero == main subprog */);
c08435ec 7653
17a52670
AS
7654 for (;;) {
7655 struct bpf_insn *insn;
7656 u8 class;
7657 int err;
7658
b5dc0163 7659 env->prev_insn_idx = prev_insn_idx;
c08435ec 7660 if (env->insn_idx >= insn_cnt) {
61bd5218 7661 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 7662 env->insn_idx, insn_cnt);
17a52670
AS
7663 return -EFAULT;
7664 }
7665
c08435ec 7666 insn = &insns[env->insn_idx];
17a52670
AS
7667 class = BPF_CLASS(insn->code);
7668
06ee7115 7669 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
7670 verbose(env,
7671 "BPF program is too large. Processed %d insn\n",
06ee7115 7672 env->insn_processed);
17a52670
AS
7673 return -E2BIG;
7674 }
7675
c08435ec 7676 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
7677 if (err < 0)
7678 return err;
7679 if (err == 1) {
7680 /* found equivalent state, can prune the search */
06ee7115 7681 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 7682 if (do_print_state)
979d63d5
DB
7683 verbose(env, "\nfrom %d to %d%s: safe\n",
7684 env->prev_insn_idx, env->insn_idx,
7685 env->cur_state->speculative ?
7686 " (speculative execution)" : "");
f1bca824 7687 else
c08435ec 7688 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
7689 }
7690 goto process_bpf_exit;
7691 }
7692
c3494801
AS
7693 if (signal_pending(current))
7694 return -EAGAIN;
7695
3c2ce60b
DB
7696 if (need_resched())
7697 cond_resched();
7698
06ee7115
AS
7699 if (env->log.level & BPF_LOG_LEVEL2 ||
7700 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
7701 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 7702 verbose(env, "%d:", env->insn_idx);
c5fc9692 7703 else
979d63d5
DB
7704 verbose(env, "\nfrom %d to %d%s:",
7705 env->prev_insn_idx, env->insn_idx,
7706 env->cur_state->speculative ?
7707 " (speculative execution)" : "");
f4d7e40a 7708 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
7709 do_print_state = false;
7710 }
7711
06ee7115 7712 if (env->log.level & BPF_LOG_LEVEL) {
7105e828
DB
7713 const struct bpf_insn_cbs cbs = {
7714 .cb_print = verbose,
abe08840 7715 .private_data = env,
7105e828
DB
7716 };
7717
c08435ec
DB
7718 verbose_linfo(env, env->insn_idx, "; ");
7719 verbose(env, "%d: ", env->insn_idx);
abe08840 7720 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
7721 }
7722
cae1927c 7723 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
7724 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
7725 env->prev_insn_idx);
cae1927c
JK
7726 if (err)
7727 return err;
7728 }
13a27dfc 7729
638f5b90 7730 regs = cur_regs(env);
c08435ec 7731 env->insn_aux_data[env->insn_idx].seen = true;
b5dc0163 7732 prev_insn_idx = env->insn_idx;
fd978bf7 7733
17a52670 7734 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 7735 err = check_alu_op(env, insn);
17a52670
AS
7736 if (err)
7737 return err;
7738
7739 } else if (class == BPF_LDX) {
3df126f3 7740 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
7741
7742 /* check for reserved fields is already done */
7743
17a52670 7744 /* check src operand */
dc503a8a 7745 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7746 if (err)
7747 return err;
7748
dc503a8a 7749 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7750 if (err)
7751 return err;
7752
725f9dcd
AS
7753 src_reg_type = regs[insn->src_reg].type;
7754
17a52670
AS
7755 /* check that memory (src_reg + off) is readable,
7756 * the state of dst_reg will be updated by this func
7757 */
c08435ec
DB
7758 err = check_mem_access(env, env->insn_idx, insn->src_reg,
7759 insn->off, BPF_SIZE(insn->code),
7760 BPF_READ, insn->dst_reg, false);
17a52670
AS
7761 if (err)
7762 return err;
7763
c08435ec 7764 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
7765
7766 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
7767 /* saw a valid insn
7768 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 7769 * save type to validate intersecting paths
9bac3d6d 7770 */
3df126f3 7771 *prev_src_type = src_reg_type;
9bac3d6d 7772
c64b7983 7773 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
7774 /* ABuser program is trying to use the same insn
7775 * dst_reg = *(u32*) (src_reg + off)
7776 * with different pointer types:
7777 * src_reg == ctx in one branch and
7778 * src_reg == stack|map in some other branch.
7779 * Reject it.
7780 */
61bd5218 7781 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
7782 return -EINVAL;
7783 }
7784
17a52670 7785 } else if (class == BPF_STX) {
3df126f3 7786 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 7787
17a52670 7788 if (BPF_MODE(insn->code) == BPF_XADD) {
c08435ec 7789 err = check_xadd(env, env->insn_idx, insn);
17a52670
AS
7790 if (err)
7791 return err;
c08435ec 7792 env->insn_idx++;
17a52670
AS
7793 continue;
7794 }
7795
17a52670 7796 /* check src1 operand */
dc503a8a 7797 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7798 if (err)
7799 return err;
7800 /* check src2 operand */
dc503a8a 7801 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7802 if (err)
7803 return err;
7804
d691f9e8
AS
7805 dst_reg_type = regs[insn->dst_reg].type;
7806
17a52670 7807 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
7808 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7809 insn->off, BPF_SIZE(insn->code),
7810 BPF_WRITE, insn->src_reg, false);
17a52670
AS
7811 if (err)
7812 return err;
7813
c08435ec 7814 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
7815
7816 if (*prev_dst_type == NOT_INIT) {
7817 *prev_dst_type = dst_reg_type;
c64b7983 7818 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 7819 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
7820 return -EINVAL;
7821 }
7822
17a52670
AS
7823 } else if (class == BPF_ST) {
7824 if (BPF_MODE(insn->code) != BPF_MEM ||
7825 insn->src_reg != BPF_REG_0) {
61bd5218 7826 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
7827 return -EINVAL;
7828 }
7829 /* check src operand */
dc503a8a 7830 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7831 if (err)
7832 return err;
7833
f37a8cb8 7834 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 7835 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
7836 insn->dst_reg,
7837 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
7838 return -EACCES;
7839 }
7840
17a52670 7841 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
7842 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7843 insn->off, BPF_SIZE(insn->code),
7844 BPF_WRITE, -1, false);
17a52670
AS
7845 if (err)
7846 return err;
7847
092ed096 7848 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
7849 u8 opcode = BPF_OP(insn->code);
7850
2589726d 7851 env->jmps_processed++;
17a52670
AS
7852 if (opcode == BPF_CALL) {
7853 if (BPF_SRC(insn->code) != BPF_K ||
7854 insn->off != 0 ||
f4d7e40a
AS
7855 (insn->src_reg != BPF_REG_0 &&
7856 insn->src_reg != BPF_PSEUDO_CALL) ||
092ed096
JW
7857 insn->dst_reg != BPF_REG_0 ||
7858 class == BPF_JMP32) {
61bd5218 7859 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
7860 return -EINVAL;
7861 }
7862
d83525ca
AS
7863 if (env->cur_state->active_spin_lock &&
7864 (insn->src_reg == BPF_PSEUDO_CALL ||
7865 insn->imm != BPF_FUNC_spin_unlock)) {
7866 verbose(env, "function calls are not allowed while holding a lock\n");
7867 return -EINVAL;
7868 }
f4d7e40a 7869 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 7870 err = check_func_call(env, insn, &env->insn_idx);
f4d7e40a 7871 else
c08435ec 7872 err = check_helper_call(env, insn->imm, env->insn_idx);
17a52670
AS
7873 if (err)
7874 return err;
7875
7876 } else if (opcode == BPF_JA) {
7877 if (BPF_SRC(insn->code) != BPF_K ||
7878 insn->imm != 0 ||
7879 insn->src_reg != BPF_REG_0 ||
092ed096
JW
7880 insn->dst_reg != BPF_REG_0 ||
7881 class == BPF_JMP32) {
61bd5218 7882 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
7883 return -EINVAL;
7884 }
7885
c08435ec 7886 env->insn_idx += insn->off + 1;
17a52670
AS
7887 continue;
7888
7889 } else if (opcode == BPF_EXIT) {
7890 if (BPF_SRC(insn->code) != BPF_K ||
7891 insn->imm != 0 ||
7892 insn->src_reg != BPF_REG_0 ||
092ed096
JW
7893 insn->dst_reg != BPF_REG_0 ||
7894 class == BPF_JMP32) {
61bd5218 7895 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
7896 return -EINVAL;
7897 }
7898
d83525ca
AS
7899 if (env->cur_state->active_spin_lock) {
7900 verbose(env, "bpf_spin_unlock is missing\n");
7901 return -EINVAL;
7902 }
7903
f4d7e40a
AS
7904 if (state->curframe) {
7905 /* exit from nested function */
c08435ec 7906 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
7907 if (err)
7908 return err;
7909 do_print_state = true;
7910 continue;
7911 }
7912
fd978bf7
JS
7913 err = check_reference_leak(env);
7914 if (err)
7915 return err;
7916
17a52670
AS
7917 /* eBPF calling convetion is such that R0 is used
7918 * to return the value from eBPF program.
7919 * Make sure that it's readable at this time
7920 * of bpf_exit, which means that program wrote
7921 * something into it earlier
7922 */
dc503a8a 7923 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
17a52670
AS
7924 if (err)
7925 return err;
7926
1be7f75d 7927 if (is_pointer_value(env, BPF_REG_0)) {
61bd5218 7928 verbose(env, "R0 leaks addr as return value\n");
1be7f75d
AS
7929 return -EACCES;
7930 }
7931
390ee7e2
AS
7932 err = check_return_code(env);
7933 if (err)
7934 return err;
f1bca824 7935process_bpf_exit:
2589726d 7936 update_branch_counts(env, env->cur_state);
b5dc0163 7937 err = pop_stack(env, &prev_insn_idx,
c08435ec 7938 &env->insn_idx);
638f5b90
AS
7939 if (err < 0) {
7940 if (err != -ENOENT)
7941 return err;
17a52670
AS
7942 break;
7943 } else {
7944 do_print_state = true;
7945 continue;
7946 }
7947 } else {
c08435ec 7948 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
7949 if (err)
7950 return err;
7951 }
7952 } else if (class == BPF_LD) {
7953 u8 mode = BPF_MODE(insn->code);
7954
7955 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
7956 err = check_ld_abs(env, insn);
7957 if (err)
7958 return err;
7959
17a52670
AS
7960 } else if (mode == BPF_IMM) {
7961 err = check_ld_imm(env, insn);
7962 if (err)
7963 return err;
7964
c08435ec
DB
7965 env->insn_idx++;
7966 env->insn_aux_data[env->insn_idx].seen = true;
17a52670 7967 } else {
61bd5218 7968 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
7969 return -EINVAL;
7970 }
7971 } else {
61bd5218 7972 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
7973 return -EINVAL;
7974 }
7975
c08435ec 7976 env->insn_idx++;
17a52670
AS
7977 }
7978
9c8105bd 7979 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
17a52670
AS
7980 return 0;
7981}
7982
56f668df
MKL
7983static int check_map_prealloc(struct bpf_map *map)
7984{
7985 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
7986 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7987 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
7988 !(map->map_flags & BPF_F_NO_PREALLOC);
7989}
7990
d83525ca
AS
7991static bool is_tracing_prog_type(enum bpf_prog_type type)
7992{
7993 switch (type) {
7994 case BPF_PROG_TYPE_KPROBE:
7995 case BPF_PROG_TYPE_TRACEPOINT:
7996 case BPF_PROG_TYPE_PERF_EVENT:
7997 case BPF_PROG_TYPE_RAW_TRACEPOINT:
7998 return true;
7999 default:
8000 return false;
8001 }
8002}
8003
61bd5218
JK
8004static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8005 struct bpf_map *map,
fdc15d38
AS
8006 struct bpf_prog *prog)
8007
8008{
56f668df
MKL
8009 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
8010 * preallocated hash maps, since doing memory allocation
8011 * in overflow_handler can crash depending on where nmi got
8012 * triggered.
8013 */
8014 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
8015 if (!check_map_prealloc(map)) {
61bd5218 8016 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
8017 return -EINVAL;
8018 }
8019 if (map->inner_map_meta &&
8020 !check_map_prealloc(map->inner_map_meta)) {
61bd5218 8021 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
56f668df
MKL
8022 return -EINVAL;
8023 }
fdc15d38 8024 }
a3884572 8025
d83525ca
AS
8026 if ((is_tracing_prog_type(prog->type) ||
8027 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
8028 map_value_has_spin_lock(map)) {
8029 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
8030 return -EINVAL;
8031 }
8032
a3884572 8033 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 8034 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
8035 verbose(env, "offload device mismatch between prog and map\n");
8036 return -EINVAL;
8037 }
8038
fdc15d38
AS
8039 return 0;
8040}
8041
b741f163
RG
8042static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
8043{
8044 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
8045 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
8046}
8047
0246e64d
AS
8048/* look for pseudo eBPF instructions that access map FDs and
8049 * replace them with actual map pointers
8050 */
58e2af8b 8051static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
8052{
8053 struct bpf_insn *insn = env->prog->insnsi;
8054 int insn_cnt = env->prog->len;
fdc15d38 8055 int i, j, err;
0246e64d 8056
f1f7714e 8057 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
8058 if (err)
8059 return err;
8060
0246e64d 8061 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 8062 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 8063 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 8064 verbose(env, "BPF_LDX uses reserved fields\n");
9bac3d6d
AS
8065 return -EINVAL;
8066 }
8067
d691f9e8
AS
8068 if (BPF_CLASS(insn->code) == BPF_STX &&
8069 ((BPF_MODE(insn->code) != BPF_MEM &&
8070 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
61bd5218 8071 verbose(env, "BPF_STX uses reserved fields\n");
d691f9e8
AS
8072 return -EINVAL;
8073 }
8074
0246e64d 8075 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 8076 struct bpf_insn_aux_data *aux;
0246e64d
AS
8077 struct bpf_map *map;
8078 struct fd f;
d8eca5bb 8079 u64 addr;
0246e64d
AS
8080
8081 if (i == insn_cnt - 1 || insn[1].code != 0 ||
8082 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
8083 insn[1].off != 0) {
61bd5218 8084 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
8085 return -EINVAL;
8086 }
8087
d8eca5bb 8088 if (insn[0].src_reg == 0)
0246e64d
AS
8089 /* valid generic load 64-bit imm */
8090 goto next_insn;
8091
d8eca5bb
DB
8092 /* In final convert_pseudo_ld_imm64() step, this is
8093 * converted into regular 64-bit imm load insn.
8094 */
8095 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
8096 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
8097 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
8098 insn[1].imm != 0)) {
8099 verbose(env,
8100 "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
8101 return -EINVAL;
8102 }
8103
20182390 8104 f = fdget(insn[0].imm);
c2101297 8105 map = __bpf_map_get(f);
0246e64d 8106 if (IS_ERR(map)) {
61bd5218 8107 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 8108 insn[0].imm);
0246e64d
AS
8109 return PTR_ERR(map);
8110 }
8111
61bd5218 8112 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
8113 if (err) {
8114 fdput(f);
8115 return err;
8116 }
8117
d8eca5bb
DB
8118 aux = &env->insn_aux_data[i];
8119 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8120 addr = (unsigned long)map;
8121 } else {
8122 u32 off = insn[1].imm;
8123
8124 if (off >= BPF_MAX_VAR_OFF) {
8125 verbose(env, "direct value offset of %u is not allowed\n", off);
8126 fdput(f);
8127 return -EINVAL;
8128 }
8129
8130 if (!map->ops->map_direct_value_addr) {
8131 verbose(env, "no direct value access support for this map type\n");
8132 fdput(f);
8133 return -EINVAL;
8134 }
8135
8136 err = map->ops->map_direct_value_addr(map, &addr, off);
8137 if (err) {
8138 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
8139 map->value_size, off);
8140 fdput(f);
8141 return err;
8142 }
8143
8144 aux->map_off = off;
8145 addr += off;
8146 }
8147
8148 insn[0].imm = (u32)addr;
8149 insn[1].imm = addr >> 32;
0246e64d
AS
8150
8151 /* check whether we recorded this map already */
d8eca5bb 8152 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 8153 if (env->used_maps[j] == map) {
d8eca5bb 8154 aux->map_index = j;
0246e64d
AS
8155 fdput(f);
8156 goto next_insn;
8157 }
d8eca5bb 8158 }
0246e64d
AS
8159
8160 if (env->used_map_cnt >= MAX_USED_MAPS) {
8161 fdput(f);
8162 return -E2BIG;
8163 }
8164
0246e64d
AS
8165 /* hold the map. If the program is rejected by verifier,
8166 * the map will be released by release_maps() or it
8167 * will be used by the valid program until it's unloaded
ab7f5bf0 8168 * and all maps are released in free_used_maps()
0246e64d 8169 */
92117d84
AS
8170 map = bpf_map_inc(map, false);
8171 if (IS_ERR(map)) {
8172 fdput(f);
8173 return PTR_ERR(map);
8174 }
d8eca5bb
DB
8175
8176 aux->map_index = env->used_map_cnt;
92117d84
AS
8177 env->used_maps[env->used_map_cnt++] = map;
8178
b741f163 8179 if (bpf_map_is_cgroup_storage(map) &&
de9cbbaa 8180 bpf_cgroup_storage_assign(env->prog, map)) {
b741f163 8181 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
8182 fdput(f);
8183 return -EBUSY;
8184 }
8185
0246e64d
AS
8186 fdput(f);
8187next_insn:
8188 insn++;
8189 i++;
5e581dad
DB
8190 continue;
8191 }
8192
8193 /* Basic sanity check before we invest more work here. */
8194 if (!bpf_opcode_in_insntable(insn->code)) {
8195 verbose(env, "unknown opcode %02x\n", insn->code);
8196 return -EINVAL;
0246e64d
AS
8197 }
8198 }
8199
8200 /* now all pseudo BPF_LD_IMM64 instructions load valid
8201 * 'struct bpf_map *' into a register instead of user map_fd.
8202 * These pointers will be used later by verifier to validate map access.
8203 */
8204 return 0;
8205}
8206
8207/* drop refcnt of maps used by the rejected program */
58e2af8b 8208static void release_maps(struct bpf_verifier_env *env)
0246e64d 8209{
8bad74f9 8210 enum bpf_cgroup_storage_type stype;
0246e64d
AS
8211 int i;
8212
8bad74f9
RG
8213 for_each_cgroup_storage_type(stype) {
8214 if (!env->prog->aux->cgroup_storage[stype])
8215 continue;
de9cbbaa 8216 bpf_cgroup_storage_release(env->prog,
8bad74f9
RG
8217 env->prog->aux->cgroup_storage[stype]);
8218 }
de9cbbaa 8219
0246e64d
AS
8220 for (i = 0; i < env->used_map_cnt; i++)
8221 bpf_map_put(env->used_maps[i]);
8222}
8223
8224/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 8225static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
8226{
8227 struct bpf_insn *insn = env->prog->insnsi;
8228 int insn_cnt = env->prog->len;
8229 int i;
8230
8231 for (i = 0; i < insn_cnt; i++, insn++)
8232 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
8233 insn->src_reg = 0;
8234}
8235
8041902d
AS
8236/* single env->prog->insni[off] instruction was replaced with the range
8237 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
8238 * [0, off) and [off, end) to new locations, so the patched range stays zero
8239 */
b325fbca
JW
8240static int adjust_insn_aux_data(struct bpf_verifier_env *env,
8241 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
8242{
8243 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca
JW
8244 struct bpf_insn *insn = new_prog->insnsi;
8245 u32 prog_len;
c131187d 8246 int i;
8041902d 8247
b325fbca
JW
8248 /* aux info at OFF always needs adjustment, no matter fast path
8249 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
8250 * original insn at old prog.
8251 */
8252 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
8253
8041902d
AS
8254 if (cnt == 1)
8255 return 0;
b325fbca 8256 prog_len = new_prog->len;
fad953ce
KC
8257 new_data = vzalloc(array_size(prog_len,
8258 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
8259 if (!new_data)
8260 return -ENOMEM;
8261 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
8262 memcpy(new_data + off + cnt - 1, old_data + off,
8263 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 8264 for (i = off; i < off + cnt - 1; i++) {
c131187d 8265 new_data[i].seen = true;
b325fbca
JW
8266 new_data[i].zext_dst = insn_has_def32(env, insn + i);
8267 }
8041902d
AS
8268 env->insn_aux_data = new_data;
8269 vfree(old_data);
8270 return 0;
8271}
8272
cc8b0b92
AS
8273static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
8274{
8275 int i;
8276
8277 if (len == 1)
8278 return;
4cb3d99c
JW
8279 /* NOTE: fake 'exit' subprog should be updated as well. */
8280 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 8281 if (env->subprog_info[i].start <= off)
cc8b0b92 8282 continue;
9c8105bd 8283 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
8284 }
8285}
8286
8041902d
AS
8287static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
8288 const struct bpf_insn *patch, u32 len)
8289{
8290 struct bpf_prog *new_prog;
8291
8292 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
8293 if (IS_ERR(new_prog)) {
8294 if (PTR_ERR(new_prog) == -ERANGE)
8295 verbose(env,
8296 "insn %d cannot be patched due to 16-bit range\n",
8297 env->insn_aux_data[off].orig_idx);
8041902d 8298 return NULL;
4f73379e 8299 }
b325fbca 8300 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 8301 return NULL;
cc8b0b92 8302 adjust_subprog_starts(env, off, len);
8041902d
AS
8303 return new_prog;
8304}
8305
52875a04
JK
8306static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
8307 u32 off, u32 cnt)
8308{
8309 int i, j;
8310
8311 /* find first prog starting at or after off (first to remove) */
8312 for (i = 0; i < env->subprog_cnt; i++)
8313 if (env->subprog_info[i].start >= off)
8314 break;
8315 /* find first prog starting at or after off + cnt (first to stay) */
8316 for (j = i; j < env->subprog_cnt; j++)
8317 if (env->subprog_info[j].start >= off + cnt)
8318 break;
8319 /* if j doesn't start exactly at off + cnt, we are just removing
8320 * the front of previous prog
8321 */
8322 if (env->subprog_info[j].start != off + cnt)
8323 j--;
8324
8325 if (j > i) {
8326 struct bpf_prog_aux *aux = env->prog->aux;
8327 int move;
8328
8329 /* move fake 'exit' subprog as well */
8330 move = env->subprog_cnt + 1 - j;
8331
8332 memmove(env->subprog_info + i,
8333 env->subprog_info + j,
8334 sizeof(*env->subprog_info) * move);
8335 env->subprog_cnt -= j - i;
8336
8337 /* remove func_info */
8338 if (aux->func_info) {
8339 move = aux->func_info_cnt - j;
8340
8341 memmove(aux->func_info + i,
8342 aux->func_info + j,
8343 sizeof(*aux->func_info) * move);
8344 aux->func_info_cnt -= j - i;
8345 /* func_info->insn_off is set after all code rewrites,
8346 * in adjust_btf_func() - no need to adjust
8347 */
8348 }
8349 } else {
8350 /* convert i from "first prog to remove" to "first to adjust" */
8351 if (env->subprog_info[i].start == off)
8352 i++;
8353 }
8354
8355 /* update fake 'exit' subprog as well */
8356 for (; i <= env->subprog_cnt; i++)
8357 env->subprog_info[i].start -= cnt;
8358
8359 return 0;
8360}
8361
8362static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
8363 u32 cnt)
8364{
8365 struct bpf_prog *prog = env->prog;
8366 u32 i, l_off, l_cnt, nr_linfo;
8367 struct bpf_line_info *linfo;
8368
8369 nr_linfo = prog->aux->nr_linfo;
8370 if (!nr_linfo)
8371 return 0;
8372
8373 linfo = prog->aux->linfo;
8374
8375 /* find first line info to remove, count lines to be removed */
8376 for (i = 0; i < nr_linfo; i++)
8377 if (linfo[i].insn_off >= off)
8378 break;
8379
8380 l_off = i;
8381 l_cnt = 0;
8382 for (; i < nr_linfo; i++)
8383 if (linfo[i].insn_off < off + cnt)
8384 l_cnt++;
8385 else
8386 break;
8387
8388 /* First live insn doesn't match first live linfo, it needs to "inherit"
8389 * last removed linfo. prog is already modified, so prog->len == off
8390 * means no live instructions after (tail of the program was removed).
8391 */
8392 if (prog->len != off && l_cnt &&
8393 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
8394 l_cnt--;
8395 linfo[--i].insn_off = off + cnt;
8396 }
8397
8398 /* remove the line info which refer to the removed instructions */
8399 if (l_cnt) {
8400 memmove(linfo + l_off, linfo + i,
8401 sizeof(*linfo) * (nr_linfo - i));
8402
8403 prog->aux->nr_linfo -= l_cnt;
8404 nr_linfo = prog->aux->nr_linfo;
8405 }
8406
8407 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
8408 for (i = l_off; i < nr_linfo; i++)
8409 linfo[i].insn_off -= cnt;
8410
8411 /* fix up all subprogs (incl. 'exit') which start >= off */
8412 for (i = 0; i <= env->subprog_cnt; i++)
8413 if (env->subprog_info[i].linfo_idx > l_off) {
8414 /* program may have started in the removed region but
8415 * may not be fully removed
8416 */
8417 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
8418 env->subprog_info[i].linfo_idx -= l_cnt;
8419 else
8420 env->subprog_info[i].linfo_idx = l_off;
8421 }
8422
8423 return 0;
8424}
8425
8426static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
8427{
8428 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8429 unsigned int orig_prog_len = env->prog->len;
8430 int err;
8431
08ca90af
JK
8432 if (bpf_prog_is_dev_bound(env->prog->aux))
8433 bpf_prog_offload_remove_insns(env, off, cnt);
8434
52875a04
JK
8435 err = bpf_remove_insns(env->prog, off, cnt);
8436 if (err)
8437 return err;
8438
8439 err = adjust_subprog_starts_after_remove(env, off, cnt);
8440 if (err)
8441 return err;
8442
8443 err = bpf_adj_linfo_after_remove(env, off, cnt);
8444 if (err)
8445 return err;
8446
8447 memmove(aux_data + off, aux_data + off + cnt,
8448 sizeof(*aux_data) * (orig_prog_len - off - cnt));
8449
8450 return 0;
8451}
8452
2a5418a1
DB
8453/* The verifier does more data flow analysis than llvm and will not
8454 * explore branches that are dead at run time. Malicious programs can
8455 * have dead code too. Therefore replace all dead at-run-time code
8456 * with 'ja -1'.
8457 *
8458 * Just nops are not optimal, e.g. if they would sit at the end of the
8459 * program and through another bug we would manage to jump there, then
8460 * we'd execute beyond program memory otherwise. Returning exception
8461 * code also wouldn't work since we can have subprogs where the dead
8462 * code could be located.
c131187d
AS
8463 */
8464static void sanitize_dead_code(struct bpf_verifier_env *env)
8465{
8466 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 8467 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
8468 struct bpf_insn *insn = env->prog->insnsi;
8469 const int insn_cnt = env->prog->len;
8470 int i;
8471
8472 for (i = 0; i < insn_cnt; i++) {
8473 if (aux_data[i].seen)
8474 continue;
2a5418a1 8475 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
8476 }
8477}
8478
e2ae4ca2
JK
8479static bool insn_is_cond_jump(u8 code)
8480{
8481 u8 op;
8482
092ed096
JW
8483 if (BPF_CLASS(code) == BPF_JMP32)
8484 return true;
8485
e2ae4ca2
JK
8486 if (BPF_CLASS(code) != BPF_JMP)
8487 return false;
8488
8489 op = BPF_OP(code);
8490 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
8491}
8492
8493static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
8494{
8495 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8496 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8497 struct bpf_insn *insn = env->prog->insnsi;
8498 const int insn_cnt = env->prog->len;
8499 int i;
8500
8501 for (i = 0; i < insn_cnt; i++, insn++) {
8502 if (!insn_is_cond_jump(insn->code))
8503 continue;
8504
8505 if (!aux_data[i + 1].seen)
8506 ja.off = insn->off;
8507 else if (!aux_data[i + 1 + insn->off].seen)
8508 ja.off = 0;
8509 else
8510 continue;
8511
08ca90af
JK
8512 if (bpf_prog_is_dev_bound(env->prog->aux))
8513 bpf_prog_offload_replace_insn(env, i, &ja);
8514
e2ae4ca2
JK
8515 memcpy(insn, &ja, sizeof(ja));
8516 }
8517}
8518
52875a04
JK
8519static int opt_remove_dead_code(struct bpf_verifier_env *env)
8520{
8521 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8522 int insn_cnt = env->prog->len;
8523 int i, err;
8524
8525 for (i = 0; i < insn_cnt; i++) {
8526 int j;
8527
8528 j = 0;
8529 while (i + j < insn_cnt && !aux_data[i + j].seen)
8530 j++;
8531 if (!j)
8532 continue;
8533
8534 err = verifier_remove_insns(env, i, j);
8535 if (err)
8536 return err;
8537 insn_cnt = env->prog->len;
8538 }
8539
8540 return 0;
8541}
8542
a1b14abc
JK
8543static int opt_remove_nops(struct bpf_verifier_env *env)
8544{
8545 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8546 struct bpf_insn *insn = env->prog->insnsi;
8547 int insn_cnt = env->prog->len;
8548 int i, err;
8549
8550 for (i = 0; i < insn_cnt; i++) {
8551 if (memcmp(&insn[i], &ja, sizeof(ja)))
8552 continue;
8553
8554 err = verifier_remove_insns(env, i, 1);
8555 if (err)
8556 return err;
8557 insn_cnt--;
8558 i--;
8559 }
8560
8561 return 0;
8562}
8563
d6c2308c
JW
8564static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
8565 const union bpf_attr *attr)
a4b1d3c1 8566{
d6c2308c 8567 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 8568 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 8569 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 8570 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 8571 struct bpf_prog *new_prog;
d6c2308c 8572 bool rnd_hi32;
a4b1d3c1 8573
d6c2308c 8574 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 8575 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
8576 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
8577 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
8578 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
8579 for (i = 0; i < len; i++) {
8580 int adj_idx = i + delta;
8581 struct bpf_insn insn;
8582
d6c2308c
JW
8583 insn = insns[adj_idx];
8584 if (!aux[adj_idx].zext_dst) {
8585 u8 code, class;
8586 u32 imm_rnd;
8587
8588 if (!rnd_hi32)
8589 continue;
8590
8591 code = insn.code;
8592 class = BPF_CLASS(code);
8593 if (insn_no_def(&insn))
8594 continue;
8595
8596 /* NOTE: arg "reg" (the fourth one) is only used for
8597 * BPF_STX which has been ruled out in above
8598 * check, it is safe to pass NULL here.
8599 */
8600 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
8601 if (class == BPF_LD &&
8602 BPF_MODE(code) == BPF_IMM)
8603 i++;
8604 continue;
8605 }
8606
8607 /* ctx load could be transformed into wider load. */
8608 if (class == BPF_LDX &&
8609 aux[adj_idx].ptr_type == PTR_TO_CTX)
8610 continue;
8611
8612 imm_rnd = get_random_int();
8613 rnd_hi32_patch[0] = insn;
8614 rnd_hi32_patch[1].imm = imm_rnd;
8615 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
8616 patch = rnd_hi32_patch;
8617 patch_len = 4;
8618 goto apply_patch_buffer;
8619 }
8620
8621 if (!bpf_jit_needs_zext())
a4b1d3c1
JW
8622 continue;
8623
a4b1d3c1
JW
8624 zext_patch[0] = insn;
8625 zext_patch[1].dst_reg = insn.dst_reg;
8626 zext_patch[1].src_reg = insn.dst_reg;
d6c2308c
JW
8627 patch = zext_patch;
8628 patch_len = 2;
8629apply_patch_buffer:
8630 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
8631 if (!new_prog)
8632 return -ENOMEM;
8633 env->prog = new_prog;
8634 insns = new_prog->insnsi;
8635 aux = env->insn_aux_data;
d6c2308c 8636 delta += patch_len - 1;
a4b1d3c1
JW
8637 }
8638
8639 return 0;
8640}
8641
c64b7983
JS
8642/* convert load instructions that access fields of a context type into a
8643 * sequence of instructions that access fields of the underlying structure:
8644 * struct __sk_buff -> struct sk_buff
8645 * struct bpf_sock_ops -> struct sock
9bac3d6d 8646 */
58e2af8b 8647static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 8648{
00176a34 8649 const struct bpf_verifier_ops *ops = env->ops;
f96da094 8650 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 8651 const int insn_cnt = env->prog->len;
36bbef52 8652 struct bpf_insn insn_buf[16], *insn;
46f53a65 8653 u32 target_size, size_default, off;
9bac3d6d 8654 struct bpf_prog *new_prog;
d691f9e8 8655 enum bpf_access_type type;
f96da094 8656 bool is_narrower_load;
9bac3d6d 8657
b09928b9
DB
8658 if (ops->gen_prologue || env->seen_direct_write) {
8659 if (!ops->gen_prologue) {
8660 verbose(env, "bpf verifier is misconfigured\n");
8661 return -EINVAL;
8662 }
36bbef52
DB
8663 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
8664 env->prog);
8665 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 8666 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
8667 return -EINVAL;
8668 } else if (cnt) {
8041902d 8669 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
8670 if (!new_prog)
8671 return -ENOMEM;
8041902d 8672
36bbef52 8673 env->prog = new_prog;
3df126f3 8674 delta += cnt - 1;
36bbef52
DB
8675 }
8676 }
8677
c64b7983 8678 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
8679 return 0;
8680
3df126f3 8681 insn = env->prog->insnsi + delta;
36bbef52 8682
9bac3d6d 8683 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
8684 bpf_convert_ctx_access_t convert_ctx_access;
8685
62c7989b
DB
8686 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
8687 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
8688 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 8689 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 8690 type = BPF_READ;
62c7989b
DB
8691 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
8692 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
8693 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 8694 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
8695 type = BPF_WRITE;
8696 else
9bac3d6d
AS
8697 continue;
8698
af86ca4e
AS
8699 if (type == BPF_WRITE &&
8700 env->insn_aux_data[i + delta].sanitize_stack_off) {
8701 struct bpf_insn patch[] = {
8702 /* Sanitize suspicious stack slot with zero.
8703 * There are no memory dependencies for this store,
8704 * since it's only using frame pointer and immediate
8705 * constant of zero
8706 */
8707 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
8708 env->insn_aux_data[i + delta].sanitize_stack_off,
8709 0),
8710 /* the original STX instruction will immediately
8711 * overwrite the same stack slot with appropriate value
8712 */
8713 *insn,
8714 };
8715
8716 cnt = ARRAY_SIZE(patch);
8717 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
8718 if (!new_prog)
8719 return -ENOMEM;
8720
8721 delta += cnt - 1;
8722 env->prog = new_prog;
8723 insn = new_prog->insnsi + i + delta;
8724 continue;
8725 }
8726
c64b7983
JS
8727 switch (env->insn_aux_data[i + delta].ptr_type) {
8728 case PTR_TO_CTX:
8729 if (!ops->convert_ctx_access)
8730 continue;
8731 convert_ctx_access = ops->convert_ctx_access;
8732 break;
8733 case PTR_TO_SOCKET:
46f8bc92 8734 case PTR_TO_SOCK_COMMON:
c64b7983
JS
8735 convert_ctx_access = bpf_sock_convert_ctx_access;
8736 break;
655a51e5
MKL
8737 case PTR_TO_TCP_SOCK:
8738 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
8739 break;
fada7fdc
JL
8740 case PTR_TO_XDP_SOCK:
8741 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
8742 break;
2a02759e
AS
8743 case PTR_TO_BTF_ID:
8744 if (type == BPF_WRITE) {
8745 verbose(env, "Writes through BTF pointers are not allowed\n");
8746 return -EINVAL;
8747 }
8748 insn->code = BPF_LDX | BPF_PROBE_MEM | BPF_SIZE((insn)->code);
3dec541b 8749 env->prog->aux->num_exentries++;
2a02759e 8750 continue;
c64b7983 8751 default:
9bac3d6d 8752 continue;
c64b7983 8753 }
9bac3d6d 8754
31fd8581 8755 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 8756 size = BPF_LDST_BYTES(insn);
31fd8581
YS
8757
8758 /* If the read access is a narrower load of the field,
8759 * convert to a 4/8-byte load, to minimum program type specific
8760 * convert_ctx_access changes. If conversion is successful,
8761 * we will apply proper mask to the result.
8762 */
f96da094 8763 is_narrower_load = size < ctx_field_size;
46f53a65
AI
8764 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
8765 off = insn->off;
31fd8581 8766 if (is_narrower_load) {
f96da094
DB
8767 u8 size_code;
8768
8769 if (type == BPF_WRITE) {
61bd5218 8770 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
8771 return -EINVAL;
8772 }
31fd8581 8773
f96da094 8774 size_code = BPF_H;
31fd8581
YS
8775 if (ctx_field_size == 4)
8776 size_code = BPF_W;
8777 else if (ctx_field_size == 8)
8778 size_code = BPF_DW;
f96da094 8779
bc23105c 8780 insn->off = off & ~(size_default - 1);
31fd8581
YS
8781 insn->code = BPF_LDX | BPF_MEM | size_code;
8782 }
f96da094
DB
8783
8784 target_size = 0;
c64b7983
JS
8785 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
8786 &target_size);
f96da094
DB
8787 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
8788 (ctx_field_size && !target_size)) {
61bd5218 8789 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
8790 return -EINVAL;
8791 }
f96da094
DB
8792
8793 if (is_narrower_load && size < target_size) {
d895a0f1
IL
8794 u8 shift = bpf_ctx_narrow_access_offset(
8795 off, size, size_default) * 8;
46f53a65
AI
8796 if (ctx_field_size <= 4) {
8797 if (shift)
8798 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
8799 insn->dst_reg,
8800 shift);
31fd8581 8801 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 8802 (1 << size * 8) - 1);
46f53a65
AI
8803 } else {
8804 if (shift)
8805 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
8806 insn->dst_reg,
8807 shift);
31fd8581 8808 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 8809 (1ULL << size * 8) - 1);
46f53a65 8810 }
31fd8581 8811 }
9bac3d6d 8812
8041902d 8813 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
8814 if (!new_prog)
8815 return -ENOMEM;
8816
3df126f3 8817 delta += cnt - 1;
9bac3d6d
AS
8818
8819 /* keep walking new program and skip insns we just inserted */
8820 env->prog = new_prog;
3df126f3 8821 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
8822 }
8823
8824 return 0;
8825}
8826
1c2a088a
AS
8827static int jit_subprogs(struct bpf_verifier_env *env)
8828{
8829 struct bpf_prog *prog = env->prog, **func, *tmp;
8830 int i, j, subprog_start, subprog_end = 0, len, subprog;
7105e828 8831 struct bpf_insn *insn;
1c2a088a 8832 void *old_bpf_func;
c454a46b 8833 int err;
1c2a088a 8834
f910cefa 8835 if (env->subprog_cnt <= 1)
1c2a088a
AS
8836 return 0;
8837
7105e828 8838 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1c2a088a
AS
8839 if (insn->code != (BPF_JMP | BPF_CALL) ||
8840 insn->src_reg != BPF_PSEUDO_CALL)
8841 continue;
c7a89784
DB
8842 /* Upon error here we cannot fall back to interpreter but
8843 * need a hard reject of the program. Thus -EFAULT is
8844 * propagated in any case.
8845 */
1c2a088a
AS
8846 subprog = find_subprog(env, i + insn->imm + 1);
8847 if (subprog < 0) {
8848 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
8849 i + insn->imm + 1);
8850 return -EFAULT;
8851 }
8852 /* temporarily remember subprog id inside insn instead of
8853 * aux_data, since next loop will split up all insns into funcs
8854 */
f910cefa 8855 insn->off = subprog;
1c2a088a
AS
8856 /* remember original imm in case JIT fails and fallback
8857 * to interpreter will be needed
8858 */
8859 env->insn_aux_data[i].call_imm = insn->imm;
8860 /* point imm to __bpf_call_base+1 from JITs point of view */
8861 insn->imm = 1;
8862 }
8863
c454a46b
MKL
8864 err = bpf_prog_alloc_jited_linfo(prog);
8865 if (err)
8866 goto out_undo_insn;
8867
8868 err = -ENOMEM;
6396bb22 8869 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 8870 if (!func)
c7a89784 8871 goto out_undo_insn;
1c2a088a 8872
f910cefa 8873 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 8874 subprog_start = subprog_end;
4cb3d99c 8875 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
8876
8877 len = subprog_end - subprog_start;
492ecee8
AS
8878 /* BPF_PROG_RUN doesn't call subprogs directly,
8879 * hence main prog stats include the runtime of subprogs.
8880 * subprogs don't have IDs and not reachable via prog_get_next_id
8881 * func[i]->aux->stats will never be accessed and stays NULL
8882 */
8883 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
8884 if (!func[i])
8885 goto out_free;
8886 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
8887 len * sizeof(struct bpf_insn));
4f74d809 8888 func[i]->type = prog->type;
1c2a088a 8889 func[i]->len = len;
4f74d809
DB
8890 if (bpf_prog_calc_tag(func[i]))
8891 goto out_free;
1c2a088a 8892 func[i]->is_func = 1;
ba64e7d8
YS
8893 func[i]->aux->func_idx = i;
8894 /* the btf and func_info will be freed only at prog->aux */
8895 func[i]->aux->btf = prog->aux->btf;
8896 func[i]->aux->func_info = prog->aux->func_info;
8897
1c2a088a
AS
8898 /* Use bpf_prog_F_tag to indicate functions in stack traces.
8899 * Long term would need debug info to populate names
8900 */
8901 func[i]->aux->name[0] = 'F';
9c8105bd 8902 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 8903 func[i]->jit_requested = 1;
c454a46b
MKL
8904 func[i]->aux->linfo = prog->aux->linfo;
8905 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
8906 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
8907 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
1c2a088a
AS
8908 func[i] = bpf_int_jit_compile(func[i]);
8909 if (!func[i]->jited) {
8910 err = -ENOTSUPP;
8911 goto out_free;
8912 }
8913 cond_resched();
8914 }
8915 /* at this point all bpf functions were successfully JITed
8916 * now populate all bpf_calls with correct addresses and
8917 * run last pass of JIT
8918 */
f910cefa 8919 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
8920 insn = func[i]->insnsi;
8921 for (j = 0; j < func[i]->len; j++, insn++) {
8922 if (insn->code != (BPF_JMP | BPF_CALL) ||
8923 insn->src_reg != BPF_PSEUDO_CALL)
8924 continue;
8925 subprog = insn->off;
0d306c31
PB
8926 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
8927 __bpf_call_base;
1c2a088a 8928 }
2162fed4
SD
8929
8930 /* we use the aux data to keep a list of the start addresses
8931 * of the JITed images for each function in the program
8932 *
8933 * for some architectures, such as powerpc64, the imm field
8934 * might not be large enough to hold the offset of the start
8935 * address of the callee's JITed image from __bpf_call_base
8936 *
8937 * in such cases, we can lookup the start address of a callee
8938 * by using its subprog id, available from the off field of
8939 * the call instruction, as an index for this list
8940 */
8941 func[i]->aux->func = func;
8942 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 8943 }
f910cefa 8944 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
8945 old_bpf_func = func[i]->bpf_func;
8946 tmp = bpf_int_jit_compile(func[i]);
8947 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
8948 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 8949 err = -ENOTSUPP;
1c2a088a
AS
8950 goto out_free;
8951 }
8952 cond_resched();
8953 }
8954
8955 /* finally lock prog and jit images for all functions and
8956 * populate kallsysm
8957 */
f910cefa 8958 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
8959 bpf_prog_lock_ro(func[i]);
8960 bpf_prog_kallsyms_add(func[i]);
8961 }
7105e828
DB
8962
8963 /* Last step: make now unused interpreter insns from main
8964 * prog consistent for later dump requests, so they can
8965 * later look the same as if they were interpreted only.
8966 */
8967 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
7105e828
DB
8968 if (insn->code != (BPF_JMP | BPF_CALL) ||
8969 insn->src_reg != BPF_PSEUDO_CALL)
8970 continue;
8971 insn->off = env->insn_aux_data[i].call_imm;
8972 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 8973 insn->imm = subprog;
7105e828
DB
8974 }
8975
1c2a088a
AS
8976 prog->jited = 1;
8977 prog->bpf_func = func[0]->bpf_func;
8978 prog->aux->func = func;
f910cefa 8979 prog->aux->func_cnt = env->subprog_cnt;
c454a46b 8980 bpf_prog_free_unused_jited_linfo(prog);
1c2a088a
AS
8981 return 0;
8982out_free:
f910cefa 8983 for (i = 0; i < env->subprog_cnt; i++)
1c2a088a
AS
8984 if (func[i])
8985 bpf_jit_free(func[i]);
8986 kfree(func);
c7a89784 8987out_undo_insn:
1c2a088a
AS
8988 /* cleanup main prog to be interpreted */
8989 prog->jit_requested = 0;
8990 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
8991 if (insn->code != (BPF_JMP | BPF_CALL) ||
8992 insn->src_reg != BPF_PSEUDO_CALL)
8993 continue;
8994 insn->off = 0;
8995 insn->imm = env->insn_aux_data[i].call_imm;
8996 }
c454a46b 8997 bpf_prog_free_jited_linfo(prog);
1c2a088a
AS
8998 return err;
8999}
9000
1ea47e01
AS
9001static int fixup_call_args(struct bpf_verifier_env *env)
9002{
19d28fbd 9003#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
9004 struct bpf_prog *prog = env->prog;
9005 struct bpf_insn *insn = prog->insnsi;
9006 int i, depth;
19d28fbd 9007#endif
e4052d06 9008 int err = 0;
1ea47e01 9009
e4052d06
QM
9010 if (env->prog->jit_requested &&
9011 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
9012 err = jit_subprogs(env);
9013 if (err == 0)
1c2a088a 9014 return 0;
c7a89784
DB
9015 if (err == -EFAULT)
9016 return err;
19d28fbd
DM
9017 }
9018#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
9019 for (i = 0; i < prog->len; i++, insn++) {
9020 if (insn->code != (BPF_JMP | BPF_CALL) ||
9021 insn->src_reg != BPF_PSEUDO_CALL)
9022 continue;
9023 depth = get_callee_stack_depth(env, insn, i);
9024 if (depth < 0)
9025 return depth;
9026 bpf_patch_call_args(insn, depth);
9027 }
19d28fbd
DM
9028 err = 0;
9029#endif
9030 return err;
1ea47e01
AS
9031}
9032
79741b3b 9033/* fixup insn->imm field of bpf_call instructions
81ed18ab 9034 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
9035 *
9036 * this function is called after eBPF program passed verification
9037 */
79741b3b 9038static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 9039{
79741b3b
AS
9040 struct bpf_prog *prog = env->prog;
9041 struct bpf_insn *insn = prog->insnsi;
e245c5c6 9042 const struct bpf_func_proto *fn;
79741b3b 9043 const int insn_cnt = prog->len;
09772d92 9044 const struct bpf_map_ops *ops;
c93552c4 9045 struct bpf_insn_aux_data *aux;
81ed18ab
AS
9046 struct bpf_insn insn_buf[16];
9047 struct bpf_prog *new_prog;
9048 struct bpf_map *map_ptr;
9049 int i, cnt, delta = 0;
e245c5c6 9050
79741b3b 9051 for (i = 0; i < insn_cnt; i++, insn++) {
f6b1b3bf
DB
9052 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
9053 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9054 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 9055 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf
DB
9056 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
9057 struct bpf_insn mask_and_div[] = {
9058 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9059 /* Rx div 0 -> 0 */
9060 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
9061 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
9062 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9063 *insn,
9064 };
9065 struct bpf_insn mask_and_mod[] = {
9066 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9067 /* Rx mod 0 -> Rx */
9068 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
9069 *insn,
9070 };
9071 struct bpf_insn *patchlet;
9072
9073 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9074 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9075 patchlet = mask_and_div + (is64 ? 1 : 0);
9076 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
9077 } else {
9078 patchlet = mask_and_mod + (is64 ? 1 : 0);
9079 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
9080 }
9081
9082 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
9083 if (!new_prog)
9084 return -ENOMEM;
9085
9086 delta += cnt - 1;
9087 env->prog = prog = new_prog;
9088 insn = new_prog->insnsi + i + delta;
9089 continue;
9090 }
9091
e0cea7ce
DB
9092 if (BPF_CLASS(insn->code) == BPF_LD &&
9093 (BPF_MODE(insn->code) == BPF_ABS ||
9094 BPF_MODE(insn->code) == BPF_IND)) {
9095 cnt = env->ops->gen_ld_abs(insn, insn_buf);
9096 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9097 verbose(env, "bpf verifier is misconfigured\n");
9098 return -EINVAL;
9099 }
9100
9101 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9102 if (!new_prog)
9103 return -ENOMEM;
9104
9105 delta += cnt - 1;
9106 env->prog = prog = new_prog;
9107 insn = new_prog->insnsi + i + delta;
9108 continue;
9109 }
9110
979d63d5
DB
9111 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
9112 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
9113 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
9114 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
9115 struct bpf_insn insn_buf[16];
9116 struct bpf_insn *patch = &insn_buf[0];
9117 bool issrc, isneg;
9118 u32 off_reg;
9119
9120 aux = &env->insn_aux_data[i + delta];
3612af78
DB
9121 if (!aux->alu_state ||
9122 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
9123 continue;
9124
9125 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
9126 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
9127 BPF_ALU_SANITIZE_SRC;
9128
9129 off_reg = issrc ? insn->src_reg : insn->dst_reg;
9130 if (isneg)
9131 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9132 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
9133 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
9134 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
9135 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
9136 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
9137 if (issrc) {
9138 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
9139 off_reg);
9140 insn->src_reg = BPF_REG_AX;
9141 } else {
9142 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
9143 BPF_REG_AX);
9144 }
9145 if (isneg)
9146 insn->code = insn->code == code_add ?
9147 code_sub : code_add;
9148 *patch++ = *insn;
9149 if (issrc && isneg)
9150 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9151 cnt = patch - insn_buf;
9152
9153 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9154 if (!new_prog)
9155 return -ENOMEM;
9156
9157 delta += cnt - 1;
9158 env->prog = prog = new_prog;
9159 insn = new_prog->insnsi + i + delta;
9160 continue;
9161 }
9162
79741b3b
AS
9163 if (insn->code != (BPF_JMP | BPF_CALL))
9164 continue;
cc8b0b92
AS
9165 if (insn->src_reg == BPF_PSEUDO_CALL)
9166 continue;
e245c5c6 9167
79741b3b
AS
9168 if (insn->imm == BPF_FUNC_get_route_realm)
9169 prog->dst_needed = 1;
9170 if (insn->imm == BPF_FUNC_get_prandom_u32)
9171 bpf_user_rnd_init_once();
9802d865
JB
9172 if (insn->imm == BPF_FUNC_override_return)
9173 prog->kprobe_override = 1;
79741b3b 9174 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
9175 /* If we tail call into other programs, we
9176 * cannot make any assumptions since they can
9177 * be replaced dynamically during runtime in
9178 * the program array.
9179 */
9180 prog->cb_access = 1;
80a58d02 9181 env->prog->aux->stack_depth = MAX_BPF_STACK;
e647815a 9182 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 9183
79741b3b
AS
9184 /* mark bpf_tail_call as different opcode to avoid
9185 * conditional branch in the interpeter for every normal
9186 * call and to prevent accidental JITing by JIT compiler
9187 * that doesn't support bpf_tail_call yet
e245c5c6 9188 */
79741b3b 9189 insn->imm = 0;
71189fa9 9190 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 9191
c93552c4
DB
9192 aux = &env->insn_aux_data[i + delta];
9193 if (!bpf_map_ptr_unpriv(aux))
9194 continue;
9195
b2157399
AS
9196 /* instead of changing every JIT dealing with tail_call
9197 * emit two extra insns:
9198 * if (index >= max_entries) goto out;
9199 * index &= array->index_mask;
9200 * to avoid out-of-bounds cpu speculation
9201 */
c93552c4 9202 if (bpf_map_ptr_poisoned(aux)) {
40950343 9203 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
9204 return -EINVAL;
9205 }
c93552c4
DB
9206
9207 map_ptr = BPF_MAP_PTR(aux->map_state);
b2157399
AS
9208 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
9209 map_ptr->max_entries, 2);
9210 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
9211 container_of(map_ptr,
9212 struct bpf_array,
9213 map)->index_mask);
9214 insn_buf[2] = *insn;
9215 cnt = 3;
9216 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9217 if (!new_prog)
9218 return -ENOMEM;
9219
9220 delta += cnt - 1;
9221 env->prog = prog = new_prog;
9222 insn = new_prog->insnsi + i + delta;
79741b3b
AS
9223 continue;
9224 }
e245c5c6 9225
89c63074 9226 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
9227 * and other inlining handlers are currently limited to 64 bit
9228 * only.
89c63074 9229 */
60b58afc 9230 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
9231 (insn->imm == BPF_FUNC_map_lookup_elem ||
9232 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
9233 insn->imm == BPF_FUNC_map_delete_elem ||
9234 insn->imm == BPF_FUNC_map_push_elem ||
9235 insn->imm == BPF_FUNC_map_pop_elem ||
9236 insn->imm == BPF_FUNC_map_peek_elem)) {
c93552c4
DB
9237 aux = &env->insn_aux_data[i + delta];
9238 if (bpf_map_ptr_poisoned(aux))
9239 goto patch_call_imm;
9240
9241 map_ptr = BPF_MAP_PTR(aux->map_state);
09772d92
DB
9242 ops = map_ptr->ops;
9243 if (insn->imm == BPF_FUNC_map_lookup_elem &&
9244 ops->map_gen_lookup) {
9245 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
9246 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9247 verbose(env, "bpf verifier is misconfigured\n");
9248 return -EINVAL;
9249 }
81ed18ab 9250
09772d92
DB
9251 new_prog = bpf_patch_insn_data(env, i + delta,
9252 insn_buf, cnt);
9253 if (!new_prog)
9254 return -ENOMEM;
81ed18ab 9255
09772d92
DB
9256 delta += cnt - 1;
9257 env->prog = prog = new_prog;
9258 insn = new_prog->insnsi + i + delta;
9259 continue;
9260 }
81ed18ab 9261
09772d92
DB
9262 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
9263 (void *(*)(struct bpf_map *map, void *key))NULL));
9264 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
9265 (int (*)(struct bpf_map *map, void *key))NULL));
9266 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
9267 (int (*)(struct bpf_map *map, void *key, void *value,
9268 u64 flags))NULL));
84430d42
DB
9269 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
9270 (int (*)(struct bpf_map *map, void *value,
9271 u64 flags))NULL));
9272 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
9273 (int (*)(struct bpf_map *map, void *value))NULL));
9274 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
9275 (int (*)(struct bpf_map *map, void *value))NULL));
9276
09772d92
DB
9277 switch (insn->imm) {
9278 case BPF_FUNC_map_lookup_elem:
9279 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
9280 __bpf_call_base;
9281 continue;
9282 case BPF_FUNC_map_update_elem:
9283 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
9284 __bpf_call_base;
9285 continue;
9286 case BPF_FUNC_map_delete_elem:
9287 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
9288 __bpf_call_base;
9289 continue;
84430d42
DB
9290 case BPF_FUNC_map_push_elem:
9291 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
9292 __bpf_call_base;
9293 continue;
9294 case BPF_FUNC_map_pop_elem:
9295 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
9296 __bpf_call_base;
9297 continue;
9298 case BPF_FUNC_map_peek_elem:
9299 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
9300 __bpf_call_base;
9301 continue;
09772d92 9302 }
81ed18ab 9303
09772d92 9304 goto patch_call_imm;
81ed18ab
AS
9305 }
9306
9307patch_call_imm:
5e43f899 9308 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
9309 /* all functions that have prototype and verifier allowed
9310 * programs to call them, must be real in-kernel functions
9311 */
9312 if (!fn->func) {
61bd5218
JK
9313 verbose(env,
9314 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
9315 func_id_name(insn->imm), insn->imm);
9316 return -EFAULT;
e245c5c6 9317 }
79741b3b 9318 insn->imm = fn->func - __bpf_call_base;
e245c5c6 9319 }
e245c5c6 9320
79741b3b
AS
9321 return 0;
9322}
e245c5c6 9323
58e2af8b 9324static void free_states(struct bpf_verifier_env *env)
f1bca824 9325{
58e2af8b 9326 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
9327 int i;
9328
9f4686c4
AS
9329 sl = env->free_list;
9330 while (sl) {
9331 sln = sl->next;
9332 free_verifier_state(&sl->state, false);
9333 kfree(sl);
9334 sl = sln;
9335 }
9336
f1bca824
AS
9337 if (!env->explored_states)
9338 return;
9339
dc2a4ebc 9340 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
9341 sl = env->explored_states[i];
9342
a8f500af
AS
9343 while (sl) {
9344 sln = sl->next;
9345 free_verifier_state(&sl->state, false);
9346 kfree(sl);
9347 sl = sln;
9348 }
f1bca824
AS
9349 }
9350
71dde681 9351 kvfree(env->explored_states);
f1bca824
AS
9352}
9353
06ee7115
AS
9354static void print_verification_stats(struct bpf_verifier_env *env)
9355{
9356 int i;
9357
9358 if (env->log.level & BPF_LOG_STATS) {
9359 verbose(env, "verification time %lld usec\n",
9360 div_u64(env->verification_time, 1000));
9361 verbose(env, "stack depth ");
9362 for (i = 0; i < env->subprog_cnt; i++) {
9363 u32 depth = env->subprog_info[i].stack_depth;
9364
9365 verbose(env, "%d", depth);
9366 if (i + 1 < env->subprog_cnt)
9367 verbose(env, "+");
9368 }
9369 verbose(env, "\n");
9370 }
9371 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
9372 "total_states %d peak_states %d mark_read %d\n",
9373 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
9374 env->max_states_per_insn, env->total_states,
9375 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
9376}
9377
38207291
MKL
9378static int check_attach_btf_id(struct bpf_verifier_env *env)
9379{
9380 struct bpf_prog *prog = env->prog;
9381 u32 btf_id = prog->aux->attach_btf_id;
f1b9509c 9382 const char prefix[] = "btf_trace_";
fec56f58 9383 struct bpf_trampoline *tr;
38207291
MKL
9384 const struct btf_type *t;
9385 const char *tname;
fec56f58
AS
9386 int ret = 0;
9387 long addr;
38207291 9388
f1b9509c
AS
9389 if (prog->type != BPF_PROG_TYPE_TRACING)
9390 return 0;
38207291 9391
f1b9509c
AS
9392 if (!btf_id) {
9393 verbose(env, "Tracing programs must provide btf_id\n");
9394 return -EINVAL;
9395 }
9396 t = btf_type_by_id(btf_vmlinux, btf_id);
9397 if (!t) {
9398 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
9399 return -EINVAL;
9400 }
9401 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
9402 if (!tname) {
9403 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
9404 return -EINVAL;
9405 }
9406
9407 switch (prog->expected_attach_type) {
9408 case BPF_TRACE_RAW_TP:
38207291
MKL
9409 if (!btf_type_is_typedef(t)) {
9410 verbose(env, "attach_btf_id %u is not a typedef\n",
9411 btf_id);
9412 return -EINVAL;
9413 }
f1b9509c 9414 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
38207291
MKL
9415 verbose(env, "attach_btf_id %u points to wrong type name %s\n",
9416 btf_id, tname);
9417 return -EINVAL;
9418 }
9419 tname += sizeof(prefix) - 1;
9420 t = btf_type_by_id(btf_vmlinux, t->type);
9421 if (!btf_type_is_ptr(t))
9422 /* should never happen in valid vmlinux build */
9423 return -EINVAL;
9424 t = btf_type_by_id(btf_vmlinux, t->type);
9425 if (!btf_type_is_func_proto(t))
9426 /* should never happen in valid vmlinux build */
9427 return -EINVAL;
9428
9429 /* remember two read only pointers that are valid for
9430 * the life time of the kernel
9431 */
9432 prog->aux->attach_func_name = tname;
9433 prog->aux->attach_func_proto = t;
9434 prog->aux->attach_btf_trace = true;
f1b9509c 9435 return 0;
fec56f58
AS
9436 case BPF_TRACE_FENTRY:
9437 case BPF_TRACE_FEXIT:
9438 if (!btf_type_is_func(t)) {
9439 verbose(env, "attach_btf_id %u is not a function\n",
9440 btf_id);
9441 return -EINVAL;
9442 }
9443 t = btf_type_by_id(btf_vmlinux, t->type);
9444 if (!btf_type_is_func_proto(t))
9445 return -EINVAL;
9446 tr = bpf_trampoline_lookup(btf_id);
9447 if (!tr)
9448 return -ENOMEM;
9449 prog->aux->attach_func_name = tname;
9450 prog->aux->attach_func_proto = t;
9451 mutex_lock(&tr->mutex);
9452 if (tr->func.addr) {
9453 prog->aux->trampoline = tr;
9454 goto out;
9455 }
9456 ret = btf_distill_func_proto(&env->log, btf_vmlinux, t,
9457 tname, &tr->func.model);
9458 if (ret < 0)
9459 goto out;
9460 addr = kallsyms_lookup_name(tname);
9461 if (!addr) {
9462 verbose(env,
9463 "The address of function %s cannot be found\n",
9464 tname);
9465 ret = -ENOENT;
9466 goto out;
9467 }
9468 tr->func.addr = (void *)addr;
9469 prog->aux->trampoline = tr;
9470out:
9471 mutex_unlock(&tr->mutex);
9472 if (ret)
9473 bpf_trampoline_put(tr);
9474 return ret;
f1b9509c
AS
9475 default:
9476 return -EINVAL;
38207291 9477 }
38207291
MKL
9478}
9479
838e9690
YS
9480int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
9481 union bpf_attr __user *uattr)
51580e79 9482{
06ee7115 9483 u64 start_time = ktime_get_ns();
58e2af8b 9484 struct bpf_verifier_env *env;
b9193c1b 9485 struct bpf_verifier_log *log;
9e4c24e7 9486 int i, len, ret = -EINVAL;
e2ae4ca2 9487 bool is_priv;
51580e79 9488
eba0c929
AB
9489 /* no program is valid */
9490 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
9491 return -EINVAL;
9492
58e2af8b 9493 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
9494 * allocate/free it every time bpf_check() is called
9495 */
58e2af8b 9496 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
9497 if (!env)
9498 return -ENOMEM;
61bd5218 9499 log = &env->log;
cbd35700 9500
9e4c24e7 9501 len = (*prog)->len;
fad953ce 9502 env->insn_aux_data =
9e4c24e7 9503 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
9504 ret = -ENOMEM;
9505 if (!env->insn_aux_data)
9506 goto err_free_env;
9e4c24e7
JK
9507 for (i = 0; i < len; i++)
9508 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 9509 env->prog = *prog;
00176a34 9510 env->ops = bpf_verifier_ops[env->prog->type];
45a73c17 9511 is_priv = capable(CAP_SYS_ADMIN);
0246e64d 9512
8580ac94
AS
9513 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
9514 mutex_lock(&bpf_verifier_lock);
9515 if (!btf_vmlinux)
9516 btf_vmlinux = btf_parse_vmlinux();
9517 mutex_unlock(&bpf_verifier_lock);
9518 }
9519
cbd35700 9520 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
9521 if (!is_priv)
9522 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
9523
9524 if (attr->log_level || attr->log_buf || attr->log_size) {
9525 /* user requested verbose verifier output
9526 * and supplied buffer to store the verification trace
9527 */
e7bf8249
JK
9528 log->level = attr->log_level;
9529 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
9530 log->len_total = attr->log_size;
cbd35700
AS
9531
9532 ret = -EINVAL;
e7bf8249 9533 /* log attributes have to be sane */
7a9f5c65 9534 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 9535 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 9536 goto err_unlock;
cbd35700 9537 }
1ad2f583 9538
8580ac94
AS
9539 if (IS_ERR(btf_vmlinux)) {
9540 /* Either gcc or pahole or kernel are broken. */
9541 verbose(env, "in-kernel BTF is malformed\n");
9542 ret = PTR_ERR(btf_vmlinux);
38207291 9543 goto skip_full_check;
8580ac94
AS
9544 }
9545
38207291
MKL
9546 ret = check_attach_btf_id(env);
9547 if (ret)
9548 goto skip_full_check;
9549
1ad2f583
DB
9550 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
9551 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 9552 env->strict_alignment = true;
e9ee9efc
DM
9553 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
9554 env->strict_alignment = false;
cbd35700 9555
e2ae4ca2
JK
9556 env->allow_ptr_leaks = is_priv;
9557
10d274e8
AS
9558 if (is_priv)
9559 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
9560
f4e3ec0d
JK
9561 ret = replace_map_fd_with_map_ptr(env);
9562 if (ret < 0)
9563 goto skip_full_check;
9564
cae1927c 9565 if (bpf_prog_is_dev_bound(env->prog->aux)) {
a40a2632 9566 ret = bpf_prog_offload_verifier_prep(env->prog);
ab3f0063 9567 if (ret)
f4e3ec0d 9568 goto skip_full_check;
ab3f0063
JK
9569 }
9570
dc2a4ebc 9571 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 9572 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
9573 GFP_USER);
9574 ret = -ENOMEM;
9575 if (!env->explored_states)
9576 goto skip_full_check;
9577
d9762e84 9578 ret = check_subprogs(env);
475fb78f
AS
9579 if (ret < 0)
9580 goto skip_full_check;
9581
c454a46b 9582 ret = check_btf_info(env, attr, uattr);
838e9690
YS
9583 if (ret < 0)
9584 goto skip_full_check;
9585
d9762e84
MKL
9586 ret = check_cfg(env);
9587 if (ret < 0)
9588 goto skip_full_check;
9589
17a52670 9590 ret = do_check(env);
8c01c4f8
CG
9591 if (env->cur_state) {
9592 free_verifier_state(env->cur_state, true);
9593 env->cur_state = NULL;
9594 }
cbd35700 9595
c941ce9c
QM
9596 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
9597 ret = bpf_prog_offload_finalize(env);
9598
0246e64d 9599skip_full_check:
638f5b90 9600 while (!pop_stack(env, NULL, NULL));
f1bca824 9601 free_states(env);
0246e64d 9602
c131187d 9603 if (ret == 0)
9b38c405 9604 ret = check_max_stack_depth(env);
c131187d 9605
9b38c405 9606 /* instruction rewrites happen after this point */
e2ae4ca2
JK
9607 if (is_priv) {
9608 if (ret == 0)
9609 opt_hard_wire_dead_code_branches(env);
52875a04
JK
9610 if (ret == 0)
9611 ret = opt_remove_dead_code(env);
a1b14abc
JK
9612 if (ret == 0)
9613 ret = opt_remove_nops(env);
52875a04
JK
9614 } else {
9615 if (ret == 0)
9616 sanitize_dead_code(env);
e2ae4ca2
JK
9617 }
9618
9bac3d6d
AS
9619 if (ret == 0)
9620 /* program is valid, convert *(u32*)(ctx + off) accesses */
9621 ret = convert_ctx_accesses(env);
9622
e245c5c6 9623 if (ret == 0)
79741b3b 9624 ret = fixup_bpf_calls(env);
e245c5c6 9625
a4b1d3c1
JW
9626 /* do 32-bit optimization after insn patching has done so those patched
9627 * insns could be handled correctly.
9628 */
d6c2308c
JW
9629 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
9630 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
9631 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
9632 : false;
a4b1d3c1
JW
9633 }
9634
1ea47e01
AS
9635 if (ret == 0)
9636 ret = fixup_call_args(env);
9637
06ee7115
AS
9638 env->verification_time = ktime_get_ns() - start_time;
9639 print_verification_stats(env);
9640
a2a7d570 9641 if (log->level && bpf_verifier_log_full(log))
cbd35700 9642 ret = -ENOSPC;
a2a7d570 9643 if (log->level && !log->ubuf) {
cbd35700 9644 ret = -EFAULT;
a2a7d570 9645 goto err_release_maps;
cbd35700
AS
9646 }
9647
0246e64d
AS
9648 if (ret == 0 && env->used_map_cnt) {
9649 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
9650 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
9651 sizeof(env->used_maps[0]),
9652 GFP_KERNEL);
0246e64d 9653
9bac3d6d 9654 if (!env->prog->aux->used_maps) {
0246e64d 9655 ret = -ENOMEM;
a2a7d570 9656 goto err_release_maps;
0246e64d
AS
9657 }
9658
9bac3d6d 9659 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 9660 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 9661 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
9662
9663 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
9664 * bpf_ld_imm64 instructions
9665 */
9666 convert_pseudo_ld_imm64(env);
9667 }
cbd35700 9668
ba64e7d8
YS
9669 if (ret == 0)
9670 adjust_btf_func(env);
9671
a2a7d570 9672err_release_maps:
9bac3d6d 9673 if (!env->prog->aux->used_maps)
0246e64d 9674 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 9675 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
9676 */
9677 release_maps(env);
9bac3d6d 9678 *prog = env->prog;
3df126f3 9679err_unlock:
45a73c17
AS
9680 if (!is_priv)
9681 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
9682 vfree(env->insn_aux_data);
9683err_free_env:
9684 kfree(env);
51580e79
AS
9685 return ret;
9686}