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