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