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