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