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