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