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