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