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