xref: /linux/kernel/bpf/verifier.c (revision f6f3bac08ff9855d803081a353a1fafaa8845739)
1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2  * Copyright (c) 2016 Facebook
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * General Public License for more details.
12  */
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
22 #include <linux/stringify.h>
23 #include <linux/bsearch.h>
24 #include <linux/sort.h>
25 #include <linux/perf_event.h>
26 
27 #include "disasm.h"
28 
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name) \
31 	[_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 };
37 
38 /* bpf_check() is a static code analyzer that walks eBPF program
39  * instruction by instruction and updates register/stack state.
40  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
41  *
42  * The first pass is depth-first-search to check that the program is a DAG.
43  * It rejects the following programs:
44  * - larger than BPF_MAXINSNS insns
45  * - if loop is present (detected via back-edge)
46  * - unreachable insns exist (shouldn't be a forest. program = one function)
47  * - out of bounds or malformed jumps
48  * The second pass is all possible path descent from the 1st insn.
49  * Since it's analyzing all pathes through the program, the length of the
50  * analysis is limited to 64k insn, which may be hit even if total number of
51  * insn is less then 4K, but there are too many branches that change stack/regs.
52  * Number of 'branches to be analyzed' is limited to 1k
53  *
54  * On entry to each instruction, each register has a type, and the instruction
55  * changes the types of the registers depending on instruction semantics.
56  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
57  * copied to R1.
58  *
59  * All registers are 64-bit.
60  * R0 - return register
61  * R1-R5 argument passing registers
62  * R6-R9 callee saved registers
63  * R10 - frame pointer read-only
64  *
65  * At the start of BPF program the register R1 contains a pointer to bpf_context
66  * and has type PTR_TO_CTX.
67  *
68  * Verifier tracks arithmetic operations on pointers in case:
69  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
70  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
71  * 1st insn copies R10 (which has FRAME_PTR) type into R1
72  * and 2nd arithmetic instruction is pattern matched to recognize
73  * that it wants to construct a pointer to some element within stack.
74  * So after 2nd insn, the register R1 has type PTR_TO_STACK
75  * (and -20 constant is saved for further stack bounds checking).
76  * Meaning that this reg is a pointer to stack plus known immediate constant.
77  *
78  * Most of the time the registers have SCALAR_VALUE type, which
79  * means the register has some value, but it's not a valid pointer.
80  * (like pointer plus pointer becomes SCALAR_VALUE type)
81  *
82  * When verifier sees load or store instructions the type of base register
83  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
84  * types recognized by check_mem_access() function.
85  *
86  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
87  * and the range of [ptr, ptr + map's value_size) is accessible.
88  *
89  * registers used to pass values to function calls are checked against
90  * function argument constraints.
91  *
92  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
93  * It means that the register type passed to this function must be
94  * PTR_TO_STACK and it will be used inside the function as
95  * 'pointer to map element key'
96  *
97  * For example the argument constraints for bpf_map_lookup_elem():
98  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
99  *   .arg1_type = ARG_CONST_MAP_PTR,
100  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
101  *
102  * ret_type says that this function returns 'pointer to map elem value or null'
103  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
104  * 2nd argument should be a pointer to stack, which will be used inside
105  * the helper function as a pointer to map element key.
106  *
107  * On the kernel side the helper function looks like:
108  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
109  * {
110  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
111  *    void *key = (void *) (unsigned long) r2;
112  *    void *value;
113  *
114  *    here kernel can access 'key' and 'map' pointers safely, knowing that
115  *    [key, key + map->key_size) bytes are valid and were initialized on
116  *    the stack of eBPF program.
117  * }
118  *
119  * Corresponding eBPF program may look like:
120  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
121  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
122  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
123  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
124  * here verifier looks at prototype of map_lookup_elem() and sees:
125  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
126  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
127  *
128  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
129  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
130  * and were initialized prior to this call.
131  * If it's ok, then verifier allows this BPF_CALL insn and looks at
132  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
133  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
134  * returns ether pointer to map value or NULL.
135  *
136  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
137  * insn, the register holding that pointer in the true branch changes state to
138  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
139  * branch. See check_cond_jmp_op().
140  *
141  * After the call R0 is set to return type of the function and registers R1-R5
142  * are set to NOT_INIT to indicate that they are no longer readable.
143  */
144 
145 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
146 struct bpf_verifier_stack_elem {
147 	/* verifer state is 'st'
148 	 * before processing instruction 'insn_idx'
149 	 * and after processing instruction 'prev_insn_idx'
150 	 */
151 	struct bpf_verifier_state st;
152 	int insn_idx;
153 	int prev_insn_idx;
154 	struct bpf_verifier_stack_elem *next;
155 };
156 
157 #define BPF_COMPLEXITY_LIMIT_INSNS	131072
158 #define BPF_COMPLEXITY_LIMIT_STACK	1024
159 
160 #define BPF_MAP_PTR_UNPRIV	1UL
161 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
162 					  POISON_POINTER_DELTA))
163 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
164 
165 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
166 {
167 	return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
168 }
169 
170 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
171 {
172 	return aux->map_state & BPF_MAP_PTR_UNPRIV;
173 }
174 
175 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
176 			      const struct bpf_map *map, bool unpriv)
177 {
178 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
179 	unpriv |= bpf_map_ptr_unpriv(aux);
180 	aux->map_state = (unsigned long)map |
181 			 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
182 }
183 
184 struct bpf_call_arg_meta {
185 	struct bpf_map *map_ptr;
186 	bool raw_mode;
187 	bool pkt_access;
188 	int regno;
189 	int access_size;
190 	s64 msize_smax_value;
191 	u64 msize_umax_value;
192 };
193 
194 static DEFINE_MUTEX(bpf_verifier_lock);
195 
196 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
197 		       va_list args)
198 {
199 	unsigned int n;
200 
201 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
202 
203 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
204 		  "verifier log line truncated - local buffer too short\n");
205 
206 	n = min(log->len_total - log->len_used - 1, n);
207 	log->kbuf[n] = '\0';
208 
209 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
210 		log->len_used += n;
211 	else
212 		log->ubuf = NULL;
213 }
214 
215 /* log_level controls verbosity level of eBPF verifier.
216  * bpf_verifier_log_write() is used to dump the verification trace to the log,
217  * so the user can figure out what's wrong with the program
218  */
219 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
220 					   const char *fmt, ...)
221 {
222 	va_list args;
223 
224 	if (!bpf_verifier_log_needed(&env->log))
225 		return;
226 
227 	va_start(args, fmt);
228 	bpf_verifier_vlog(&env->log, fmt, args);
229 	va_end(args);
230 }
231 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
232 
233 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
234 {
235 	struct bpf_verifier_env *env = private_data;
236 	va_list args;
237 
238 	if (!bpf_verifier_log_needed(&env->log))
239 		return;
240 
241 	va_start(args, fmt);
242 	bpf_verifier_vlog(&env->log, fmt, args);
243 	va_end(args);
244 }
245 
246 static bool type_is_pkt_pointer(enum bpf_reg_type type)
247 {
248 	return type == PTR_TO_PACKET ||
249 	       type == PTR_TO_PACKET_META;
250 }
251 
252 /* string representation of 'enum bpf_reg_type' */
253 static const char * const reg_type_str[] = {
254 	[NOT_INIT]		= "?",
255 	[SCALAR_VALUE]		= "inv",
256 	[PTR_TO_CTX]		= "ctx",
257 	[CONST_PTR_TO_MAP]	= "map_ptr",
258 	[PTR_TO_MAP_VALUE]	= "map_value",
259 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
260 	[PTR_TO_STACK]		= "fp",
261 	[PTR_TO_PACKET]		= "pkt",
262 	[PTR_TO_PACKET_META]	= "pkt_meta",
263 	[PTR_TO_PACKET_END]	= "pkt_end",
264 };
265 
266 static char slot_type_char[] = {
267 	[STACK_INVALID]	= '?',
268 	[STACK_SPILL]	= 'r',
269 	[STACK_MISC]	= 'm',
270 	[STACK_ZERO]	= '0',
271 };
272 
273 static void print_liveness(struct bpf_verifier_env *env,
274 			   enum bpf_reg_liveness live)
275 {
276 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
277 	    verbose(env, "_");
278 	if (live & REG_LIVE_READ)
279 		verbose(env, "r");
280 	if (live & REG_LIVE_WRITTEN)
281 		verbose(env, "w");
282 }
283 
284 static struct bpf_func_state *func(struct bpf_verifier_env *env,
285 				   const struct bpf_reg_state *reg)
286 {
287 	struct bpf_verifier_state *cur = env->cur_state;
288 
289 	return cur->frame[reg->frameno];
290 }
291 
292 static void print_verifier_state(struct bpf_verifier_env *env,
293 				 const struct bpf_func_state *state)
294 {
295 	const struct bpf_reg_state *reg;
296 	enum bpf_reg_type t;
297 	int i;
298 
299 	if (state->frameno)
300 		verbose(env, " frame%d:", state->frameno);
301 	for (i = 0; i < MAX_BPF_REG; i++) {
302 		reg = &state->regs[i];
303 		t = reg->type;
304 		if (t == NOT_INIT)
305 			continue;
306 		verbose(env, " R%d", i);
307 		print_liveness(env, reg->live);
308 		verbose(env, "=%s", reg_type_str[t]);
309 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
310 		    tnum_is_const(reg->var_off)) {
311 			/* reg->off should be 0 for SCALAR_VALUE */
312 			verbose(env, "%lld", reg->var_off.value + reg->off);
313 			if (t == PTR_TO_STACK)
314 				verbose(env, ",call_%d", func(env, reg)->callsite);
315 		} else {
316 			verbose(env, "(id=%d", reg->id);
317 			if (t != SCALAR_VALUE)
318 				verbose(env, ",off=%d", reg->off);
319 			if (type_is_pkt_pointer(t))
320 				verbose(env, ",r=%d", reg->range);
321 			else if (t == CONST_PTR_TO_MAP ||
322 				 t == PTR_TO_MAP_VALUE ||
323 				 t == PTR_TO_MAP_VALUE_OR_NULL)
324 				verbose(env, ",ks=%d,vs=%d",
325 					reg->map_ptr->key_size,
326 					reg->map_ptr->value_size);
327 			if (tnum_is_const(reg->var_off)) {
328 				/* Typically an immediate SCALAR_VALUE, but
329 				 * could be a pointer whose offset is too big
330 				 * for reg->off
331 				 */
332 				verbose(env, ",imm=%llx", reg->var_off.value);
333 			} else {
334 				if (reg->smin_value != reg->umin_value &&
335 				    reg->smin_value != S64_MIN)
336 					verbose(env, ",smin_value=%lld",
337 						(long long)reg->smin_value);
338 				if (reg->smax_value != reg->umax_value &&
339 				    reg->smax_value != S64_MAX)
340 					verbose(env, ",smax_value=%lld",
341 						(long long)reg->smax_value);
342 				if (reg->umin_value != 0)
343 					verbose(env, ",umin_value=%llu",
344 						(unsigned long long)reg->umin_value);
345 				if (reg->umax_value != U64_MAX)
346 					verbose(env, ",umax_value=%llu",
347 						(unsigned long long)reg->umax_value);
348 				if (!tnum_is_unknown(reg->var_off)) {
349 					char tn_buf[48];
350 
351 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
352 					verbose(env, ",var_off=%s", tn_buf);
353 				}
354 			}
355 			verbose(env, ")");
356 		}
357 	}
358 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
359 		char types_buf[BPF_REG_SIZE + 1];
360 		bool valid = false;
361 		int j;
362 
363 		for (j = 0; j < BPF_REG_SIZE; j++) {
364 			if (state->stack[i].slot_type[j] != STACK_INVALID)
365 				valid = true;
366 			types_buf[j] = slot_type_char[
367 					state->stack[i].slot_type[j]];
368 		}
369 		types_buf[BPF_REG_SIZE] = 0;
370 		if (!valid)
371 			continue;
372 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
373 		print_liveness(env, state->stack[i].spilled_ptr.live);
374 		if (state->stack[i].slot_type[0] == STACK_SPILL)
375 			verbose(env, "=%s",
376 				reg_type_str[state->stack[i].spilled_ptr.type]);
377 		else
378 			verbose(env, "=%s", types_buf);
379 	}
380 	verbose(env, "\n");
381 }
382 
383 static int copy_stack_state(struct bpf_func_state *dst,
384 			    const struct bpf_func_state *src)
385 {
386 	if (!src->stack)
387 		return 0;
388 	if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
389 		/* internal bug, make state invalid to reject the program */
390 		memset(dst, 0, sizeof(*dst));
391 		return -EFAULT;
392 	}
393 	memcpy(dst->stack, src->stack,
394 	       sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
395 	return 0;
396 }
397 
398 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
399  * make it consume minimal amount of memory. check_stack_write() access from
400  * the program calls into realloc_func_state() to grow the stack size.
401  * Note there is a non-zero parent pointer inside each reg of bpf_verifier_state
402  * which this function copies over. It points to corresponding reg in previous
403  * bpf_verifier_state which is never reallocated
404  */
405 static int realloc_func_state(struct bpf_func_state *state, int size,
406 			      bool copy_old)
407 {
408 	u32 old_size = state->allocated_stack;
409 	struct bpf_stack_state *new_stack;
410 	int slot = size / BPF_REG_SIZE;
411 
412 	if (size <= old_size || !size) {
413 		if (copy_old)
414 			return 0;
415 		state->allocated_stack = slot * BPF_REG_SIZE;
416 		if (!size && old_size) {
417 			kfree(state->stack);
418 			state->stack = NULL;
419 		}
420 		return 0;
421 	}
422 	new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
423 				  GFP_KERNEL);
424 	if (!new_stack)
425 		return -ENOMEM;
426 	if (copy_old) {
427 		if (state->stack)
428 			memcpy(new_stack, state->stack,
429 			       sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
430 		memset(new_stack + old_size / BPF_REG_SIZE, 0,
431 		       sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
432 	}
433 	state->allocated_stack = slot * BPF_REG_SIZE;
434 	kfree(state->stack);
435 	state->stack = new_stack;
436 	return 0;
437 }
438 
439 static void free_func_state(struct bpf_func_state *state)
440 {
441 	if (!state)
442 		return;
443 	kfree(state->stack);
444 	kfree(state);
445 }
446 
447 static void free_verifier_state(struct bpf_verifier_state *state,
448 				bool free_self)
449 {
450 	int i;
451 
452 	for (i = 0; i <= state->curframe; i++) {
453 		free_func_state(state->frame[i]);
454 		state->frame[i] = NULL;
455 	}
456 	if (free_self)
457 		kfree(state);
458 }
459 
460 /* copy verifier state from src to dst growing dst stack space
461  * when necessary to accommodate larger src stack
462  */
463 static int copy_func_state(struct bpf_func_state *dst,
464 			   const struct bpf_func_state *src)
465 {
466 	int err;
467 
468 	err = realloc_func_state(dst, src->allocated_stack, false);
469 	if (err)
470 		return err;
471 	memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
472 	return copy_stack_state(dst, src);
473 }
474 
475 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
476 			       const struct bpf_verifier_state *src)
477 {
478 	struct bpf_func_state *dst;
479 	int i, err;
480 
481 	/* if dst has more stack frames then src frame, free them */
482 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
483 		free_func_state(dst_state->frame[i]);
484 		dst_state->frame[i] = NULL;
485 	}
486 	dst_state->curframe = src->curframe;
487 	for (i = 0; i <= src->curframe; i++) {
488 		dst = dst_state->frame[i];
489 		if (!dst) {
490 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
491 			if (!dst)
492 				return -ENOMEM;
493 			dst_state->frame[i] = dst;
494 		}
495 		err = copy_func_state(dst, src->frame[i]);
496 		if (err)
497 			return err;
498 	}
499 	return 0;
500 }
501 
502 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
503 		     int *insn_idx)
504 {
505 	struct bpf_verifier_state *cur = env->cur_state;
506 	struct bpf_verifier_stack_elem *elem, *head = env->head;
507 	int err;
508 
509 	if (env->head == NULL)
510 		return -ENOENT;
511 
512 	if (cur) {
513 		err = copy_verifier_state(cur, &head->st);
514 		if (err)
515 			return err;
516 	}
517 	if (insn_idx)
518 		*insn_idx = head->insn_idx;
519 	if (prev_insn_idx)
520 		*prev_insn_idx = head->prev_insn_idx;
521 	elem = head->next;
522 	free_verifier_state(&head->st, false);
523 	kfree(head);
524 	env->head = elem;
525 	env->stack_size--;
526 	return 0;
527 }
528 
529 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
530 					     int insn_idx, int prev_insn_idx)
531 {
532 	struct bpf_verifier_state *cur = env->cur_state;
533 	struct bpf_verifier_stack_elem *elem;
534 	int err;
535 
536 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
537 	if (!elem)
538 		goto err;
539 
540 	elem->insn_idx = insn_idx;
541 	elem->prev_insn_idx = prev_insn_idx;
542 	elem->next = env->head;
543 	env->head = elem;
544 	env->stack_size++;
545 	err = copy_verifier_state(&elem->st, cur);
546 	if (err)
547 		goto err;
548 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
549 		verbose(env, "BPF program is too complex\n");
550 		goto err;
551 	}
552 	return &elem->st;
553 err:
554 	free_verifier_state(env->cur_state, true);
555 	env->cur_state = NULL;
556 	/* pop all elements and return */
557 	while (!pop_stack(env, NULL, NULL));
558 	return NULL;
559 }
560 
561 #define CALLER_SAVED_REGS 6
562 static const int caller_saved[CALLER_SAVED_REGS] = {
563 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
564 };
565 
566 static void __mark_reg_not_init(struct bpf_reg_state *reg);
567 
568 /* Mark the unknown part of a register (variable offset or scalar value) as
569  * known to have the value @imm.
570  */
571 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
572 {
573 	/* Clear id, off, and union(map_ptr, range) */
574 	memset(((u8 *)reg) + sizeof(reg->type), 0,
575 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
576 	reg->var_off = tnum_const(imm);
577 	reg->smin_value = (s64)imm;
578 	reg->smax_value = (s64)imm;
579 	reg->umin_value = imm;
580 	reg->umax_value = imm;
581 }
582 
583 /* Mark the 'variable offset' part of a register as zero.  This should be
584  * used only on registers holding a pointer type.
585  */
586 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
587 {
588 	__mark_reg_known(reg, 0);
589 }
590 
591 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
592 {
593 	__mark_reg_known(reg, 0);
594 	reg->type = SCALAR_VALUE;
595 }
596 
597 static void mark_reg_known_zero(struct bpf_verifier_env *env,
598 				struct bpf_reg_state *regs, u32 regno)
599 {
600 	if (WARN_ON(regno >= MAX_BPF_REG)) {
601 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
602 		/* Something bad happened, let's kill all regs */
603 		for (regno = 0; regno < MAX_BPF_REG; regno++)
604 			__mark_reg_not_init(regs + regno);
605 		return;
606 	}
607 	__mark_reg_known_zero(regs + regno);
608 }
609 
610 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
611 {
612 	return type_is_pkt_pointer(reg->type);
613 }
614 
615 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
616 {
617 	return reg_is_pkt_pointer(reg) ||
618 	       reg->type == PTR_TO_PACKET_END;
619 }
620 
621 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
622 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
623 				    enum bpf_reg_type which)
624 {
625 	/* The register can already have a range from prior markings.
626 	 * This is fine as long as it hasn't been advanced from its
627 	 * origin.
628 	 */
629 	return reg->type == which &&
630 	       reg->id == 0 &&
631 	       reg->off == 0 &&
632 	       tnum_equals_const(reg->var_off, 0);
633 }
634 
635 /* Attempts to improve min/max values based on var_off information */
636 static void __update_reg_bounds(struct bpf_reg_state *reg)
637 {
638 	/* min signed is max(sign bit) | min(other bits) */
639 	reg->smin_value = max_t(s64, reg->smin_value,
640 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
641 	/* max signed is min(sign bit) | max(other bits) */
642 	reg->smax_value = min_t(s64, reg->smax_value,
643 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
644 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
645 	reg->umax_value = min(reg->umax_value,
646 			      reg->var_off.value | reg->var_off.mask);
647 }
648 
649 /* Uses signed min/max values to inform unsigned, and vice-versa */
650 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
651 {
652 	/* Learn sign from signed bounds.
653 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
654 	 * are the same, so combine.  This works even in the negative case, e.g.
655 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
656 	 */
657 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
658 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
659 							  reg->umin_value);
660 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
661 							  reg->umax_value);
662 		return;
663 	}
664 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
665 	 * boundary, so we must be careful.
666 	 */
667 	if ((s64)reg->umax_value >= 0) {
668 		/* Positive.  We can't learn anything from the smin, but smax
669 		 * is positive, hence safe.
670 		 */
671 		reg->smin_value = reg->umin_value;
672 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
673 							  reg->umax_value);
674 	} else if ((s64)reg->umin_value < 0) {
675 		/* Negative.  We can't learn anything from the smax, but smin
676 		 * is negative, hence safe.
677 		 */
678 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
679 							  reg->umin_value);
680 		reg->smax_value = reg->umax_value;
681 	}
682 }
683 
684 /* Attempts to improve var_off based on unsigned min/max information */
685 static void __reg_bound_offset(struct bpf_reg_state *reg)
686 {
687 	reg->var_off = tnum_intersect(reg->var_off,
688 				      tnum_range(reg->umin_value,
689 						 reg->umax_value));
690 }
691 
692 /* Reset the min/max bounds of a register */
693 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
694 {
695 	reg->smin_value = S64_MIN;
696 	reg->smax_value = S64_MAX;
697 	reg->umin_value = 0;
698 	reg->umax_value = U64_MAX;
699 }
700 
701 /* Mark a register as having a completely unknown (scalar) value. */
702 static void __mark_reg_unknown(struct bpf_reg_state *reg)
703 {
704 	/*
705 	 * Clear type, id, off, and union(map_ptr, range) and
706 	 * padding between 'type' and union
707 	 */
708 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
709 	reg->type = SCALAR_VALUE;
710 	reg->var_off = tnum_unknown;
711 	reg->frameno = 0;
712 	__mark_reg_unbounded(reg);
713 }
714 
715 static void mark_reg_unknown(struct bpf_verifier_env *env,
716 			     struct bpf_reg_state *regs, u32 regno)
717 {
718 	if (WARN_ON(regno >= MAX_BPF_REG)) {
719 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
720 		/* Something bad happened, let's kill all regs except FP */
721 		for (regno = 0; regno < BPF_REG_FP; regno++)
722 			__mark_reg_not_init(regs + regno);
723 		return;
724 	}
725 	__mark_reg_unknown(regs + regno);
726 }
727 
728 static void __mark_reg_not_init(struct bpf_reg_state *reg)
729 {
730 	__mark_reg_unknown(reg);
731 	reg->type = NOT_INIT;
732 }
733 
734 static void mark_reg_not_init(struct bpf_verifier_env *env,
735 			      struct bpf_reg_state *regs, u32 regno)
736 {
737 	if (WARN_ON(regno >= MAX_BPF_REG)) {
738 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
739 		/* Something bad happened, let's kill all regs except FP */
740 		for (regno = 0; regno < BPF_REG_FP; regno++)
741 			__mark_reg_not_init(regs + regno);
742 		return;
743 	}
744 	__mark_reg_not_init(regs + regno);
745 }
746 
747 static void init_reg_state(struct bpf_verifier_env *env,
748 			   struct bpf_func_state *state)
749 {
750 	struct bpf_reg_state *regs = state->regs;
751 	int i;
752 
753 	for (i = 0; i < MAX_BPF_REG; i++) {
754 		mark_reg_not_init(env, regs, i);
755 		regs[i].live = REG_LIVE_NONE;
756 		regs[i].parent = NULL;
757 	}
758 
759 	/* frame pointer */
760 	regs[BPF_REG_FP].type = PTR_TO_STACK;
761 	mark_reg_known_zero(env, regs, BPF_REG_FP);
762 	regs[BPF_REG_FP].frameno = state->frameno;
763 
764 	/* 1st arg to a function */
765 	regs[BPF_REG_1].type = PTR_TO_CTX;
766 	mark_reg_known_zero(env, regs, BPF_REG_1);
767 }
768 
769 #define BPF_MAIN_FUNC (-1)
770 static void init_func_state(struct bpf_verifier_env *env,
771 			    struct bpf_func_state *state,
772 			    int callsite, int frameno, int subprogno)
773 {
774 	state->callsite = callsite;
775 	state->frameno = frameno;
776 	state->subprogno = subprogno;
777 	init_reg_state(env, state);
778 }
779 
780 enum reg_arg_type {
781 	SRC_OP,		/* register is used as source operand */
782 	DST_OP,		/* register is used as destination operand */
783 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
784 };
785 
786 static int cmp_subprogs(const void *a, const void *b)
787 {
788 	return ((struct bpf_subprog_info *)a)->start -
789 	       ((struct bpf_subprog_info *)b)->start;
790 }
791 
792 static int find_subprog(struct bpf_verifier_env *env, int off)
793 {
794 	struct bpf_subprog_info *p;
795 
796 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
797 		    sizeof(env->subprog_info[0]), cmp_subprogs);
798 	if (!p)
799 		return -ENOENT;
800 	return p - env->subprog_info;
801 
802 }
803 
804 static int add_subprog(struct bpf_verifier_env *env, int off)
805 {
806 	int insn_cnt = env->prog->len;
807 	int ret;
808 
809 	if (off >= insn_cnt || off < 0) {
810 		verbose(env, "call to invalid destination\n");
811 		return -EINVAL;
812 	}
813 	ret = find_subprog(env, off);
814 	if (ret >= 0)
815 		return 0;
816 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
817 		verbose(env, "too many subprograms\n");
818 		return -E2BIG;
819 	}
820 	env->subprog_info[env->subprog_cnt++].start = off;
821 	sort(env->subprog_info, env->subprog_cnt,
822 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
823 	return 0;
824 }
825 
826 static int check_subprogs(struct bpf_verifier_env *env)
827 {
828 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
829 	struct bpf_subprog_info *subprog = env->subprog_info;
830 	struct bpf_insn *insn = env->prog->insnsi;
831 	int insn_cnt = env->prog->len;
832 
833 	/* Add entry function. */
834 	ret = add_subprog(env, 0);
835 	if (ret < 0)
836 		return ret;
837 
838 	/* determine subprog starts. The end is one before the next starts */
839 	for (i = 0; i < insn_cnt; i++) {
840 		if (insn[i].code != (BPF_JMP | BPF_CALL))
841 			continue;
842 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
843 			continue;
844 		if (!env->allow_ptr_leaks) {
845 			verbose(env, "function calls to other bpf functions are allowed for root only\n");
846 			return -EPERM;
847 		}
848 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
849 			verbose(env, "function calls in offloaded programs are not supported yet\n");
850 			return -EINVAL;
851 		}
852 		ret = add_subprog(env, i + insn[i].imm + 1);
853 		if (ret < 0)
854 			return ret;
855 	}
856 
857 	/* Add a fake 'exit' subprog which could simplify subprog iteration
858 	 * logic. 'subprog_cnt' should not be increased.
859 	 */
860 	subprog[env->subprog_cnt].start = insn_cnt;
861 
862 	if (env->log.level > 1)
863 		for (i = 0; i < env->subprog_cnt; i++)
864 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
865 
866 	/* now check that all jumps are within the same subprog */
867 	subprog_start = subprog[cur_subprog].start;
868 	subprog_end = subprog[cur_subprog + 1].start;
869 	for (i = 0; i < insn_cnt; i++) {
870 		u8 code = insn[i].code;
871 
872 		if (BPF_CLASS(code) != BPF_JMP)
873 			goto next;
874 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
875 			goto next;
876 		off = i + insn[i].off + 1;
877 		if (off < subprog_start || off >= subprog_end) {
878 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
879 			return -EINVAL;
880 		}
881 next:
882 		if (i == subprog_end - 1) {
883 			/* to avoid fall-through from one subprog into another
884 			 * the last insn of the subprog should be either exit
885 			 * or unconditional jump back
886 			 */
887 			if (code != (BPF_JMP | BPF_EXIT) &&
888 			    code != (BPF_JMP | BPF_JA)) {
889 				verbose(env, "last insn is not an exit or jmp\n");
890 				return -EINVAL;
891 			}
892 			subprog_start = subprog_end;
893 			cur_subprog++;
894 			if (cur_subprog < env->subprog_cnt)
895 				subprog_end = subprog[cur_subprog + 1].start;
896 		}
897 	}
898 	return 0;
899 }
900 
901 /* Parentage chain of this register (or stack slot) should take care of all
902  * issues like callee-saved registers, stack slot allocation time, etc.
903  */
904 static int mark_reg_read(struct bpf_verifier_env *env,
905 			 const struct bpf_reg_state *state,
906 			 struct bpf_reg_state *parent)
907 {
908 	bool writes = parent == state->parent; /* Observe write marks */
909 
910 	while (parent) {
911 		/* if read wasn't screened by an earlier write ... */
912 		if (writes && state->live & REG_LIVE_WRITTEN)
913 			break;
914 		/* ... then we depend on parent's value */
915 		parent->live |= REG_LIVE_READ;
916 		state = parent;
917 		parent = state->parent;
918 		writes = true;
919 	}
920 	return 0;
921 }
922 
923 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
924 			 enum reg_arg_type t)
925 {
926 	struct bpf_verifier_state *vstate = env->cur_state;
927 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
928 	struct bpf_reg_state *regs = state->regs;
929 
930 	if (regno >= MAX_BPF_REG) {
931 		verbose(env, "R%d is invalid\n", regno);
932 		return -EINVAL;
933 	}
934 
935 	if (t == SRC_OP) {
936 		/* check whether register used as source operand can be read */
937 		if (regs[regno].type == NOT_INIT) {
938 			verbose(env, "R%d !read_ok\n", regno);
939 			return -EACCES;
940 		}
941 		/* We don't need to worry about FP liveness because it's read-only */
942 		if (regno != BPF_REG_FP)
943 			return mark_reg_read(env, &regs[regno],
944 					     regs[regno].parent);
945 	} else {
946 		/* check whether register used as dest operand can be written to */
947 		if (regno == BPF_REG_FP) {
948 			verbose(env, "frame pointer is read only\n");
949 			return -EACCES;
950 		}
951 		regs[regno].live |= REG_LIVE_WRITTEN;
952 		if (t == DST_OP)
953 			mark_reg_unknown(env, regs, regno);
954 	}
955 	return 0;
956 }
957 
958 static bool is_spillable_regtype(enum bpf_reg_type type)
959 {
960 	switch (type) {
961 	case PTR_TO_MAP_VALUE:
962 	case PTR_TO_MAP_VALUE_OR_NULL:
963 	case PTR_TO_STACK:
964 	case PTR_TO_CTX:
965 	case PTR_TO_PACKET:
966 	case PTR_TO_PACKET_META:
967 	case PTR_TO_PACKET_END:
968 	case CONST_PTR_TO_MAP:
969 		return true;
970 	default:
971 		return false;
972 	}
973 }
974 
975 /* Does this register contain a constant zero? */
976 static bool register_is_null(struct bpf_reg_state *reg)
977 {
978 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
979 }
980 
981 /* check_stack_read/write functions track spill/fill of registers,
982  * stack boundary and alignment are checked in check_mem_access()
983  */
984 static int check_stack_write(struct bpf_verifier_env *env,
985 			     struct bpf_func_state *state, /* func where register points to */
986 			     int off, int size, int value_regno, int insn_idx)
987 {
988 	struct bpf_func_state *cur; /* state of the current function */
989 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
990 	enum bpf_reg_type type;
991 
992 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
993 				 true);
994 	if (err)
995 		return err;
996 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
997 	 * so it's aligned access and [off, off + size) are within stack limits
998 	 */
999 	if (!env->allow_ptr_leaks &&
1000 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
1001 	    size != BPF_REG_SIZE) {
1002 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
1003 		return -EACCES;
1004 	}
1005 
1006 	cur = env->cur_state->frame[env->cur_state->curframe];
1007 	if (value_regno >= 0 &&
1008 	    is_spillable_regtype((type = cur->regs[value_regno].type))) {
1009 
1010 		/* register containing pointer is being spilled into stack */
1011 		if (size != BPF_REG_SIZE) {
1012 			verbose(env, "invalid size of register spill\n");
1013 			return -EACCES;
1014 		}
1015 
1016 		if (state != cur && type == PTR_TO_STACK) {
1017 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1018 			return -EINVAL;
1019 		}
1020 
1021 		/* save register state */
1022 		state->stack[spi].spilled_ptr = cur->regs[value_regno];
1023 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1024 
1025 		for (i = 0; i < BPF_REG_SIZE; i++) {
1026 			if (state->stack[spi].slot_type[i] == STACK_MISC &&
1027 			    !env->allow_ptr_leaks) {
1028 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1029 				int soff = (-spi - 1) * BPF_REG_SIZE;
1030 
1031 				/* detected reuse of integer stack slot with a pointer
1032 				 * which means either llvm is reusing stack slot or
1033 				 * an attacker is trying to exploit CVE-2018-3639
1034 				 * (speculative store bypass)
1035 				 * Have to sanitize that slot with preemptive
1036 				 * store of zero.
1037 				 */
1038 				if (*poff && *poff != soff) {
1039 					/* disallow programs where single insn stores
1040 					 * into two different stack slots, since verifier
1041 					 * cannot sanitize them
1042 					 */
1043 					verbose(env,
1044 						"insn %d cannot access two stack slots fp%d and fp%d",
1045 						insn_idx, *poff, soff);
1046 					return -EINVAL;
1047 				}
1048 				*poff = soff;
1049 			}
1050 			state->stack[spi].slot_type[i] = STACK_SPILL;
1051 		}
1052 	} else {
1053 		u8 type = STACK_MISC;
1054 
1055 		/* regular write of data into stack destroys any spilled ptr */
1056 		state->stack[spi].spilled_ptr.type = NOT_INIT;
1057 
1058 		/* only mark the slot as written if all 8 bytes were written
1059 		 * otherwise read propagation may incorrectly stop too soon
1060 		 * when stack slots are partially written.
1061 		 * This heuristic means that read propagation will be
1062 		 * conservative, since it will add reg_live_read marks
1063 		 * to stack slots all the way to first state when programs
1064 		 * writes+reads less than 8 bytes
1065 		 */
1066 		if (size == BPF_REG_SIZE)
1067 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1068 
1069 		/* when we zero initialize stack slots mark them as such */
1070 		if (value_regno >= 0 &&
1071 		    register_is_null(&cur->regs[value_regno]))
1072 			type = STACK_ZERO;
1073 
1074 		for (i = 0; i < size; i++)
1075 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1076 				type;
1077 	}
1078 	return 0;
1079 }
1080 
1081 static int check_stack_read(struct bpf_verifier_env *env,
1082 			    struct bpf_func_state *reg_state /* func where register points to */,
1083 			    int off, int size, int value_regno)
1084 {
1085 	struct bpf_verifier_state *vstate = env->cur_state;
1086 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1087 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1088 	u8 *stype;
1089 
1090 	if (reg_state->allocated_stack <= slot) {
1091 		verbose(env, "invalid read from stack off %d+0 size %d\n",
1092 			off, size);
1093 		return -EACCES;
1094 	}
1095 	stype = reg_state->stack[spi].slot_type;
1096 
1097 	if (stype[0] == STACK_SPILL) {
1098 		if (size != BPF_REG_SIZE) {
1099 			verbose(env, "invalid size of register spill\n");
1100 			return -EACCES;
1101 		}
1102 		for (i = 1; i < BPF_REG_SIZE; i++) {
1103 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1104 				verbose(env, "corrupted spill memory\n");
1105 				return -EACCES;
1106 			}
1107 		}
1108 
1109 		if (value_regno >= 0) {
1110 			/* restore register state from stack */
1111 			state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1112 			/* mark reg as written since spilled pointer state likely
1113 			 * has its liveness marks cleared by is_state_visited()
1114 			 * which resets stack/reg liveness for state transitions
1115 			 */
1116 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1117 		}
1118 		mark_reg_read(env, &reg_state->stack[spi].spilled_ptr,
1119 			      reg_state->stack[spi].spilled_ptr.parent);
1120 		return 0;
1121 	} else {
1122 		int zeros = 0;
1123 
1124 		for (i = 0; i < size; i++) {
1125 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1126 				continue;
1127 			if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1128 				zeros++;
1129 				continue;
1130 			}
1131 			verbose(env, "invalid read from stack off %d+%d size %d\n",
1132 				off, i, size);
1133 			return -EACCES;
1134 		}
1135 		mark_reg_read(env, &reg_state->stack[spi].spilled_ptr,
1136 			      reg_state->stack[spi].spilled_ptr.parent);
1137 		if (value_regno >= 0) {
1138 			if (zeros == size) {
1139 				/* any size read into register is zero extended,
1140 				 * so the whole register == const_zero
1141 				 */
1142 				__mark_reg_const_zero(&state->regs[value_regno]);
1143 			} else {
1144 				/* have read misc data from the stack */
1145 				mark_reg_unknown(env, state->regs, value_regno);
1146 			}
1147 			state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1148 		}
1149 		return 0;
1150 	}
1151 }
1152 
1153 /* check read/write into map element returned by bpf_map_lookup_elem() */
1154 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1155 			      int size, bool zero_size_allowed)
1156 {
1157 	struct bpf_reg_state *regs = cur_regs(env);
1158 	struct bpf_map *map = regs[regno].map_ptr;
1159 
1160 	if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1161 	    off + size > map->value_size) {
1162 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1163 			map->value_size, off, size);
1164 		return -EACCES;
1165 	}
1166 	return 0;
1167 }
1168 
1169 /* check read/write into a map element with possible variable offset */
1170 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1171 			    int off, int size, bool zero_size_allowed)
1172 {
1173 	struct bpf_verifier_state *vstate = env->cur_state;
1174 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1175 	struct bpf_reg_state *reg = &state->regs[regno];
1176 	int err;
1177 
1178 	/* We may have adjusted the register to this map value, so we
1179 	 * need to try adding each of min_value and max_value to off
1180 	 * to make sure our theoretical access will be safe.
1181 	 */
1182 	if (env->log.level)
1183 		print_verifier_state(env, state);
1184 	/* The minimum value is only important with signed
1185 	 * comparisons where we can't assume the floor of a
1186 	 * value is 0.  If we are using signed variables for our
1187 	 * index'es we need to make sure that whatever we use
1188 	 * will have a set floor within our range.
1189 	 */
1190 	if (reg->smin_value < 0) {
1191 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1192 			regno);
1193 		return -EACCES;
1194 	}
1195 	err = __check_map_access(env, regno, reg->smin_value + off, size,
1196 				 zero_size_allowed);
1197 	if (err) {
1198 		verbose(env, "R%d min value is outside of the array range\n",
1199 			regno);
1200 		return err;
1201 	}
1202 
1203 	/* If we haven't set a max value then we need to bail since we can't be
1204 	 * sure we won't do bad things.
1205 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
1206 	 */
1207 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1208 		verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1209 			regno);
1210 		return -EACCES;
1211 	}
1212 	err = __check_map_access(env, regno, reg->umax_value + off, size,
1213 				 zero_size_allowed);
1214 	if (err)
1215 		verbose(env, "R%d max value is outside of the array range\n",
1216 			regno);
1217 	return err;
1218 }
1219 
1220 #define MAX_PACKET_OFF 0xffff
1221 
1222 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1223 				       const struct bpf_call_arg_meta *meta,
1224 				       enum bpf_access_type t)
1225 {
1226 	switch (env->prog->type) {
1227 	case BPF_PROG_TYPE_LWT_IN:
1228 	case BPF_PROG_TYPE_LWT_OUT:
1229 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1230 	case BPF_PROG_TYPE_SK_REUSEPORT:
1231 		/* dst_input() and dst_output() can't write for now */
1232 		if (t == BPF_WRITE)
1233 			return false;
1234 		/* fallthrough */
1235 	case BPF_PROG_TYPE_SCHED_CLS:
1236 	case BPF_PROG_TYPE_SCHED_ACT:
1237 	case BPF_PROG_TYPE_XDP:
1238 	case BPF_PROG_TYPE_LWT_XMIT:
1239 	case BPF_PROG_TYPE_SK_SKB:
1240 	case BPF_PROG_TYPE_SK_MSG:
1241 		if (meta)
1242 			return meta->pkt_access;
1243 
1244 		env->seen_direct_write = true;
1245 		return true;
1246 	default:
1247 		return false;
1248 	}
1249 }
1250 
1251 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1252 				 int off, int size, bool zero_size_allowed)
1253 {
1254 	struct bpf_reg_state *regs = cur_regs(env);
1255 	struct bpf_reg_state *reg = &regs[regno];
1256 
1257 	if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1258 	    (u64)off + size > reg->range) {
1259 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1260 			off, size, regno, reg->id, reg->off, reg->range);
1261 		return -EACCES;
1262 	}
1263 	return 0;
1264 }
1265 
1266 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1267 			       int size, bool zero_size_allowed)
1268 {
1269 	struct bpf_reg_state *regs = cur_regs(env);
1270 	struct bpf_reg_state *reg = &regs[regno];
1271 	int err;
1272 
1273 	/* We may have added a variable offset to the packet pointer; but any
1274 	 * reg->range we have comes after that.  We are only checking the fixed
1275 	 * offset.
1276 	 */
1277 
1278 	/* We don't allow negative numbers, because we aren't tracking enough
1279 	 * detail to prove they're safe.
1280 	 */
1281 	if (reg->smin_value < 0) {
1282 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1283 			regno);
1284 		return -EACCES;
1285 	}
1286 	err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1287 	if (err) {
1288 		verbose(env, "R%d offset is outside of the packet\n", regno);
1289 		return err;
1290 	}
1291 	return err;
1292 }
1293 
1294 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
1295 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1296 			    enum bpf_access_type t, enum bpf_reg_type *reg_type)
1297 {
1298 	struct bpf_insn_access_aux info = {
1299 		.reg_type = *reg_type,
1300 	};
1301 
1302 	if (env->ops->is_valid_access &&
1303 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1304 		/* A non zero info.ctx_field_size indicates that this field is a
1305 		 * candidate for later verifier transformation to load the whole
1306 		 * field and then apply a mask when accessed with a narrower
1307 		 * access than actual ctx access size. A zero info.ctx_field_size
1308 		 * will only allow for whole field access and rejects any other
1309 		 * type of narrower access.
1310 		 */
1311 		*reg_type = info.reg_type;
1312 
1313 		env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1314 		/* remember the offset of last byte accessed in ctx */
1315 		if (env->prog->aux->max_ctx_offset < off + size)
1316 			env->prog->aux->max_ctx_offset = off + size;
1317 		return 0;
1318 	}
1319 
1320 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1321 	return -EACCES;
1322 }
1323 
1324 static bool __is_pointer_value(bool allow_ptr_leaks,
1325 			       const struct bpf_reg_state *reg)
1326 {
1327 	if (allow_ptr_leaks)
1328 		return false;
1329 
1330 	return reg->type != SCALAR_VALUE;
1331 }
1332 
1333 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1334 {
1335 	return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1336 }
1337 
1338 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1339 {
1340 	const struct bpf_reg_state *reg = cur_regs(env) + regno;
1341 
1342 	return reg->type == PTR_TO_CTX;
1343 }
1344 
1345 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1346 {
1347 	const struct bpf_reg_state *reg = cur_regs(env) + regno;
1348 
1349 	return type_is_pkt_pointer(reg->type);
1350 }
1351 
1352 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1353 				   const struct bpf_reg_state *reg,
1354 				   int off, int size, bool strict)
1355 {
1356 	struct tnum reg_off;
1357 	int ip_align;
1358 
1359 	/* Byte size accesses are always allowed. */
1360 	if (!strict || size == 1)
1361 		return 0;
1362 
1363 	/* For platforms that do not have a Kconfig enabling
1364 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1365 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
1366 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1367 	 * to this code only in strict mode where we want to emulate
1368 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
1369 	 * unconditional IP align value of '2'.
1370 	 */
1371 	ip_align = 2;
1372 
1373 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1374 	if (!tnum_is_aligned(reg_off, size)) {
1375 		char tn_buf[48];
1376 
1377 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1378 		verbose(env,
1379 			"misaligned packet access off %d+%s+%d+%d size %d\n",
1380 			ip_align, tn_buf, reg->off, off, size);
1381 		return -EACCES;
1382 	}
1383 
1384 	return 0;
1385 }
1386 
1387 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1388 				       const struct bpf_reg_state *reg,
1389 				       const char *pointer_desc,
1390 				       int off, int size, bool strict)
1391 {
1392 	struct tnum reg_off;
1393 
1394 	/* Byte size accesses are always allowed. */
1395 	if (!strict || size == 1)
1396 		return 0;
1397 
1398 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1399 	if (!tnum_is_aligned(reg_off, size)) {
1400 		char tn_buf[48];
1401 
1402 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1403 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1404 			pointer_desc, tn_buf, reg->off, off, size);
1405 		return -EACCES;
1406 	}
1407 
1408 	return 0;
1409 }
1410 
1411 static int check_ptr_alignment(struct bpf_verifier_env *env,
1412 			       const struct bpf_reg_state *reg, int off,
1413 			       int size, bool strict_alignment_once)
1414 {
1415 	bool strict = env->strict_alignment || strict_alignment_once;
1416 	const char *pointer_desc = "";
1417 
1418 	switch (reg->type) {
1419 	case PTR_TO_PACKET:
1420 	case PTR_TO_PACKET_META:
1421 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
1422 		 * right in front, treat it the very same way.
1423 		 */
1424 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
1425 	case PTR_TO_MAP_VALUE:
1426 		pointer_desc = "value ";
1427 		break;
1428 	case PTR_TO_CTX:
1429 		pointer_desc = "context ";
1430 		break;
1431 	case PTR_TO_STACK:
1432 		pointer_desc = "stack ";
1433 		/* The stack spill tracking logic in check_stack_write()
1434 		 * and check_stack_read() relies on stack accesses being
1435 		 * aligned.
1436 		 */
1437 		strict = true;
1438 		break;
1439 	default:
1440 		break;
1441 	}
1442 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1443 					   strict);
1444 }
1445 
1446 static int update_stack_depth(struct bpf_verifier_env *env,
1447 			      const struct bpf_func_state *func,
1448 			      int off)
1449 {
1450 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
1451 
1452 	if (stack >= -off)
1453 		return 0;
1454 
1455 	/* update known max for given subprogram */
1456 	env->subprog_info[func->subprogno].stack_depth = -off;
1457 	return 0;
1458 }
1459 
1460 /* starting from main bpf function walk all instructions of the function
1461  * and recursively walk all callees that given function can call.
1462  * Ignore jump and exit insns.
1463  * Since recursion is prevented by check_cfg() this algorithm
1464  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1465  */
1466 static int check_max_stack_depth(struct bpf_verifier_env *env)
1467 {
1468 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1469 	struct bpf_subprog_info *subprog = env->subprog_info;
1470 	struct bpf_insn *insn = env->prog->insnsi;
1471 	int ret_insn[MAX_CALL_FRAMES];
1472 	int ret_prog[MAX_CALL_FRAMES];
1473 
1474 process_func:
1475 	/* round up to 32-bytes, since this is granularity
1476 	 * of interpreter stack size
1477 	 */
1478 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1479 	if (depth > MAX_BPF_STACK) {
1480 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
1481 			frame + 1, depth);
1482 		return -EACCES;
1483 	}
1484 continue_func:
1485 	subprog_end = subprog[idx + 1].start;
1486 	for (; i < subprog_end; i++) {
1487 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1488 			continue;
1489 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1490 			continue;
1491 		/* remember insn and function to return to */
1492 		ret_insn[frame] = i + 1;
1493 		ret_prog[frame] = idx;
1494 
1495 		/* find the callee */
1496 		i = i + insn[i].imm + 1;
1497 		idx = find_subprog(env, i);
1498 		if (idx < 0) {
1499 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1500 				  i);
1501 			return -EFAULT;
1502 		}
1503 		frame++;
1504 		if (frame >= MAX_CALL_FRAMES) {
1505 			WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1506 			return -EFAULT;
1507 		}
1508 		goto process_func;
1509 	}
1510 	/* end of for() loop means the last insn of the 'subprog'
1511 	 * was reached. Doesn't matter whether it was JA or EXIT
1512 	 */
1513 	if (frame == 0)
1514 		return 0;
1515 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1516 	frame--;
1517 	i = ret_insn[frame];
1518 	idx = ret_prog[frame];
1519 	goto continue_func;
1520 }
1521 
1522 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1523 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1524 				  const struct bpf_insn *insn, int idx)
1525 {
1526 	int start = idx + insn->imm + 1, subprog;
1527 
1528 	subprog = find_subprog(env, start);
1529 	if (subprog < 0) {
1530 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1531 			  start);
1532 		return -EFAULT;
1533 	}
1534 	return env->subprog_info[subprog].stack_depth;
1535 }
1536 #endif
1537 
1538 static int check_ctx_reg(struct bpf_verifier_env *env,
1539 			 const struct bpf_reg_state *reg, int regno)
1540 {
1541 	/* Access to ctx or passing it to a helper is only allowed in
1542 	 * its original, unmodified form.
1543 	 */
1544 
1545 	if (reg->off) {
1546 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1547 			regno, reg->off);
1548 		return -EACCES;
1549 	}
1550 
1551 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1552 		char tn_buf[48];
1553 
1554 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1555 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1556 		return -EACCES;
1557 	}
1558 
1559 	return 0;
1560 }
1561 
1562 /* truncate register to smaller size (in bytes)
1563  * must be called with size < BPF_REG_SIZE
1564  */
1565 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1566 {
1567 	u64 mask;
1568 
1569 	/* clear high bits in bit representation */
1570 	reg->var_off = tnum_cast(reg->var_off, size);
1571 
1572 	/* fix arithmetic bounds */
1573 	mask = ((u64)1 << (size * 8)) - 1;
1574 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1575 		reg->umin_value &= mask;
1576 		reg->umax_value &= mask;
1577 	} else {
1578 		reg->umin_value = 0;
1579 		reg->umax_value = mask;
1580 	}
1581 	reg->smin_value = reg->umin_value;
1582 	reg->smax_value = reg->umax_value;
1583 }
1584 
1585 /* check whether memory at (regno + off) is accessible for t = (read | write)
1586  * if t==write, value_regno is a register which value is stored into memory
1587  * if t==read, value_regno is a register which will receive the value from memory
1588  * if t==write && value_regno==-1, some unknown value is stored into memory
1589  * if t==read && value_regno==-1, don't care what we read from memory
1590  */
1591 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1592 			    int off, int bpf_size, enum bpf_access_type t,
1593 			    int value_regno, bool strict_alignment_once)
1594 {
1595 	struct bpf_reg_state *regs = cur_regs(env);
1596 	struct bpf_reg_state *reg = regs + regno;
1597 	struct bpf_func_state *state;
1598 	int size, err = 0;
1599 
1600 	size = bpf_size_to_bytes(bpf_size);
1601 	if (size < 0)
1602 		return size;
1603 
1604 	/* alignment checks will add in reg->off themselves */
1605 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1606 	if (err)
1607 		return err;
1608 
1609 	/* for access checks, reg->off is just part of off */
1610 	off += reg->off;
1611 
1612 	if (reg->type == PTR_TO_MAP_VALUE) {
1613 		if (t == BPF_WRITE && value_regno >= 0 &&
1614 		    is_pointer_value(env, value_regno)) {
1615 			verbose(env, "R%d leaks addr into map\n", value_regno);
1616 			return -EACCES;
1617 		}
1618 
1619 		err = check_map_access(env, regno, off, size, false);
1620 		if (!err && t == BPF_READ && value_regno >= 0)
1621 			mark_reg_unknown(env, regs, value_regno);
1622 
1623 	} else if (reg->type == PTR_TO_CTX) {
1624 		enum bpf_reg_type reg_type = SCALAR_VALUE;
1625 
1626 		if (t == BPF_WRITE && value_regno >= 0 &&
1627 		    is_pointer_value(env, value_regno)) {
1628 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
1629 			return -EACCES;
1630 		}
1631 
1632 		err = check_ctx_reg(env, reg, regno);
1633 		if (err < 0)
1634 			return err;
1635 
1636 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
1637 		if (!err && t == BPF_READ && value_regno >= 0) {
1638 			/* ctx access returns either a scalar, or a
1639 			 * PTR_TO_PACKET[_META,_END]. In the latter
1640 			 * case, we know the offset is zero.
1641 			 */
1642 			if (reg_type == SCALAR_VALUE)
1643 				mark_reg_unknown(env, regs, value_regno);
1644 			else
1645 				mark_reg_known_zero(env, regs,
1646 						    value_regno);
1647 			regs[value_regno].type = reg_type;
1648 		}
1649 
1650 	} else if (reg->type == PTR_TO_STACK) {
1651 		/* stack accesses must be at a fixed offset, so that we can
1652 		 * determine what type of data were returned.
1653 		 * See check_stack_read().
1654 		 */
1655 		if (!tnum_is_const(reg->var_off)) {
1656 			char tn_buf[48];
1657 
1658 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1659 			verbose(env, "variable stack access var_off=%s off=%d size=%d",
1660 				tn_buf, off, size);
1661 			return -EACCES;
1662 		}
1663 		off += reg->var_off.value;
1664 		if (off >= 0 || off < -MAX_BPF_STACK) {
1665 			verbose(env, "invalid stack off=%d size=%d\n", off,
1666 				size);
1667 			return -EACCES;
1668 		}
1669 
1670 		state = func(env, reg);
1671 		err = update_stack_depth(env, state, off);
1672 		if (err)
1673 			return err;
1674 
1675 		if (t == BPF_WRITE)
1676 			err = check_stack_write(env, state, off, size,
1677 						value_regno, insn_idx);
1678 		else
1679 			err = check_stack_read(env, state, off, size,
1680 					       value_regno);
1681 	} else if (reg_is_pkt_pointer(reg)) {
1682 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1683 			verbose(env, "cannot write into packet\n");
1684 			return -EACCES;
1685 		}
1686 		if (t == BPF_WRITE && value_regno >= 0 &&
1687 		    is_pointer_value(env, value_regno)) {
1688 			verbose(env, "R%d leaks addr into packet\n",
1689 				value_regno);
1690 			return -EACCES;
1691 		}
1692 		err = check_packet_access(env, regno, off, size, false);
1693 		if (!err && t == BPF_READ && value_regno >= 0)
1694 			mark_reg_unknown(env, regs, value_regno);
1695 	} else {
1696 		verbose(env, "R%d invalid mem access '%s'\n", regno,
1697 			reg_type_str[reg->type]);
1698 		return -EACCES;
1699 	}
1700 
1701 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1702 	    regs[value_regno].type == SCALAR_VALUE) {
1703 		/* b/h/w load zero-extends, mark upper bits as known 0 */
1704 		coerce_reg_to_size(&regs[value_regno], size);
1705 	}
1706 	return err;
1707 }
1708 
1709 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1710 {
1711 	int err;
1712 
1713 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1714 	    insn->imm != 0) {
1715 		verbose(env, "BPF_XADD uses reserved fields\n");
1716 		return -EINVAL;
1717 	}
1718 
1719 	/* check src1 operand */
1720 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
1721 	if (err)
1722 		return err;
1723 
1724 	/* check src2 operand */
1725 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1726 	if (err)
1727 		return err;
1728 
1729 	if (is_pointer_value(env, insn->src_reg)) {
1730 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1731 		return -EACCES;
1732 	}
1733 
1734 	if (is_ctx_reg(env, insn->dst_reg) ||
1735 	    is_pkt_reg(env, insn->dst_reg)) {
1736 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1737 			insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1738 			"context" : "packet");
1739 		return -EACCES;
1740 	}
1741 
1742 	/* check whether atomic_add can read the memory */
1743 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1744 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
1745 	if (err)
1746 		return err;
1747 
1748 	/* check whether atomic_add can write into the same memory */
1749 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1750 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1751 }
1752 
1753 /* when register 'regno' is passed into function that will read 'access_size'
1754  * bytes from that pointer, make sure that it's within stack boundary
1755  * and all elements of stack are initialized.
1756  * Unlike most pointer bounds-checking functions, this one doesn't take an
1757  * 'off' argument, so it has to add in reg->off itself.
1758  */
1759 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1760 				int access_size, bool zero_size_allowed,
1761 				struct bpf_call_arg_meta *meta)
1762 {
1763 	struct bpf_reg_state *reg = cur_regs(env) + regno;
1764 	struct bpf_func_state *state = func(env, reg);
1765 	int off, i, slot, spi;
1766 
1767 	if (reg->type != PTR_TO_STACK) {
1768 		/* Allow zero-byte read from NULL, regardless of pointer type */
1769 		if (zero_size_allowed && access_size == 0 &&
1770 		    register_is_null(reg))
1771 			return 0;
1772 
1773 		verbose(env, "R%d type=%s expected=%s\n", regno,
1774 			reg_type_str[reg->type],
1775 			reg_type_str[PTR_TO_STACK]);
1776 		return -EACCES;
1777 	}
1778 
1779 	/* Only allow fixed-offset stack reads */
1780 	if (!tnum_is_const(reg->var_off)) {
1781 		char tn_buf[48];
1782 
1783 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1784 		verbose(env, "invalid variable stack read R%d var_off=%s\n",
1785 			regno, tn_buf);
1786 		return -EACCES;
1787 	}
1788 	off = reg->off + reg->var_off.value;
1789 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1790 	    access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1791 		verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1792 			regno, off, access_size);
1793 		return -EACCES;
1794 	}
1795 
1796 	if (meta && meta->raw_mode) {
1797 		meta->access_size = access_size;
1798 		meta->regno = regno;
1799 		return 0;
1800 	}
1801 
1802 	for (i = 0; i < access_size; i++) {
1803 		u8 *stype;
1804 
1805 		slot = -(off + i) - 1;
1806 		spi = slot / BPF_REG_SIZE;
1807 		if (state->allocated_stack <= slot)
1808 			goto err;
1809 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1810 		if (*stype == STACK_MISC)
1811 			goto mark;
1812 		if (*stype == STACK_ZERO) {
1813 			/* helper can write anything into the stack */
1814 			*stype = STACK_MISC;
1815 			goto mark;
1816 		}
1817 err:
1818 		verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1819 			off, i, access_size);
1820 		return -EACCES;
1821 mark:
1822 		/* reading any byte out of 8-byte 'spill_slot' will cause
1823 		 * the whole slot to be marked as 'read'
1824 		 */
1825 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
1826 			      state->stack[spi].spilled_ptr.parent);
1827 	}
1828 	return update_stack_depth(env, state, off);
1829 }
1830 
1831 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1832 				   int access_size, bool zero_size_allowed,
1833 				   struct bpf_call_arg_meta *meta)
1834 {
1835 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1836 
1837 	switch (reg->type) {
1838 	case PTR_TO_PACKET:
1839 	case PTR_TO_PACKET_META:
1840 		return check_packet_access(env, regno, reg->off, access_size,
1841 					   zero_size_allowed);
1842 	case PTR_TO_MAP_VALUE:
1843 		return check_map_access(env, regno, reg->off, access_size,
1844 					zero_size_allowed);
1845 	default: /* scalar_value|ptr_to_stack or invalid ptr */
1846 		return check_stack_boundary(env, regno, access_size,
1847 					    zero_size_allowed, meta);
1848 	}
1849 }
1850 
1851 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1852 {
1853 	return type == ARG_PTR_TO_MEM ||
1854 	       type == ARG_PTR_TO_MEM_OR_NULL ||
1855 	       type == ARG_PTR_TO_UNINIT_MEM;
1856 }
1857 
1858 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1859 {
1860 	return type == ARG_CONST_SIZE ||
1861 	       type == ARG_CONST_SIZE_OR_ZERO;
1862 }
1863 
1864 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1865 			  enum bpf_arg_type arg_type,
1866 			  struct bpf_call_arg_meta *meta)
1867 {
1868 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1869 	enum bpf_reg_type expected_type, type = reg->type;
1870 	int err = 0;
1871 
1872 	if (arg_type == ARG_DONTCARE)
1873 		return 0;
1874 
1875 	err = check_reg_arg(env, regno, SRC_OP);
1876 	if (err)
1877 		return err;
1878 
1879 	if (arg_type == ARG_ANYTHING) {
1880 		if (is_pointer_value(env, regno)) {
1881 			verbose(env, "R%d leaks addr into helper function\n",
1882 				regno);
1883 			return -EACCES;
1884 		}
1885 		return 0;
1886 	}
1887 
1888 	if (type_is_pkt_pointer(type) &&
1889 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1890 		verbose(env, "helper access to the packet is not allowed\n");
1891 		return -EACCES;
1892 	}
1893 
1894 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
1895 	    arg_type == ARG_PTR_TO_MAP_VALUE) {
1896 		expected_type = PTR_TO_STACK;
1897 		if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
1898 		    type != expected_type)
1899 			goto err_type;
1900 	} else if (arg_type == ARG_CONST_SIZE ||
1901 		   arg_type == ARG_CONST_SIZE_OR_ZERO) {
1902 		expected_type = SCALAR_VALUE;
1903 		if (type != expected_type)
1904 			goto err_type;
1905 	} else if (arg_type == ARG_CONST_MAP_PTR) {
1906 		expected_type = CONST_PTR_TO_MAP;
1907 		if (type != expected_type)
1908 			goto err_type;
1909 	} else if (arg_type == ARG_PTR_TO_CTX) {
1910 		expected_type = PTR_TO_CTX;
1911 		if (type != expected_type)
1912 			goto err_type;
1913 		err = check_ctx_reg(env, reg, regno);
1914 		if (err < 0)
1915 			return err;
1916 	} else if (arg_type_is_mem_ptr(arg_type)) {
1917 		expected_type = PTR_TO_STACK;
1918 		/* One exception here. In case function allows for NULL to be
1919 		 * passed in as argument, it's a SCALAR_VALUE type. Final test
1920 		 * happens during stack boundary checking.
1921 		 */
1922 		if (register_is_null(reg) &&
1923 		    arg_type == ARG_PTR_TO_MEM_OR_NULL)
1924 			/* final test in check_stack_boundary() */;
1925 		else if (!type_is_pkt_pointer(type) &&
1926 			 type != PTR_TO_MAP_VALUE &&
1927 			 type != expected_type)
1928 			goto err_type;
1929 		meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1930 	} else {
1931 		verbose(env, "unsupported arg_type %d\n", arg_type);
1932 		return -EFAULT;
1933 	}
1934 
1935 	if (arg_type == ARG_CONST_MAP_PTR) {
1936 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1937 		meta->map_ptr = reg->map_ptr;
1938 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1939 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
1940 		 * check that [key, key + map->key_size) are within
1941 		 * stack limits and initialized
1942 		 */
1943 		if (!meta->map_ptr) {
1944 			/* in function declaration map_ptr must come before
1945 			 * map_key, so that it's verified and known before
1946 			 * we have to check map_key here. Otherwise it means
1947 			 * that kernel subsystem misconfigured verifier
1948 			 */
1949 			verbose(env, "invalid map_ptr to access map->key\n");
1950 			return -EACCES;
1951 		}
1952 		err = check_helper_mem_access(env, regno,
1953 					      meta->map_ptr->key_size, false,
1954 					      NULL);
1955 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1956 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
1957 		 * check [value, value + map->value_size) validity
1958 		 */
1959 		if (!meta->map_ptr) {
1960 			/* kernel subsystem misconfigured verifier */
1961 			verbose(env, "invalid map_ptr to access map->value\n");
1962 			return -EACCES;
1963 		}
1964 		err = check_helper_mem_access(env, regno,
1965 					      meta->map_ptr->value_size, false,
1966 					      NULL);
1967 	} else if (arg_type_is_mem_size(arg_type)) {
1968 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1969 
1970 		/* remember the mem_size which may be used later
1971 		 * to refine return values.
1972 		 */
1973 		meta->msize_smax_value = reg->smax_value;
1974 		meta->msize_umax_value = reg->umax_value;
1975 
1976 		/* The register is SCALAR_VALUE; the access check
1977 		 * happens using its boundaries.
1978 		 */
1979 		if (!tnum_is_const(reg->var_off))
1980 			/* For unprivileged variable accesses, disable raw
1981 			 * mode so that the program is required to
1982 			 * initialize all the memory that the helper could
1983 			 * just partially fill up.
1984 			 */
1985 			meta = NULL;
1986 
1987 		if (reg->smin_value < 0) {
1988 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
1989 				regno);
1990 			return -EACCES;
1991 		}
1992 
1993 		if (reg->umin_value == 0) {
1994 			err = check_helper_mem_access(env, regno - 1, 0,
1995 						      zero_size_allowed,
1996 						      meta);
1997 			if (err)
1998 				return err;
1999 		}
2000 
2001 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2002 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2003 				regno);
2004 			return -EACCES;
2005 		}
2006 		err = check_helper_mem_access(env, regno - 1,
2007 					      reg->umax_value,
2008 					      zero_size_allowed, meta);
2009 	}
2010 
2011 	return err;
2012 err_type:
2013 	verbose(env, "R%d type=%s expected=%s\n", regno,
2014 		reg_type_str[type], reg_type_str[expected_type]);
2015 	return -EACCES;
2016 }
2017 
2018 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2019 					struct bpf_map *map, int func_id)
2020 {
2021 	if (!map)
2022 		return 0;
2023 
2024 	/* We need a two way check, first is from map perspective ... */
2025 	switch (map->map_type) {
2026 	case BPF_MAP_TYPE_PROG_ARRAY:
2027 		if (func_id != BPF_FUNC_tail_call)
2028 			goto error;
2029 		break;
2030 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2031 		if (func_id != BPF_FUNC_perf_event_read &&
2032 		    func_id != BPF_FUNC_perf_event_output &&
2033 		    func_id != BPF_FUNC_perf_event_read_value)
2034 			goto error;
2035 		break;
2036 	case BPF_MAP_TYPE_STACK_TRACE:
2037 		if (func_id != BPF_FUNC_get_stackid)
2038 			goto error;
2039 		break;
2040 	case BPF_MAP_TYPE_CGROUP_ARRAY:
2041 		if (func_id != BPF_FUNC_skb_under_cgroup &&
2042 		    func_id != BPF_FUNC_current_task_under_cgroup)
2043 			goto error;
2044 		break;
2045 	case BPF_MAP_TYPE_CGROUP_STORAGE:
2046 		if (func_id != BPF_FUNC_get_local_storage)
2047 			goto error;
2048 		break;
2049 	/* devmap returns a pointer to a live net_device ifindex that we cannot
2050 	 * allow to be modified from bpf side. So do not allow lookup elements
2051 	 * for now.
2052 	 */
2053 	case BPF_MAP_TYPE_DEVMAP:
2054 		if (func_id != BPF_FUNC_redirect_map)
2055 			goto error;
2056 		break;
2057 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
2058 	 * appear.
2059 	 */
2060 	case BPF_MAP_TYPE_CPUMAP:
2061 	case BPF_MAP_TYPE_XSKMAP:
2062 		if (func_id != BPF_FUNC_redirect_map)
2063 			goto error;
2064 		break;
2065 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2066 	case BPF_MAP_TYPE_HASH_OF_MAPS:
2067 		if (func_id != BPF_FUNC_map_lookup_elem)
2068 			goto error;
2069 		break;
2070 	case BPF_MAP_TYPE_SOCKMAP:
2071 		if (func_id != BPF_FUNC_sk_redirect_map &&
2072 		    func_id != BPF_FUNC_sock_map_update &&
2073 		    func_id != BPF_FUNC_map_delete_elem &&
2074 		    func_id != BPF_FUNC_msg_redirect_map)
2075 			goto error;
2076 		break;
2077 	case BPF_MAP_TYPE_SOCKHASH:
2078 		if (func_id != BPF_FUNC_sk_redirect_hash &&
2079 		    func_id != BPF_FUNC_sock_hash_update &&
2080 		    func_id != BPF_FUNC_map_delete_elem &&
2081 		    func_id != BPF_FUNC_msg_redirect_hash)
2082 			goto error;
2083 		break;
2084 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2085 		if (func_id != BPF_FUNC_sk_select_reuseport)
2086 			goto error;
2087 		break;
2088 	default:
2089 		break;
2090 	}
2091 
2092 	/* ... and second from the function itself. */
2093 	switch (func_id) {
2094 	case BPF_FUNC_tail_call:
2095 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2096 			goto error;
2097 		if (env->subprog_cnt > 1) {
2098 			verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2099 			return -EINVAL;
2100 		}
2101 		break;
2102 	case BPF_FUNC_perf_event_read:
2103 	case BPF_FUNC_perf_event_output:
2104 	case BPF_FUNC_perf_event_read_value:
2105 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2106 			goto error;
2107 		break;
2108 	case BPF_FUNC_get_stackid:
2109 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2110 			goto error;
2111 		break;
2112 	case BPF_FUNC_current_task_under_cgroup:
2113 	case BPF_FUNC_skb_under_cgroup:
2114 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2115 			goto error;
2116 		break;
2117 	case BPF_FUNC_redirect_map:
2118 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2119 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
2120 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
2121 			goto error;
2122 		break;
2123 	case BPF_FUNC_sk_redirect_map:
2124 	case BPF_FUNC_msg_redirect_map:
2125 	case BPF_FUNC_sock_map_update:
2126 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2127 			goto error;
2128 		break;
2129 	case BPF_FUNC_sk_redirect_hash:
2130 	case BPF_FUNC_msg_redirect_hash:
2131 	case BPF_FUNC_sock_hash_update:
2132 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2133 			goto error;
2134 		break;
2135 	case BPF_FUNC_get_local_storage:
2136 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
2137 			goto error;
2138 		break;
2139 	case BPF_FUNC_sk_select_reuseport:
2140 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2141 			goto error;
2142 		break;
2143 	default:
2144 		break;
2145 	}
2146 
2147 	return 0;
2148 error:
2149 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
2150 		map->map_type, func_id_name(func_id), func_id);
2151 	return -EINVAL;
2152 }
2153 
2154 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2155 {
2156 	int count = 0;
2157 
2158 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2159 		count++;
2160 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2161 		count++;
2162 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2163 		count++;
2164 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2165 		count++;
2166 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2167 		count++;
2168 
2169 	/* We only support one arg being in raw mode at the moment,
2170 	 * which is sufficient for the helper functions we have
2171 	 * right now.
2172 	 */
2173 	return count <= 1;
2174 }
2175 
2176 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2177 				    enum bpf_arg_type arg_next)
2178 {
2179 	return (arg_type_is_mem_ptr(arg_curr) &&
2180 	        !arg_type_is_mem_size(arg_next)) ||
2181 	       (!arg_type_is_mem_ptr(arg_curr) &&
2182 		arg_type_is_mem_size(arg_next));
2183 }
2184 
2185 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2186 {
2187 	/* bpf_xxx(..., buf, len) call will access 'len'
2188 	 * bytes from memory 'buf'. Both arg types need
2189 	 * to be paired, so make sure there's no buggy
2190 	 * helper function specification.
2191 	 */
2192 	if (arg_type_is_mem_size(fn->arg1_type) ||
2193 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
2194 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2195 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2196 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2197 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2198 		return false;
2199 
2200 	return true;
2201 }
2202 
2203 static int check_func_proto(const struct bpf_func_proto *fn)
2204 {
2205 	return check_raw_mode_ok(fn) &&
2206 	       check_arg_pair_ok(fn) ? 0 : -EINVAL;
2207 }
2208 
2209 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2210  * are now invalid, so turn them into unknown SCALAR_VALUE.
2211  */
2212 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2213 				     struct bpf_func_state *state)
2214 {
2215 	struct bpf_reg_state *regs = state->regs, *reg;
2216 	int i;
2217 
2218 	for (i = 0; i < MAX_BPF_REG; i++)
2219 		if (reg_is_pkt_pointer_any(&regs[i]))
2220 			mark_reg_unknown(env, regs, i);
2221 
2222 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2223 		if (state->stack[i].slot_type[0] != STACK_SPILL)
2224 			continue;
2225 		reg = &state->stack[i].spilled_ptr;
2226 		if (reg_is_pkt_pointer_any(reg))
2227 			__mark_reg_unknown(reg);
2228 	}
2229 }
2230 
2231 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2232 {
2233 	struct bpf_verifier_state *vstate = env->cur_state;
2234 	int i;
2235 
2236 	for (i = 0; i <= vstate->curframe; i++)
2237 		__clear_all_pkt_pointers(env, vstate->frame[i]);
2238 }
2239 
2240 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2241 			   int *insn_idx)
2242 {
2243 	struct bpf_verifier_state *state = env->cur_state;
2244 	struct bpf_func_state *caller, *callee;
2245 	int i, subprog, target_insn;
2246 
2247 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2248 		verbose(env, "the call stack of %d frames is too deep\n",
2249 			state->curframe + 2);
2250 		return -E2BIG;
2251 	}
2252 
2253 	target_insn = *insn_idx + insn->imm;
2254 	subprog = find_subprog(env, target_insn + 1);
2255 	if (subprog < 0) {
2256 		verbose(env, "verifier bug. No program starts at insn %d\n",
2257 			target_insn + 1);
2258 		return -EFAULT;
2259 	}
2260 
2261 	caller = state->frame[state->curframe];
2262 	if (state->frame[state->curframe + 1]) {
2263 		verbose(env, "verifier bug. Frame %d already allocated\n",
2264 			state->curframe + 1);
2265 		return -EFAULT;
2266 	}
2267 
2268 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2269 	if (!callee)
2270 		return -ENOMEM;
2271 	state->frame[state->curframe + 1] = callee;
2272 
2273 	/* callee cannot access r0, r6 - r9 for reading and has to write
2274 	 * into its own stack before reading from it.
2275 	 * callee can read/write into caller's stack
2276 	 */
2277 	init_func_state(env, callee,
2278 			/* remember the callsite, it will be used by bpf_exit */
2279 			*insn_idx /* callsite */,
2280 			state->curframe + 1 /* frameno within this callchain */,
2281 			subprog /* subprog number within this prog */);
2282 
2283 	/* copy r1 - r5 args that callee can access.  The copy includes parent
2284 	 * pointers, which connects us up to the liveness chain
2285 	 */
2286 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2287 		callee->regs[i] = caller->regs[i];
2288 
2289 	/* after the call registers r0 - r5 were scratched */
2290 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
2291 		mark_reg_not_init(env, caller->regs, caller_saved[i]);
2292 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2293 	}
2294 
2295 	/* only increment it after check_reg_arg() finished */
2296 	state->curframe++;
2297 
2298 	/* and go analyze first insn of the callee */
2299 	*insn_idx = target_insn;
2300 
2301 	if (env->log.level) {
2302 		verbose(env, "caller:\n");
2303 		print_verifier_state(env, caller);
2304 		verbose(env, "callee:\n");
2305 		print_verifier_state(env, callee);
2306 	}
2307 	return 0;
2308 }
2309 
2310 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2311 {
2312 	struct bpf_verifier_state *state = env->cur_state;
2313 	struct bpf_func_state *caller, *callee;
2314 	struct bpf_reg_state *r0;
2315 
2316 	callee = state->frame[state->curframe];
2317 	r0 = &callee->regs[BPF_REG_0];
2318 	if (r0->type == PTR_TO_STACK) {
2319 		/* technically it's ok to return caller's stack pointer
2320 		 * (or caller's caller's pointer) back to the caller,
2321 		 * since these pointers are valid. Only current stack
2322 		 * pointer will be invalid as soon as function exits,
2323 		 * but let's be conservative
2324 		 */
2325 		verbose(env, "cannot return stack pointer to the caller\n");
2326 		return -EINVAL;
2327 	}
2328 
2329 	state->curframe--;
2330 	caller = state->frame[state->curframe];
2331 	/* return to the caller whatever r0 had in the callee */
2332 	caller->regs[BPF_REG_0] = *r0;
2333 
2334 	*insn_idx = callee->callsite + 1;
2335 	if (env->log.level) {
2336 		verbose(env, "returning from callee:\n");
2337 		print_verifier_state(env, callee);
2338 		verbose(env, "to caller at %d:\n", *insn_idx);
2339 		print_verifier_state(env, caller);
2340 	}
2341 	/* clear everything in the callee */
2342 	free_func_state(callee);
2343 	state->frame[state->curframe + 1] = NULL;
2344 	return 0;
2345 }
2346 
2347 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
2348 				   int func_id,
2349 				   struct bpf_call_arg_meta *meta)
2350 {
2351 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
2352 
2353 	if (ret_type != RET_INTEGER ||
2354 	    (func_id != BPF_FUNC_get_stack &&
2355 	     func_id != BPF_FUNC_probe_read_str))
2356 		return;
2357 
2358 	ret_reg->smax_value = meta->msize_smax_value;
2359 	ret_reg->umax_value = meta->msize_umax_value;
2360 	__reg_deduce_bounds(ret_reg);
2361 	__reg_bound_offset(ret_reg);
2362 }
2363 
2364 static int
2365 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2366 		int func_id, int insn_idx)
2367 {
2368 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2369 
2370 	if (func_id != BPF_FUNC_tail_call &&
2371 	    func_id != BPF_FUNC_map_lookup_elem &&
2372 	    func_id != BPF_FUNC_map_update_elem &&
2373 	    func_id != BPF_FUNC_map_delete_elem)
2374 		return 0;
2375 
2376 	if (meta->map_ptr == NULL) {
2377 		verbose(env, "kernel subsystem misconfigured verifier\n");
2378 		return -EINVAL;
2379 	}
2380 
2381 	if (!BPF_MAP_PTR(aux->map_state))
2382 		bpf_map_ptr_store(aux, meta->map_ptr,
2383 				  meta->map_ptr->unpriv_array);
2384 	else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2385 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2386 				  meta->map_ptr->unpriv_array);
2387 	return 0;
2388 }
2389 
2390 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2391 {
2392 	const struct bpf_func_proto *fn = NULL;
2393 	struct bpf_reg_state *regs;
2394 	struct bpf_call_arg_meta meta;
2395 	bool changes_data;
2396 	int i, err;
2397 
2398 	/* find function prototype */
2399 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2400 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2401 			func_id);
2402 		return -EINVAL;
2403 	}
2404 
2405 	if (env->ops->get_func_proto)
2406 		fn = env->ops->get_func_proto(func_id, env->prog);
2407 	if (!fn) {
2408 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2409 			func_id);
2410 		return -EINVAL;
2411 	}
2412 
2413 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
2414 	if (!env->prog->gpl_compatible && fn->gpl_only) {
2415 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2416 		return -EINVAL;
2417 	}
2418 
2419 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
2420 	changes_data = bpf_helper_changes_pkt_data(fn->func);
2421 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2422 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2423 			func_id_name(func_id), func_id);
2424 		return -EINVAL;
2425 	}
2426 
2427 	memset(&meta, 0, sizeof(meta));
2428 	meta.pkt_access = fn->pkt_access;
2429 
2430 	err = check_func_proto(fn);
2431 	if (err) {
2432 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2433 			func_id_name(func_id), func_id);
2434 		return err;
2435 	}
2436 
2437 	/* check args */
2438 	err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2439 	if (err)
2440 		return err;
2441 	err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2442 	if (err)
2443 		return err;
2444 	err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2445 	if (err)
2446 		return err;
2447 	err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2448 	if (err)
2449 		return err;
2450 	err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2451 	if (err)
2452 		return err;
2453 
2454 	err = record_func_map(env, &meta, func_id, insn_idx);
2455 	if (err)
2456 		return err;
2457 
2458 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
2459 	 * is inferred from register state.
2460 	 */
2461 	for (i = 0; i < meta.access_size; i++) {
2462 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2463 				       BPF_WRITE, -1, false);
2464 		if (err)
2465 			return err;
2466 	}
2467 
2468 	regs = cur_regs(env);
2469 
2470 	/* check that flags argument in get_local_storage(map, flags) is 0,
2471 	 * this is required because get_local_storage() can't return an error.
2472 	 */
2473 	if (func_id == BPF_FUNC_get_local_storage &&
2474 	    !register_is_null(&regs[BPF_REG_2])) {
2475 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
2476 		return -EINVAL;
2477 	}
2478 
2479 	/* reset caller saved regs */
2480 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
2481 		mark_reg_not_init(env, regs, caller_saved[i]);
2482 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2483 	}
2484 
2485 	/* update return register (already marked as written above) */
2486 	if (fn->ret_type == RET_INTEGER) {
2487 		/* sets type to SCALAR_VALUE */
2488 		mark_reg_unknown(env, regs, BPF_REG_0);
2489 	} else if (fn->ret_type == RET_VOID) {
2490 		regs[BPF_REG_0].type = NOT_INIT;
2491 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
2492 		   fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2493 		if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
2494 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
2495 		else
2496 			regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2497 		/* There is no offset yet applied, variable or fixed */
2498 		mark_reg_known_zero(env, regs, BPF_REG_0);
2499 		/* remember map_ptr, so that check_map_access()
2500 		 * can check 'value_size' boundary of memory access
2501 		 * to map element returned from bpf_map_lookup_elem()
2502 		 */
2503 		if (meta.map_ptr == NULL) {
2504 			verbose(env,
2505 				"kernel subsystem misconfigured verifier\n");
2506 			return -EINVAL;
2507 		}
2508 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
2509 		regs[BPF_REG_0].id = ++env->id_gen;
2510 	} else {
2511 		verbose(env, "unknown return type %d of func %s#%d\n",
2512 			fn->ret_type, func_id_name(func_id), func_id);
2513 		return -EINVAL;
2514 	}
2515 
2516 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
2517 
2518 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2519 	if (err)
2520 		return err;
2521 
2522 	if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
2523 		const char *err_str;
2524 
2525 #ifdef CONFIG_PERF_EVENTS
2526 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
2527 		err_str = "cannot get callchain buffer for func %s#%d\n";
2528 #else
2529 		err = -ENOTSUPP;
2530 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
2531 #endif
2532 		if (err) {
2533 			verbose(env, err_str, func_id_name(func_id), func_id);
2534 			return err;
2535 		}
2536 
2537 		env->prog->has_callchain_buf = true;
2538 	}
2539 
2540 	if (changes_data)
2541 		clear_all_pkt_pointers(env);
2542 	return 0;
2543 }
2544 
2545 static bool signed_add_overflows(s64 a, s64 b)
2546 {
2547 	/* Do the add in u64, where overflow is well-defined */
2548 	s64 res = (s64)((u64)a + (u64)b);
2549 
2550 	if (b < 0)
2551 		return res > a;
2552 	return res < a;
2553 }
2554 
2555 static bool signed_sub_overflows(s64 a, s64 b)
2556 {
2557 	/* Do the sub in u64, where overflow is well-defined */
2558 	s64 res = (s64)((u64)a - (u64)b);
2559 
2560 	if (b < 0)
2561 		return res < a;
2562 	return res > a;
2563 }
2564 
2565 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2566 				  const struct bpf_reg_state *reg,
2567 				  enum bpf_reg_type type)
2568 {
2569 	bool known = tnum_is_const(reg->var_off);
2570 	s64 val = reg->var_off.value;
2571 	s64 smin = reg->smin_value;
2572 
2573 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2574 		verbose(env, "math between %s pointer and %lld is not allowed\n",
2575 			reg_type_str[type], val);
2576 		return false;
2577 	}
2578 
2579 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2580 		verbose(env, "%s pointer offset %d is not allowed\n",
2581 			reg_type_str[type], reg->off);
2582 		return false;
2583 	}
2584 
2585 	if (smin == S64_MIN) {
2586 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2587 			reg_type_str[type]);
2588 		return false;
2589 	}
2590 
2591 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2592 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
2593 			smin, reg_type_str[type]);
2594 		return false;
2595 	}
2596 
2597 	return true;
2598 }
2599 
2600 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2601  * Caller should also handle BPF_MOV case separately.
2602  * If we return -EACCES, caller may want to try again treating pointer as a
2603  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
2604  */
2605 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2606 				   struct bpf_insn *insn,
2607 				   const struct bpf_reg_state *ptr_reg,
2608 				   const struct bpf_reg_state *off_reg)
2609 {
2610 	struct bpf_verifier_state *vstate = env->cur_state;
2611 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2612 	struct bpf_reg_state *regs = state->regs, *dst_reg;
2613 	bool known = tnum_is_const(off_reg->var_off);
2614 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2615 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2616 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2617 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2618 	u8 opcode = BPF_OP(insn->code);
2619 	u32 dst = insn->dst_reg;
2620 
2621 	dst_reg = &regs[dst];
2622 
2623 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2624 	    smin_val > smax_val || umin_val > umax_val) {
2625 		/* Taint dst register if offset had invalid bounds derived from
2626 		 * e.g. dead branches.
2627 		 */
2628 		__mark_reg_unknown(dst_reg);
2629 		return 0;
2630 	}
2631 
2632 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
2633 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
2634 		verbose(env,
2635 			"R%d 32-bit pointer arithmetic prohibited\n",
2636 			dst);
2637 		return -EACCES;
2638 	}
2639 
2640 	if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2641 		verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2642 			dst);
2643 		return -EACCES;
2644 	}
2645 	if (ptr_reg->type == CONST_PTR_TO_MAP) {
2646 		verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2647 			dst);
2648 		return -EACCES;
2649 	}
2650 	if (ptr_reg->type == PTR_TO_PACKET_END) {
2651 		verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2652 			dst);
2653 		return -EACCES;
2654 	}
2655 
2656 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2657 	 * The id may be overwritten later if we create a new variable offset.
2658 	 */
2659 	dst_reg->type = ptr_reg->type;
2660 	dst_reg->id = ptr_reg->id;
2661 
2662 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2663 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2664 		return -EINVAL;
2665 
2666 	switch (opcode) {
2667 	case BPF_ADD:
2668 		/* We can take a fixed offset as long as it doesn't overflow
2669 		 * the s32 'off' field
2670 		 */
2671 		if (known && (ptr_reg->off + smin_val ==
2672 			      (s64)(s32)(ptr_reg->off + smin_val))) {
2673 			/* pointer += K.  Accumulate it into fixed offset */
2674 			dst_reg->smin_value = smin_ptr;
2675 			dst_reg->smax_value = smax_ptr;
2676 			dst_reg->umin_value = umin_ptr;
2677 			dst_reg->umax_value = umax_ptr;
2678 			dst_reg->var_off = ptr_reg->var_off;
2679 			dst_reg->off = ptr_reg->off + smin_val;
2680 			dst_reg->range = ptr_reg->range;
2681 			break;
2682 		}
2683 		/* A new variable offset is created.  Note that off_reg->off
2684 		 * == 0, since it's a scalar.
2685 		 * dst_reg gets the pointer type and since some positive
2686 		 * integer value was added to the pointer, give it a new 'id'
2687 		 * if it's a PTR_TO_PACKET.
2688 		 * this creates a new 'base' pointer, off_reg (variable) gets
2689 		 * added into the variable offset, and we copy the fixed offset
2690 		 * from ptr_reg.
2691 		 */
2692 		if (signed_add_overflows(smin_ptr, smin_val) ||
2693 		    signed_add_overflows(smax_ptr, smax_val)) {
2694 			dst_reg->smin_value = S64_MIN;
2695 			dst_reg->smax_value = S64_MAX;
2696 		} else {
2697 			dst_reg->smin_value = smin_ptr + smin_val;
2698 			dst_reg->smax_value = smax_ptr + smax_val;
2699 		}
2700 		if (umin_ptr + umin_val < umin_ptr ||
2701 		    umax_ptr + umax_val < umax_ptr) {
2702 			dst_reg->umin_value = 0;
2703 			dst_reg->umax_value = U64_MAX;
2704 		} else {
2705 			dst_reg->umin_value = umin_ptr + umin_val;
2706 			dst_reg->umax_value = umax_ptr + umax_val;
2707 		}
2708 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2709 		dst_reg->off = ptr_reg->off;
2710 		if (reg_is_pkt_pointer(ptr_reg)) {
2711 			dst_reg->id = ++env->id_gen;
2712 			/* something was added to pkt_ptr, set range to zero */
2713 			dst_reg->range = 0;
2714 		}
2715 		break;
2716 	case BPF_SUB:
2717 		if (dst_reg == off_reg) {
2718 			/* scalar -= pointer.  Creates an unknown scalar */
2719 			verbose(env, "R%d tried to subtract pointer from scalar\n",
2720 				dst);
2721 			return -EACCES;
2722 		}
2723 		/* We don't allow subtraction from FP, because (according to
2724 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
2725 		 * be able to deal with it.
2726 		 */
2727 		if (ptr_reg->type == PTR_TO_STACK) {
2728 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
2729 				dst);
2730 			return -EACCES;
2731 		}
2732 		if (known && (ptr_reg->off - smin_val ==
2733 			      (s64)(s32)(ptr_reg->off - smin_val))) {
2734 			/* pointer -= K.  Subtract it from fixed offset */
2735 			dst_reg->smin_value = smin_ptr;
2736 			dst_reg->smax_value = smax_ptr;
2737 			dst_reg->umin_value = umin_ptr;
2738 			dst_reg->umax_value = umax_ptr;
2739 			dst_reg->var_off = ptr_reg->var_off;
2740 			dst_reg->id = ptr_reg->id;
2741 			dst_reg->off = ptr_reg->off - smin_val;
2742 			dst_reg->range = ptr_reg->range;
2743 			break;
2744 		}
2745 		/* A new variable offset is created.  If the subtrahend is known
2746 		 * nonnegative, then any reg->range we had before is still good.
2747 		 */
2748 		if (signed_sub_overflows(smin_ptr, smax_val) ||
2749 		    signed_sub_overflows(smax_ptr, smin_val)) {
2750 			/* Overflow possible, we know nothing */
2751 			dst_reg->smin_value = S64_MIN;
2752 			dst_reg->smax_value = S64_MAX;
2753 		} else {
2754 			dst_reg->smin_value = smin_ptr - smax_val;
2755 			dst_reg->smax_value = smax_ptr - smin_val;
2756 		}
2757 		if (umin_ptr < umax_val) {
2758 			/* Overflow possible, we know nothing */
2759 			dst_reg->umin_value = 0;
2760 			dst_reg->umax_value = U64_MAX;
2761 		} else {
2762 			/* Cannot overflow (as long as bounds are consistent) */
2763 			dst_reg->umin_value = umin_ptr - umax_val;
2764 			dst_reg->umax_value = umax_ptr - umin_val;
2765 		}
2766 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2767 		dst_reg->off = ptr_reg->off;
2768 		if (reg_is_pkt_pointer(ptr_reg)) {
2769 			dst_reg->id = ++env->id_gen;
2770 			/* something was added to pkt_ptr, set range to zero */
2771 			if (smin_val < 0)
2772 				dst_reg->range = 0;
2773 		}
2774 		break;
2775 	case BPF_AND:
2776 	case BPF_OR:
2777 	case BPF_XOR:
2778 		/* bitwise ops on pointers are troublesome, prohibit. */
2779 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
2780 			dst, bpf_alu_string[opcode >> 4]);
2781 		return -EACCES;
2782 	default:
2783 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
2784 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
2785 			dst, bpf_alu_string[opcode >> 4]);
2786 		return -EACCES;
2787 	}
2788 
2789 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2790 		return -EINVAL;
2791 
2792 	__update_reg_bounds(dst_reg);
2793 	__reg_deduce_bounds(dst_reg);
2794 	__reg_bound_offset(dst_reg);
2795 	return 0;
2796 }
2797 
2798 /* WARNING: This function does calculations on 64-bit values, but the actual
2799  * execution may occur on 32-bit values. Therefore, things like bitshifts
2800  * need extra checks in the 32-bit case.
2801  */
2802 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2803 				      struct bpf_insn *insn,
2804 				      struct bpf_reg_state *dst_reg,
2805 				      struct bpf_reg_state src_reg)
2806 {
2807 	struct bpf_reg_state *regs = cur_regs(env);
2808 	u8 opcode = BPF_OP(insn->code);
2809 	bool src_known, dst_known;
2810 	s64 smin_val, smax_val;
2811 	u64 umin_val, umax_val;
2812 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2813 
2814 	smin_val = src_reg.smin_value;
2815 	smax_val = src_reg.smax_value;
2816 	umin_val = src_reg.umin_value;
2817 	umax_val = src_reg.umax_value;
2818 	src_known = tnum_is_const(src_reg.var_off);
2819 	dst_known = tnum_is_const(dst_reg->var_off);
2820 
2821 	if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2822 	    smin_val > smax_val || umin_val > umax_val) {
2823 		/* Taint dst register if offset had invalid bounds derived from
2824 		 * e.g. dead branches.
2825 		 */
2826 		__mark_reg_unknown(dst_reg);
2827 		return 0;
2828 	}
2829 
2830 	if (!src_known &&
2831 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2832 		__mark_reg_unknown(dst_reg);
2833 		return 0;
2834 	}
2835 
2836 	switch (opcode) {
2837 	case BPF_ADD:
2838 		if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2839 		    signed_add_overflows(dst_reg->smax_value, smax_val)) {
2840 			dst_reg->smin_value = S64_MIN;
2841 			dst_reg->smax_value = S64_MAX;
2842 		} else {
2843 			dst_reg->smin_value += smin_val;
2844 			dst_reg->smax_value += smax_val;
2845 		}
2846 		if (dst_reg->umin_value + umin_val < umin_val ||
2847 		    dst_reg->umax_value + umax_val < umax_val) {
2848 			dst_reg->umin_value = 0;
2849 			dst_reg->umax_value = U64_MAX;
2850 		} else {
2851 			dst_reg->umin_value += umin_val;
2852 			dst_reg->umax_value += umax_val;
2853 		}
2854 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2855 		break;
2856 	case BPF_SUB:
2857 		if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2858 		    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2859 			/* Overflow possible, we know nothing */
2860 			dst_reg->smin_value = S64_MIN;
2861 			dst_reg->smax_value = S64_MAX;
2862 		} else {
2863 			dst_reg->smin_value -= smax_val;
2864 			dst_reg->smax_value -= smin_val;
2865 		}
2866 		if (dst_reg->umin_value < umax_val) {
2867 			/* Overflow possible, we know nothing */
2868 			dst_reg->umin_value = 0;
2869 			dst_reg->umax_value = U64_MAX;
2870 		} else {
2871 			/* Cannot overflow (as long as bounds are consistent) */
2872 			dst_reg->umin_value -= umax_val;
2873 			dst_reg->umax_value -= umin_val;
2874 		}
2875 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2876 		break;
2877 	case BPF_MUL:
2878 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2879 		if (smin_val < 0 || dst_reg->smin_value < 0) {
2880 			/* Ain't nobody got time to multiply that sign */
2881 			__mark_reg_unbounded(dst_reg);
2882 			__update_reg_bounds(dst_reg);
2883 			break;
2884 		}
2885 		/* Both values are positive, so we can work with unsigned and
2886 		 * copy the result to signed (unless it exceeds S64_MAX).
2887 		 */
2888 		if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2889 			/* Potential overflow, we know nothing */
2890 			__mark_reg_unbounded(dst_reg);
2891 			/* (except what we can learn from the var_off) */
2892 			__update_reg_bounds(dst_reg);
2893 			break;
2894 		}
2895 		dst_reg->umin_value *= umin_val;
2896 		dst_reg->umax_value *= umax_val;
2897 		if (dst_reg->umax_value > S64_MAX) {
2898 			/* Overflow possible, we know nothing */
2899 			dst_reg->smin_value = S64_MIN;
2900 			dst_reg->smax_value = S64_MAX;
2901 		} else {
2902 			dst_reg->smin_value = dst_reg->umin_value;
2903 			dst_reg->smax_value = dst_reg->umax_value;
2904 		}
2905 		break;
2906 	case BPF_AND:
2907 		if (src_known && dst_known) {
2908 			__mark_reg_known(dst_reg, dst_reg->var_off.value &
2909 						  src_reg.var_off.value);
2910 			break;
2911 		}
2912 		/* We get our minimum from the var_off, since that's inherently
2913 		 * bitwise.  Our maximum is the minimum of the operands' maxima.
2914 		 */
2915 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2916 		dst_reg->umin_value = dst_reg->var_off.value;
2917 		dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2918 		if (dst_reg->smin_value < 0 || smin_val < 0) {
2919 			/* Lose signed bounds when ANDing negative numbers,
2920 			 * ain't nobody got time for that.
2921 			 */
2922 			dst_reg->smin_value = S64_MIN;
2923 			dst_reg->smax_value = S64_MAX;
2924 		} else {
2925 			/* ANDing two positives gives a positive, so safe to
2926 			 * cast result into s64.
2927 			 */
2928 			dst_reg->smin_value = dst_reg->umin_value;
2929 			dst_reg->smax_value = dst_reg->umax_value;
2930 		}
2931 		/* We may learn something more from the var_off */
2932 		__update_reg_bounds(dst_reg);
2933 		break;
2934 	case BPF_OR:
2935 		if (src_known && dst_known) {
2936 			__mark_reg_known(dst_reg, dst_reg->var_off.value |
2937 						  src_reg.var_off.value);
2938 			break;
2939 		}
2940 		/* We get our maximum from the var_off, and our minimum is the
2941 		 * maximum of the operands' minima
2942 		 */
2943 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2944 		dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2945 		dst_reg->umax_value = dst_reg->var_off.value |
2946 				      dst_reg->var_off.mask;
2947 		if (dst_reg->smin_value < 0 || smin_val < 0) {
2948 			/* Lose signed bounds when ORing negative numbers,
2949 			 * ain't nobody got time for that.
2950 			 */
2951 			dst_reg->smin_value = S64_MIN;
2952 			dst_reg->smax_value = S64_MAX;
2953 		} else {
2954 			/* ORing two positives gives a positive, so safe to
2955 			 * cast result into s64.
2956 			 */
2957 			dst_reg->smin_value = dst_reg->umin_value;
2958 			dst_reg->smax_value = dst_reg->umax_value;
2959 		}
2960 		/* We may learn something more from the var_off */
2961 		__update_reg_bounds(dst_reg);
2962 		break;
2963 	case BPF_LSH:
2964 		if (umax_val >= insn_bitness) {
2965 			/* Shifts greater than 31 or 63 are undefined.
2966 			 * This includes shifts by a negative number.
2967 			 */
2968 			mark_reg_unknown(env, regs, insn->dst_reg);
2969 			break;
2970 		}
2971 		/* We lose all sign bit information (except what we can pick
2972 		 * up from var_off)
2973 		 */
2974 		dst_reg->smin_value = S64_MIN;
2975 		dst_reg->smax_value = S64_MAX;
2976 		/* If we might shift our top bit out, then we know nothing */
2977 		if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2978 			dst_reg->umin_value = 0;
2979 			dst_reg->umax_value = U64_MAX;
2980 		} else {
2981 			dst_reg->umin_value <<= umin_val;
2982 			dst_reg->umax_value <<= umax_val;
2983 		}
2984 		dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2985 		/* We may learn something more from the var_off */
2986 		__update_reg_bounds(dst_reg);
2987 		break;
2988 	case BPF_RSH:
2989 		if (umax_val >= insn_bitness) {
2990 			/* Shifts greater than 31 or 63 are undefined.
2991 			 * This includes shifts by a negative number.
2992 			 */
2993 			mark_reg_unknown(env, regs, insn->dst_reg);
2994 			break;
2995 		}
2996 		/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
2997 		 * be negative, then either:
2998 		 * 1) src_reg might be zero, so the sign bit of the result is
2999 		 *    unknown, so we lose our signed bounds
3000 		 * 2) it's known negative, thus the unsigned bounds capture the
3001 		 *    signed bounds
3002 		 * 3) the signed bounds cross zero, so they tell us nothing
3003 		 *    about the result
3004 		 * If the value in dst_reg is known nonnegative, then again the
3005 		 * unsigned bounts capture the signed bounds.
3006 		 * Thus, in all cases it suffices to blow away our signed bounds
3007 		 * and rely on inferring new ones from the unsigned bounds and
3008 		 * var_off of the result.
3009 		 */
3010 		dst_reg->smin_value = S64_MIN;
3011 		dst_reg->smax_value = S64_MAX;
3012 		dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3013 		dst_reg->umin_value >>= umax_val;
3014 		dst_reg->umax_value >>= umin_val;
3015 		/* We may learn something more from the var_off */
3016 		__update_reg_bounds(dst_reg);
3017 		break;
3018 	case BPF_ARSH:
3019 		if (umax_val >= insn_bitness) {
3020 			/* Shifts greater than 31 or 63 are undefined.
3021 			 * This includes shifts by a negative number.
3022 			 */
3023 			mark_reg_unknown(env, regs, insn->dst_reg);
3024 			break;
3025 		}
3026 
3027 		/* Upon reaching here, src_known is true and
3028 		 * umax_val is equal to umin_val.
3029 		 */
3030 		dst_reg->smin_value >>= umin_val;
3031 		dst_reg->smax_value >>= umin_val;
3032 		dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
3033 
3034 		/* blow away the dst_reg umin_value/umax_value and rely on
3035 		 * dst_reg var_off to refine the result.
3036 		 */
3037 		dst_reg->umin_value = 0;
3038 		dst_reg->umax_value = U64_MAX;
3039 		__update_reg_bounds(dst_reg);
3040 		break;
3041 	default:
3042 		mark_reg_unknown(env, regs, insn->dst_reg);
3043 		break;
3044 	}
3045 
3046 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
3047 		/* 32-bit ALU ops are (32,32)->32 */
3048 		coerce_reg_to_size(dst_reg, 4);
3049 		coerce_reg_to_size(&src_reg, 4);
3050 	}
3051 
3052 	__reg_deduce_bounds(dst_reg);
3053 	__reg_bound_offset(dst_reg);
3054 	return 0;
3055 }
3056 
3057 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3058  * and var_off.
3059  */
3060 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3061 				   struct bpf_insn *insn)
3062 {
3063 	struct bpf_verifier_state *vstate = env->cur_state;
3064 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3065 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3066 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3067 	u8 opcode = BPF_OP(insn->code);
3068 
3069 	dst_reg = &regs[insn->dst_reg];
3070 	src_reg = NULL;
3071 	if (dst_reg->type != SCALAR_VALUE)
3072 		ptr_reg = dst_reg;
3073 	if (BPF_SRC(insn->code) == BPF_X) {
3074 		src_reg = &regs[insn->src_reg];
3075 		if (src_reg->type != SCALAR_VALUE) {
3076 			if (dst_reg->type != SCALAR_VALUE) {
3077 				/* Combining two pointers by any ALU op yields
3078 				 * an arbitrary scalar. Disallow all math except
3079 				 * pointer subtraction
3080 				 */
3081 				if (opcode == BPF_SUB){
3082 					mark_reg_unknown(env, regs, insn->dst_reg);
3083 					return 0;
3084 				}
3085 				verbose(env, "R%d pointer %s pointer prohibited\n",
3086 					insn->dst_reg,
3087 					bpf_alu_string[opcode >> 4]);
3088 				return -EACCES;
3089 			} else {
3090 				/* scalar += pointer
3091 				 * This is legal, but we have to reverse our
3092 				 * src/dest handling in computing the range
3093 				 */
3094 				return adjust_ptr_min_max_vals(env, insn,
3095 							       src_reg, dst_reg);
3096 			}
3097 		} else if (ptr_reg) {
3098 			/* pointer += scalar */
3099 			return adjust_ptr_min_max_vals(env, insn,
3100 						       dst_reg, src_reg);
3101 		}
3102 	} else {
3103 		/* Pretend the src is a reg with a known value, since we only
3104 		 * need to be able to read from this state.
3105 		 */
3106 		off_reg.type = SCALAR_VALUE;
3107 		__mark_reg_known(&off_reg, insn->imm);
3108 		src_reg = &off_reg;
3109 		if (ptr_reg) /* pointer += K */
3110 			return adjust_ptr_min_max_vals(env, insn,
3111 						       ptr_reg, src_reg);
3112 	}
3113 
3114 	/* Got here implies adding two SCALAR_VALUEs */
3115 	if (WARN_ON_ONCE(ptr_reg)) {
3116 		print_verifier_state(env, state);
3117 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
3118 		return -EINVAL;
3119 	}
3120 	if (WARN_ON(!src_reg)) {
3121 		print_verifier_state(env, state);
3122 		verbose(env, "verifier internal error: no src_reg\n");
3123 		return -EINVAL;
3124 	}
3125 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3126 }
3127 
3128 /* check validity of 32-bit and 64-bit arithmetic operations */
3129 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3130 {
3131 	struct bpf_reg_state *regs = cur_regs(env);
3132 	u8 opcode = BPF_OP(insn->code);
3133 	int err;
3134 
3135 	if (opcode == BPF_END || opcode == BPF_NEG) {
3136 		if (opcode == BPF_NEG) {
3137 			if (BPF_SRC(insn->code) != 0 ||
3138 			    insn->src_reg != BPF_REG_0 ||
3139 			    insn->off != 0 || insn->imm != 0) {
3140 				verbose(env, "BPF_NEG uses reserved fields\n");
3141 				return -EINVAL;
3142 			}
3143 		} else {
3144 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3145 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3146 			    BPF_CLASS(insn->code) == BPF_ALU64) {
3147 				verbose(env, "BPF_END uses reserved fields\n");
3148 				return -EINVAL;
3149 			}
3150 		}
3151 
3152 		/* check src operand */
3153 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3154 		if (err)
3155 			return err;
3156 
3157 		if (is_pointer_value(env, insn->dst_reg)) {
3158 			verbose(env, "R%d pointer arithmetic prohibited\n",
3159 				insn->dst_reg);
3160 			return -EACCES;
3161 		}
3162 
3163 		/* check dest operand */
3164 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
3165 		if (err)
3166 			return err;
3167 
3168 	} else if (opcode == BPF_MOV) {
3169 
3170 		if (BPF_SRC(insn->code) == BPF_X) {
3171 			if (insn->imm != 0 || insn->off != 0) {
3172 				verbose(env, "BPF_MOV uses reserved fields\n");
3173 				return -EINVAL;
3174 			}
3175 
3176 			/* check src operand */
3177 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
3178 			if (err)
3179 				return err;
3180 		} else {
3181 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3182 				verbose(env, "BPF_MOV uses reserved fields\n");
3183 				return -EINVAL;
3184 			}
3185 		}
3186 
3187 		/* check dest operand, mark as required later */
3188 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3189 		if (err)
3190 			return err;
3191 
3192 		if (BPF_SRC(insn->code) == BPF_X) {
3193 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
3194 				/* case: R1 = R2
3195 				 * copy register state to dest reg
3196 				 */
3197 				regs[insn->dst_reg] = regs[insn->src_reg];
3198 				regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
3199 			} else {
3200 				/* R1 = (u32) R2 */
3201 				if (is_pointer_value(env, insn->src_reg)) {
3202 					verbose(env,
3203 						"R%d partial copy of pointer\n",
3204 						insn->src_reg);
3205 					return -EACCES;
3206 				}
3207 				mark_reg_unknown(env, regs, insn->dst_reg);
3208 				coerce_reg_to_size(&regs[insn->dst_reg], 4);
3209 			}
3210 		} else {
3211 			/* case: R = imm
3212 			 * remember the value we stored into this reg
3213 			 */
3214 			/* clear any state __mark_reg_known doesn't set */
3215 			mark_reg_unknown(env, regs, insn->dst_reg);
3216 			regs[insn->dst_reg].type = SCALAR_VALUE;
3217 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
3218 				__mark_reg_known(regs + insn->dst_reg,
3219 						 insn->imm);
3220 			} else {
3221 				__mark_reg_known(regs + insn->dst_reg,
3222 						 (u32)insn->imm);
3223 			}
3224 		}
3225 
3226 	} else if (opcode > BPF_END) {
3227 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3228 		return -EINVAL;
3229 
3230 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
3231 
3232 		if (BPF_SRC(insn->code) == BPF_X) {
3233 			if (insn->imm != 0 || insn->off != 0) {
3234 				verbose(env, "BPF_ALU uses reserved fields\n");
3235 				return -EINVAL;
3236 			}
3237 			/* check src1 operand */
3238 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
3239 			if (err)
3240 				return err;
3241 		} else {
3242 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3243 				verbose(env, "BPF_ALU uses reserved fields\n");
3244 				return -EINVAL;
3245 			}
3246 		}
3247 
3248 		/* check src2 operand */
3249 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3250 		if (err)
3251 			return err;
3252 
3253 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3254 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3255 			verbose(env, "div by zero\n");
3256 			return -EINVAL;
3257 		}
3258 
3259 		if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3260 			verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3261 			return -EINVAL;
3262 		}
3263 
3264 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3265 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3266 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3267 
3268 			if (insn->imm < 0 || insn->imm >= size) {
3269 				verbose(env, "invalid shift %d\n", insn->imm);
3270 				return -EINVAL;
3271 			}
3272 		}
3273 
3274 		/* check dest operand */
3275 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3276 		if (err)
3277 			return err;
3278 
3279 		return adjust_reg_min_max_vals(env, insn);
3280 	}
3281 
3282 	return 0;
3283 }
3284 
3285 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3286 				   struct bpf_reg_state *dst_reg,
3287 				   enum bpf_reg_type type,
3288 				   bool range_right_open)
3289 {
3290 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3291 	struct bpf_reg_state *regs = state->regs, *reg;
3292 	u16 new_range;
3293 	int i, j;
3294 
3295 	if (dst_reg->off < 0 ||
3296 	    (dst_reg->off == 0 && range_right_open))
3297 		/* This doesn't give us any range */
3298 		return;
3299 
3300 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
3301 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3302 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
3303 		 * than pkt_end, but that's because it's also less than pkt.
3304 		 */
3305 		return;
3306 
3307 	new_range = dst_reg->off;
3308 	if (range_right_open)
3309 		new_range--;
3310 
3311 	/* Examples for register markings:
3312 	 *
3313 	 * pkt_data in dst register:
3314 	 *
3315 	 *   r2 = r3;
3316 	 *   r2 += 8;
3317 	 *   if (r2 > pkt_end) goto <handle exception>
3318 	 *   <access okay>
3319 	 *
3320 	 *   r2 = r3;
3321 	 *   r2 += 8;
3322 	 *   if (r2 < pkt_end) goto <access okay>
3323 	 *   <handle exception>
3324 	 *
3325 	 *   Where:
3326 	 *     r2 == dst_reg, pkt_end == src_reg
3327 	 *     r2=pkt(id=n,off=8,r=0)
3328 	 *     r3=pkt(id=n,off=0,r=0)
3329 	 *
3330 	 * pkt_data in src register:
3331 	 *
3332 	 *   r2 = r3;
3333 	 *   r2 += 8;
3334 	 *   if (pkt_end >= r2) goto <access okay>
3335 	 *   <handle exception>
3336 	 *
3337 	 *   r2 = r3;
3338 	 *   r2 += 8;
3339 	 *   if (pkt_end <= r2) goto <handle exception>
3340 	 *   <access okay>
3341 	 *
3342 	 *   Where:
3343 	 *     pkt_end == dst_reg, r2 == src_reg
3344 	 *     r2=pkt(id=n,off=8,r=0)
3345 	 *     r3=pkt(id=n,off=0,r=0)
3346 	 *
3347 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3348 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3349 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
3350 	 * the check.
3351 	 */
3352 
3353 	/* If our ids match, then we must have the same max_value.  And we
3354 	 * don't care about the other reg's fixed offset, since if it's too big
3355 	 * the range won't allow anything.
3356 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3357 	 */
3358 	for (i = 0; i < MAX_BPF_REG; i++)
3359 		if (regs[i].type == type && regs[i].id == dst_reg->id)
3360 			/* keep the maximum range already checked */
3361 			regs[i].range = max(regs[i].range, new_range);
3362 
3363 	for (j = 0; j <= vstate->curframe; j++) {
3364 		state = vstate->frame[j];
3365 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3366 			if (state->stack[i].slot_type[0] != STACK_SPILL)
3367 				continue;
3368 			reg = &state->stack[i].spilled_ptr;
3369 			if (reg->type == type && reg->id == dst_reg->id)
3370 				reg->range = max(reg->range, new_range);
3371 		}
3372 	}
3373 }
3374 
3375 /* Adjusts the register min/max values in the case that the dst_reg is the
3376  * variable register that we are working on, and src_reg is a constant or we're
3377  * simply doing a BPF_K check.
3378  * In JEQ/JNE cases we also adjust the var_off values.
3379  */
3380 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3381 			    struct bpf_reg_state *false_reg, u64 val,
3382 			    u8 opcode)
3383 {
3384 	/* If the dst_reg is a pointer, we can't learn anything about its
3385 	 * variable offset from the compare (unless src_reg were a pointer into
3386 	 * the same object, but we don't bother with that.
3387 	 * Since false_reg and true_reg have the same type by construction, we
3388 	 * only need to check one of them for pointerness.
3389 	 */
3390 	if (__is_pointer_value(false, false_reg))
3391 		return;
3392 
3393 	switch (opcode) {
3394 	case BPF_JEQ:
3395 		/* If this is false then we know nothing Jon Snow, but if it is
3396 		 * true then we know for sure.
3397 		 */
3398 		__mark_reg_known(true_reg, val);
3399 		break;
3400 	case BPF_JNE:
3401 		/* If this is true we know nothing Jon Snow, but if it is false
3402 		 * we know the value for sure;
3403 		 */
3404 		__mark_reg_known(false_reg, val);
3405 		break;
3406 	case BPF_JGT:
3407 		false_reg->umax_value = min(false_reg->umax_value, val);
3408 		true_reg->umin_value = max(true_reg->umin_value, val + 1);
3409 		break;
3410 	case BPF_JSGT:
3411 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3412 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3413 		break;
3414 	case BPF_JLT:
3415 		false_reg->umin_value = max(false_reg->umin_value, val);
3416 		true_reg->umax_value = min(true_reg->umax_value, val - 1);
3417 		break;
3418 	case BPF_JSLT:
3419 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3420 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3421 		break;
3422 	case BPF_JGE:
3423 		false_reg->umax_value = min(false_reg->umax_value, val - 1);
3424 		true_reg->umin_value = max(true_reg->umin_value, val);
3425 		break;
3426 	case BPF_JSGE:
3427 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3428 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3429 		break;
3430 	case BPF_JLE:
3431 		false_reg->umin_value = max(false_reg->umin_value, val + 1);
3432 		true_reg->umax_value = min(true_reg->umax_value, val);
3433 		break;
3434 	case BPF_JSLE:
3435 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3436 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3437 		break;
3438 	default:
3439 		break;
3440 	}
3441 
3442 	__reg_deduce_bounds(false_reg);
3443 	__reg_deduce_bounds(true_reg);
3444 	/* We might have learned some bits from the bounds. */
3445 	__reg_bound_offset(false_reg);
3446 	__reg_bound_offset(true_reg);
3447 	/* Intersecting with the old var_off might have improved our bounds
3448 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3449 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3450 	 */
3451 	__update_reg_bounds(false_reg);
3452 	__update_reg_bounds(true_reg);
3453 }
3454 
3455 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3456  * the variable reg.
3457  */
3458 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3459 				struct bpf_reg_state *false_reg, u64 val,
3460 				u8 opcode)
3461 {
3462 	if (__is_pointer_value(false, false_reg))
3463 		return;
3464 
3465 	switch (opcode) {
3466 	case BPF_JEQ:
3467 		/* If this is false then we know nothing Jon Snow, but if it is
3468 		 * true then we know for sure.
3469 		 */
3470 		__mark_reg_known(true_reg, val);
3471 		break;
3472 	case BPF_JNE:
3473 		/* If this is true we know nothing Jon Snow, but if it is false
3474 		 * we know the value for sure;
3475 		 */
3476 		__mark_reg_known(false_reg, val);
3477 		break;
3478 	case BPF_JGT:
3479 		true_reg->umax_value = min(true_reg->umax_value, val - 1);
3480 		false_reg->umin_value = max(false_reg->umin_value, val);
3481 		break;
3482 	case BPF_JSGT:
3483 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3484 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3485 		break;
3486 	case BPF_JLT:
3487 		true_reg->umin_value = max(true_reg->umin_value, val + 1);
3488 		false_reg->umax_value = min(false_reg->umax_value, val);
3489 		break;
3490 	case BPF_JSLT:
3491 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3492 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3493 		break;
3494 	case BPF_JGE:
3495 		true_reg->umax_value = min(true_reg->umax_value, val);
3496 		false_reg->umin_value = max(false_reg->umin_value, val + 1);
3497 		break;
3498 	case BPF_JSGE:
3499 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3500 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3501 		break;
3502 	case BPF_JLE:
3503 		true_reg->umin_value = max(true_reg->umin_value, val);
3504 		false_reg->umax_value = min(false_reg->umax_value, val - 1);
3505 		break;
3506 	case BPF_JSLE:
3507 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3508 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3509 		break;
3510 	default:
3511 		break;
3512 	}
3513 
3514 	__reg_deduce_bounds(false_reg);
3515 	__reg_deduce_bounds(true_reg);
3516 	/* We might have learned some bits from the bounds. */
3517 	__reg_bound_offset(false_reg);
3518 	__reg_bound_offset(true_reg);
3519 	/* Intersecting with the old var_off might have improved our bounds
3520 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3521 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3522 	 */
3523 	__update_reg_bounds(false_reg);
3524 	__update_reg_bounds(true_reg);
3525 }
3526 
3527 /* Regs are known to be equal, so intersect their min/max/var_off */
3528 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3529 				  struct bpf_reg_state *dst_reg)
3530 {
3531 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3532 							dst_reg->umin_value);
3533 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3534 							dst_reg->umax_value);
3535 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3536 							dst_reg->smin_value);
3537 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3538 							dst_reg->smax_value);
3539 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3540 							     dst_reg->var_off);
3541 	/* We might have learned new bounds from the var_off. */
3542 	__update_reg_bounds(src_reg);
3543 	__update_reg_bounds(dst_reg);
3544 	/* We might have learned something about the sign bit. */
3545 	__reg_deduce_bounds(src_reg);
3546 	__reg_deduce_bounds(dst_reg);
3547 	/* We might have learned some bits from the bounds. */
3548 	__reg_bound_offset(src_reg);
3549 	__reg_bound_offset(dst_reg);
3550 	/* Intersecting with the old var_off might have improved our bounds
3551 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3552 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3553 	 */
3554 	__update_reg_bounds(src_reg);
3555 	__update_reg_bounds(dst_reg);
3556 }
3557 
3558 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3559 				struct bpf_reg_state *true_dst,
3560 				struct bpf_reg_state *false_src,
3561 				struct bpf_reg_state *false_dst,
3562 				u8 opcode)
3563 {
3564 	switch (opcode) {
3565 	case BPF_JEQ:
3566 		__reg_combine_min_max(true_src, true_dst);
3567 		break;
3568 	case BPF_JNE:
3569 		__reg_combine_min_max(false_src, false_dst);
3570 		break;
3571 	}
3572 }
3573 
3574 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3575 			 bool is_null)
3576 {
3577 	struct bpf_reg_state *reg = &regs[regno];
3578 
3579 	if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3580 		/* Old offset (both fixed and variable parts) should
3581 		 * have been known-zero, because we don't allow pointer
3582 		 * arithmetic on pointers that might be NULL.
3583 		 */
3584 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3585 				 !tnum_equals_const(reg->var_off, 0) ||
3586 				 reg->off)) {
3587 			__mark_reg_known_zero(reg);
3588 			reg->off = 0;
3589 		}
3590 		if (is_null) {
3591 			reg->type = SCALAR_VALUE;
3592 		} else if (reg->map_ptr->inner_map_meta) {
3593 			reg->type = CONST_PTR_TO_MAP;
3594 			reg->map_ptr = reg->map_ptr->inner_map_meta;
3595 		} else {
3596 			reg->type = PTR_TO_MAP_VALUE;
3597 		}
3598 		/* We don't need id from this point onwards anymore, thus we
3599 		 * should better reset it, so that state pruning has chances
3600 		 * to take effect.
3601 		 */
3602 		reg->id = 0;
3603 	}
3604 }
3605 
3606 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3607  * be folded together at some point.
3608  */
3609 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
3610 			  bool is_null)
3611 {
3612 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3613 	struct bpf_reg_state *regs = state->regs;
3614 	u32 id = regs[regno].id;
3615 	int i, j;
3616 
3617 	for (i = 0; i < MAX_BPF_REG; i++)
3618 		mark_map_reg(regs, i, id, is_null);
3619 
3620 	for (j = 0; j <= vstate->curframe; j++) {
3621 		state = vstate->frame[j];
3622 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3623 			if (state->stack[i].slot_type[0] != STACK_SPILL)
3624 				continue;
3625 			mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3626 		}
3627 	}
3628 }
3629 
3630 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
3631 				   struct bpf_reg_state *dst_reg,
3632 				   struct bpf_reg_state *src_reg,
3633 				   struct bpf_verifier_state *this_branch,
3634 				   struct bpf_verifier_state *other_branch)
3635 {
3636 	if (BPF_SRC(insn->code) != BPF_X)
3637 		return false;
3638 
3639 	switch (BPF_OP(insn->code)) {
3640 	case BPF_JGT:
3641 		if ((dst_reg->type == PTR_TO_PACKET &&
3642 		     src_reg->type == PTR_TO_PACKET_END) ||
3643 		    (dst_reg->type == PTR_TO_PACKET_META &&
3644 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3645 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
3646 			find_good_pkt_pointers(this_branch, dst_reg,
3647 					       dst_reg->type, false);
3648 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
3649 			    src_reg->type == PTR_TO_PACKET) ||
3650 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3651 			    src_reg->type == PTR_TO_PACKET_META)) {
3652 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
3653 			find_good_pkt_pointers(other_branch, src_reg,
3654 					       src_reg->type, true);
3655 		} else {
3656 			return false;
3657 		}
3658 		break;
3659 	case BPF_JLT:
3660 		if ((dst_reg->type == PTR_TO_PACKET &&
3661 		     src_reg->type == PTR_TO_PACKET_END) ||
3662 		    (dst_reg->type == PTR_TO_PACKET_META &&
3663 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3664 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
3665 			find_good_pkt_pointers(other_branch, dst_reg,
3666 					       dst_reg->type, true);
3667 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
3668 			    src_reg->type == PTR_TO_PACKET) ||
3669 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3670 			    src_reg->type == PTR_TO_PACKET_META)) {
3671 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
3672 			find_good_pkt_pointers(this_branch, src_reg,
3673 					       src_reg->type, false);
3674 		} else {
3675 			return false;
3676 		}
3677 		break;
3678 	case BPF_JGE:
3679 		if ((dst_reg->type == PTR_TO_PACKET &&
3680 		     src_reg->type == PTR_TO_PACKET_END) ||
3681 		    (dst_reg->type == PTR_TO_PACKET_META &&
3682 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3683 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
3684 			find_good_pkt_pointers(this_branch, dst_reg,
3685 					       dst_reg->type, true);
3686 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
3687 			    src_reg->type == PTR_TO_PACKET) ||
3688 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3689 			    src_reg->type == PTR_TO_PACKET_META)) {
3690 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
3691 			find_good_pkt_pointers(other_branch, src_reg,
3692 					       src_reg->type, false);
3693 		} else {
3694 			return false;
3695 		}
3696 		break;
3697 	case BPF_JLE:
3698 		if ((dst_reg->type == PTR_TO_PACKET &&
3699 		     src_reg->type == PTR_TO_PACKET_END) ||
3700 		    (dst_reg->type == PTR_TO_PACKET_META &&
3701 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3702 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
3703 			find_good_pkt_pointers(other_branch, dst_reg,
3704 					       dst_reg->type, false);
3705 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
3706 			    src_reg->type == PTR_TO_PACKET) ||
3707 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3708 			    src_reg->type == PTR_TO_PACKET_META)) {
3709 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
3710 			find_good_pkt_pointers(this_branch, src_reg,
3711 					       src_reg->type, true);
3712 		} else {
3713 			return false;
3714 		}
3715 		break;
3716 	default:
3717 		return false;
3718 	}
3719 
3720 	return true;
3721 }
3722 
3723 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3724 			     struct bpf_insn *insn, int *insn_idx)
3725 {
3726 	struct bpf_verifier_state *this_branch = env->cur_state;
3727 	struct bpf_verifier_state *other_branch;
3728 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
3729 	struct bpf_reg_state *dst_reg, *other_branch_regs;
3730 	u8 opcode = BPF_OP(insn->code);
3731 	int err;
3732 
3733 	if (opcode > BPF_JSLE) {
3734 		verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
3735 		return -EINVAL;
3736 	}
3737 
3738 	if (BPF_SRC(insn->code) == BPF_X) {
3739 		if (insn->imm != 0) {
3740 			verbose(env, "BPF_JMP uses reserved fields\n");
3741 			return -EINVAL;
3742 		}
3743 
3744 		/* check src1 operand */
3745 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
3746 		if (err)
3747 			return err;
3748 
3749 		if (is_pointer_value(env, insn->src_reg)) {
3750 			verbose(env, "R%d pointer comparison prohibited\n",
3751 				insn->src_reg);
3752 			return -EACCES;
3753 		}
3754 	} else {
3755 		if (insn->src_reg != BPF_REG_0) {
3756 			verbose(env, "BPF_JMP uses reserved fields\n");
3757 			return -EINVAL;
3758 		}
3759 	}
3760 
3761 	/* check src2 operand */
3762 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3763 	if (err)
3764 		return err;
3765 
3766 	dst_reg = &regs[insn->dst_reg];
3767 
3768 	/* detect if R == 0 where R was initialized to zero earlier */
3769 	if (BPF_SRC(insn->code) == BPF_K &&
3770 	    (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3771 	    dst_reg->type == SCALAR_VALUE &&
3772 	    tnum_is_const(dst_reg->var_off)) {
3773 		if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
3774 		    (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
3775 			/* if (imm == imm) goto pc+off;
3776 			 * only follow the goto, ignore fall-through
3777 			 */
3778 			*insn_idx += insn->off;
3779 			return 0;
3780 		} else {
3781 			/* if (imm != imm) goto pc+off;
3782 			 * only follow fall-through branch, since
3783 			 * that's where the program will go
3784 			 */
3785 			return 0;
3786 		}
3787 	}
3788 
3789 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
3790 	if (!other_branch)
3791 		return -EFAULT;
3792 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
3793 
3794 	/* detect if we are comparing against a constant value so we can adjust
3795 	 * our min/max values for our dst register.
3796 	 * this is only legit if both are scalars (or pointers to the same
3797 	 * object, I suppose, but we don't support that right now), because
3798 	 * otherwise the different base pointers mean the offsets aren't
3799 	 * comparable.
3800 	 */
3801 	if (BPF_SRC(insn->code) == BPF_X) {
3802 		if (dst_reg->type == SCALAR_VALUE &&
3803 		    regs[insn->src_reg].type == SCALAR_VALUE) {
3804 			if (tnum_is_const(regs[insn->src_reg].var_off))
3805 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
3806 						dst_reg, regs[insn->src_reg].var_off.value,
3807 						opcode);
3808 			else if (tnum_is_const(dst_reg->var_off))
3809 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
3810 						    &regs[insn->src_reg],
3811 						    dst_reg->var_off.value, opcode);
3812 			else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3813 				/* Comparing for equality, we can combine knowledge */
3814 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
3815 						    &other_branch_regs[insn->dst_reg],
3816 						    &regs[insn->src_reg],
3817 						    &regs[insn->dst_reg], opcode);
3818 		}
3819 	} else if (dst_reg->type == SCALAR_VALUE) {
3820 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
3821 					dst_reg, insn->imm, opcode);
3822 	}
3823 
3824 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3825 	if (BPF_SRC(insn->code) == BPF_K &&
3826 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3827 	    dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3828 		/* Mark all identical map registers in each branch as either
3829 		 * safe or unknown depending R == 0 or R != 0 conditional.
3830 		 */
3831 		mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3832 		mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3833 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
3834 					   this_branch, other_branch) &&
3835 		   is_pointer_value(env, insn->dst_reg)) {
3836 		verbose(env, "R%d pointer comparison prohibited\n",
3837 			insn->dst_reg);
3838 		return -EACCES;
3839 	}
3840 	if (env->log.level)
3841 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
3842 	return 0;
3843 }
3844 
3845 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3846 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3847 {
3848 	u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3849 
3850 	return (struct bpf_map *) (unsigned long) imm64;
3851 }
3852 
3853 /* verify BPF_LD_IMM64 instruction */
3854 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3855 {
3856 	struct bpf_reg_state *regs = cur_regs(env);
3857 	int err;
3858 
3859 	if (BPF_SIZE(insn->code) != BPF_DW) {
3860 		verbose(env, "invalid BPF_LD_IMM insn\n");
3861 		return -EINVAL;
3862 	}
3863 	if (insn->off != 0) {
3864 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
3865 		return -EINVAL;
3866 	}
3867 
3868 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
3869 	if (err)
3870 		return err;
3871 
3872 	if (insn->src_reg == 0) {
3873 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3874 
3875 		regs[insn->dst_reg].type = SCALAR_VALUE;
3876 		__mark_reg_known(&regs[insn->dst_reg], imm);
3877 		return 0;
3878 	}
3879 
3880 	/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3881 	BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3882 
3883 	regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3884 	regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3885 	return 0;
3886 }
3887 
3888 static bool may_access_skb(enum bpf_prog_type type)
3889 {
3890 	switch (type) {
3891 	case BPF_PROG_TYPE_SOCKET_FILTER:
3892 	case BPF_PROG_TYPE_SCHED_CLS:
3893 	case BPF_PROG_TYPE_SCHED_ACT:
3894 		return true;
3895 	default:
3896 		return false;
3897 	}
3898 }
3899 
3900 /* verify safety of LD_ABS|LD_IND instructions:
3901  * - they can only appear in the programs where ctx == skb
3902  * - since they are wrappers of function calls, they scratch R1-R5 registers,
3903  *   preserve R6-R9, and store return value into R0
3904  *
3905  * Implicit input:
3906  *   ctx == skb == R6 == CTX
3907  *
3908  * Explicit input:
3909  *   SRC == any register
3910  *   IMM == 32-bit immediate
3911  *
3912  * Output:
3913  *   R0 - 8/16/32-bit skb data converted to cpu endianness
3914  */
3915 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3916 {
3917 	struct bpf_reg_state *regs = cur_regs(env);
3918 	u8 mode = BPF_MODE(insn->code);
3919 	int i, err;
3920 
3921 	if (!may_access_skb(env->prog->type)) {
3922 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3923 		return -EINVAL;
3924 	}
3925 
3926 	if (!env->ops->gen_ld_abs) {
3927 		verbose(env, "bpf verifier is misconfigured\n");
3928 		return -EINVAL;
3929 	}
3930 
3931 	if (env->subprog_cnt > 1) {
3932 		/* when program has LD_ABS insn JITs and interpreter assume
3933 		 * that r1 == ctx == skb which is not the case for callees
3934 		 * that can have arbitrary arguments. It's problematic
3935 		 * for main prog as well since JITs would need to analyze
3936 		 * all functions in order to make proper register save/restore
3937 		 * decisions in the main prog. Hence disallow LD_ABS with calls
3938 		 */
3939 		verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
3940 		return -EINVAL;
3941 	}
3942 
3943 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3944 	    BPF_SIZE(insn->code) == BPF_DW ||
3945 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3946 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
3947 		return -EINVAL;
3948 	}
3949 
3950 	/* check whether implicit source operand (register R6) is readable */
3951 	err = check_reg_arg(env, BPF_REG_6, SRC_OP);
3952 	if (err)
3953 		return err;
3954 
3955 	if (regs[BPF_REG_6].type != PTR_TO_CTX) {
3956 		verbose(env,
3957 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3958 		return -EINVAL;
3959 	}
3960 
3961 	if (mode == BPF_IND) {
3962 		/* check explicit source operand */
3963 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
3964 		if (err)
3965 			return err;
3966 	}
3967 
3968 	/* reset caller saved regs to unreadable */
3969 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
3970 		mark_reg_not_init(env, regs, caller_saved[i]);
3971 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3972 	}
3973 
3974 	/* mark destination R0 register as readable, since it contains
3975 	 * the value fetched from the packet.
3976 	 * Already marked as written above.
3977 	 */
3978 	mark_reg_unknown(env, regs, BPF_REG_0);
3979 	return 0;
3980 }
3981 
3982 static int check_return_code(struct bpf_verifier_env *env)
3983 {
3984 	struct bpf_reg_state *reg;
3985 	struct tnum range = tnum_range(0, 1);
3986 
3987 	switch (env->prog->type) {
3988 	case BPF_PROG_TYPE_CGROUP_SKB:
3989 	case BPF_PROG_TYPE_CGROUP_SOCK:
3990 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3991 	case BPF_PROG_TYPE_SOCK_OPS:
3992 	case BPF_PROG_TYPE_CGROUP_DEVICE:
3993 		break;
3994 	default:
3995 		return 0;
3996 	}
3997 
3998 	reg = cur_regs(env) + BPF_REG_0;
3999 	if (reg->type != SCALAR_VALUE) {
4000 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
4001 			reg_type_str[reg->type]);
4002 		return -EINVAL;
4003 	}
4004 
4005 	if (!tnum_in(range, reg->var_off)) {
4006 		verbose(env, "At program exit the register R0 ");
4007 		if (!tnum_is_unknown(reg->var_off)) {
4008 			char tn_buf[48];
4009 
4010 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4011 			verbose(env, "has value %s", tn_buf);
4012 		} else {
4013 			verbose(env, "has unknown scalar value");
4014 		}
4015 		verbose(env, " should have been 0 or 1\n");
4016 		return -EINVAL;
4017 	}
4018 	return 0;
4019 }
4020 
4021 /* non-recursive DFS pseudo code
4022  * 1  procedure DFS-iterative(G,v):
4023  * 2      label v as discovered
4024  * 3      let S be a stack
4025  * 4      S.push(v)
4026  * 5      while S is not empty
4027  * 6            t <- S.pop()
4028  * 7            if t is what we're looking for:
4029  * 8                return t
4030  * 9            for all edges e in G.adjacentEdges(t) do
4031  * 10               if edge e is already labelled
4032  * 11                   continue with the next edge
4033  * 12               w <- G.adjacentVertex(t,e)
4034  * 13               if vertex w is not discovered and not explored
4035  * 14                   label e as tree-edge
4036  * 15                   label w as discovered
4037  * 16                   S.push(w)
4038  * 17                   continue at 5
4039  * 18               else if vertex w is discovered
4040  * 19                   label e as back-edge
4041  * 20               else
4042  * 21                   // vertex w is explored
4043  * 22                   label e as forward- or cross-edge
4044  * 23           label t as explored
4045  * 24           S.pop()
4046  *
4047  * convention:
4048  * 0x10 - discovered
4049  * 0x11 - discovered and fall-through edge labelled
4050  * 0x12 - discovered and fall-through and branch edges labelled
4051  * 0x20 - explored
4052  */
4053 
4054 enum {
4055 	DISCOVERED = 0x10,
4056 	EXPLORED = 0x20,
4057 	FALLTHROUGH = 1,
4058 	BRANCH = 2,
4059 };
4060 
4061 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
4062 
4063 static int *insn_stack;	/* stack of insns to process */
4064 static int cur_stack;	/* current stack index */
4065 static int *insn_state;
4066 
4067 /* t, w, e - match pseudo-code above:
4068  * t - index of current instruction
4069  * w - next instruction
4070  * e - edge
4071  */
4072 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
4073 {
4074 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
4075 		return 0;
4076 
4077 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
4078 		return 0;
4079 
4080 	if (w < 0 || w >= env->prog->len) {
4081 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
4082 		return -EINVAL;
4083 	}
4084 
4085 	if (e == BRANCH)
4086 		/* mark branch target for state pruning */
4087 		env->explored_states[w] = STATE_LIST_MARK;
4088 
4089 	if (insn_state[w] == 0) {
4090 		/* tree-edge */
4091 		insn_state[t] = DISCOVERED | e;
4092 		insn_state[w] = DISCOVERED;
4093 		if (cur_stack >= env->prog->len)
4094 			return -E2BIG;
4095 		insn_stack[cur_stack++] = w;
4096 		return 1;
4097 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4098 		verbose(env, "back-edge from insn %d to %d\n", t, w);
4099 		return -EINVAL;
4100 	} else if (insn_state[w] == EXPLORED) {
4101 		/* forward- or cross-edge */
4102 		insn_state[t] = DISCOVERED | e;
4103 	} else {
4104 		verbose(env, "insn state internal bug\n");
4105 		return -EFAULT;
4106 	}
4107 	return 0;
4108 }
4109 
4110 /* non-recursive depth-first-search to detect loops in BPF program
4111  * loop == back-edge in directed graph
4112  */
4113 static int check_cfg(struct bpf_verifier_env *env)
4114 {
4115 	struct bpf_insn *insns = env->prog->insnsi;
4116 	int insn_cnt = env->prog->len;
4117 	int ret = 0;
4118 	int i, t;
4119 
4120 	ret = check_subprogs(env);
4121 	if (ret < 0)
4122 		return ret;
4123 
4124 	insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4125 	if (!insn_state)
4126 		return -ENOMEM;
4127 
4128 	insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4129 	if (!insn_stack) {
4130 		kfree(insn_state);
4131 		return -ENOMEM;
4132 	}
4133 
4134 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4135 	insn_stack[0] = 0; /* 0 is the first instruction */
4136 	cur_stack = 1;
4137 
4138 peek_stack:
4139 	if (cur_stack == 0)
4140 		goto check_state;
4141 	t = insn_stack[cur_stack - 1];
4142 
4143 	if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4144 		u8 opcode = BPF_OP(insns[t].code);
4145 
4146 		if (opcode == BPF_EXIT) {
4147 			goto mark_explored;
4148 		} else if (opcode == BPF_CALL) {
4149 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
4150 			if (ret == 1)
4151 				goto peek_stack;
4152 			else if (ret < 0)
4153 				goto err_free;
4154 			if (t + 1 < insn_cnt)
4155 				env->explored_states[t + 1] = STATE_LIST_MARK;
4156 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4157 				env->explored_states[t] = STATE_LIST_MARK;
4158 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4159 				if (ret == 1)
4160 					goto peek_stack;
4161 				else if (ret < 0)
4162 					goto err_free;
4163 			}
4164 		} else if (opcode == BPF_JA) {
4165 			if (BPF_SRC(insns[t].code) != BPF_K) {
4166 				ret = -EINVAL;
4167 				goto err_free;
4168 			}
4169 			/* unconditional jump with single edge */
4170 			ret = push_insn(t, t + insns[t].off + 1,
4171 					FALLTHROUGH, env);
4172 			if (ret == 1)
4173 				goto peek_stack;
4174 			else if (ret < 0)
4175 				goto err_free;
4176 			/* tell verifier to check for equivalent states
4177 			 * after every call and jump
4178 			 */
4179 			if (t + 1 < insn_cnt)
4180 				env->explored_states[t + 1] = STATE_LIST_MARK;
4181 		} else {
4182 			/* conditional jump with two edges */
4183 			env->explored_states[t] = STATE_LIST_MARK;
4184 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
4185 			if (ret == 1)
4186 				goto peek_stack;
4187 			else if (ret < 0)
4188 				goto err_free;
4189 
4190 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4191 			if (ret == 1)
4192 				goto peek_stack;
4193 			else if (ret < 0)
4194 				goto err_free;
4195 		}
4196 	} else {
4197 		/* all other non-branch instructions with single
4198 		 * fall-through edge
4199 		 */
4200 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
4201 		if (ret == 1)
4202 			goto peek_stack;
4203 		else if (ret < 0)
4204 			goto err_free;
4205 	}
4206 
4207 mark_explored:
4208 	insn_state[t] = EXPLORED;
4209 	if (cur_stack-- <= 0) {
4210 		verbose(env, "pop stack internal bug\n");
4211 		ret = -EFAULT;
4212 		goto err_free;
4213 	}
4214 	goto peek_stack;
4215 
4216 check_state:
4217 	for (i = 0; i < insn_cnt; i++) {
4218 		if (insn_state[i] != EXPLORED) {
4219 			verbose(env, "unreachable insn %d\n", i);
4220 			ret = -EINVAL;
4221 			goto err_free;
4222 		}
4223 	}
4224 	ret = 0; /* cfg looks good */
4225 
4226 err_free:
4227 	kfree(insn_state);
4228 	kfree(insn_stack);
4229 	return ret;
4230 }
4231 
4232 /* check %cur's range satisfies %old's */
4233 static bool range_within(struct bpf_reg_state *old,
4234 			 struct bpf_reg_state *cur)
4235 {
4236 	return old->umin_value <= cur->umin_value &&
4237 	       old->umax_value >= cur->umax_value &&
4238 	       old->smin_value <= cur->smin_value &&
4239 	       old->smax_value >= cur->smax_value;
4240 }
4241 
4242 /* Maximum number of register states that can exist at once */
4243 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4244 struct idpair {
4245 	u32 old;
4246 	u32 cur;
4247 };
4248 
4249 /* If in the old state two registers had the same id, then they need to have
4250  * the same id in the new state as well.  But that id could be different from
4251  * the old state, so we need to track the mapping from old to new ids.
4252  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4253  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
4254  * regs with a different old id could still have new id 9, we don't care about
4255  * that.
4256  * So we look through our idmap to see if this old id has been seen before.  If
4257  * so, we require the new id to match; otherwise, we add the id pair to the map.
4258  */
4259 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4260 {
4261 	unsigned int i;
4262 
4263 	for (i = 0; i < ID_MAP_SIZE; i++) {
4264 		if (!idmap[i].old) {
4265 			/* Reached an empty slot; haven't seen this id before */
4266 			idmap[i].old = old_id;
4267 			idmap[i].cur = cur_id;
4268 			return true;
4269 		}
4270 		if (idmap[i].old == old_id)
4271 			return idmap[i].cur == cur_id;
4272 	}
4273 	/* We ran out of idmap slots, which should be impossible */
4274 	WARN_ON_ONCE(1);
4275 	return false;
4276 }
4277 
4278 /* Returns true if (rold safe implies rcur safe) */
4279 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4280 		    struct idpair *idmap)
4281 {
4282 	bool equal;
4283 
4284 	if (!(rold->live & REG_LIVE_READ))
4285 		/* explored state didn't use this */
4286 		return true;
4287 
4288 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
4289 
4290 	if (rold->type == PTR_TO_STACK)
4291 		/* two stack pointers are equal only if they're pointing to
4292 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
4293 		 */
4294 		return equal && rold->frameno == rcur->frameno;
4295 
4296 	if (equal)
4297 		return true;
4298 
4299 	if (rold->type == NOT_INIT)
4300 		/* explored state can't have used this */
4301 		return true;
4302 	if (rcur->type == NOT_INIT)
4303 		return false;
4304 	switch (rold->type) {
4305 	case SCALAR_VALUE:
4306 		if (rcur->type == SCALAR_VALUE) {
4307 			/* new val must satisfy old val knowledge */
4308 			return range_within(rold, rcur) &&
4309 			       tnum_in(rold->var_off, rcur->var_off);
4310 		} else {
4311 			/* We're trying to use a pointer in place of a scalar.
4312 			 * Even if the scalar was unbounded, this could lead to
4313 			 * pointer leaks because scalars are allowed to leak
4314 			 * while pointers are not. We could make this safe in
4315 			 * special cases if root is calling us, but it's
4316 			 * probably not worth the hassle.
4317 			 */
4318 			return false;
4319 		}
4320 	case PTR_TO_MAP_VALUE:
4321 		/* If the new min/max/var_off satisfy the old ones and
4322 		 * everything else matches, we are OK.
4323 		 * We don't care about the 'id' value, because nothing
4324 		 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4325 		 */
4326 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4327 		       range_within(rold, rcur) &&
4328 		       tnum_in(rold->var_off, rcur->var_off);
4329 	case PTR_TO_MAP_VALUE_OR_NULL:
4330 		/* a PTR_TO_MAP_VALUE could be safe to use as a
4331 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4332 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4333 		 * checked, doing so could have affected others with the same
4334 		 * id, and we can't check for that because we lost the id when
4335 		 * we converted to a PTR_TO_MAP_VALUE.
4336 		 */
4337 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4338 			return false;
4339 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4340 			return false;
4341 		/* Check our ids match any regs they're supposed to */
4342 		return check_ids(rold->id, rcur->id, idmap);
4343 	case PTR_TO_PACKET_META:
4344 	case PTR_TO_PACKET:
4345 		if (rcur->type != rold->type)
4346 			return false;
4347 		/* We must have at least as much range as the old ptr
4348 		 * did, so that any accesses which were safe before are
4349 		 * still safe.  This is true even if old range < old off,
4350 		 * since someone could have accessed through (ptr - k), or
4351 		 * even done ptr -= k in a register, to get a safe access.
4352 		 */
4353 		if (rold->range > rcur->range)
4354 			return false;
4355 		/* If the offsets don't match, we can't trust our alignment;
4356 		 * nor can we be sure that we won't fall out of range.
4357 		 */
4358 		if (rold->off != rcur->off)
4359 			return false;
4360 		/* id relations must be preserved */
4361 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4362 			return false;
4363 		/* new val must satisfy old val knowledge */
4364 		return range_within(rold, rcur) &&
4365 		       tnum_in(rold->var_off, rcur->var_off);
4366 	case PTR_TO_CTX:
4367 	case CONST_PTR_TO_MAP:
4368 	case PTR_TO_PACKET_END:
4369 		/* Only valid matches are exact, which memcmp() above
4370 		 * would have accepted
4371 		 */
4372 	default:
4373 		/* Don't know what's going on, just say it's not safe */
4374 		return false;
4375 	}
4376 
4377 	/* Shouldn't get here; if we do, say it's not safe */
4378 	WARN_ON_ONCE(1);
4379 	return false;
4380 }
4381 
4382 static bool stacksafe(struct bpf_func_state *old,
4383 		      struct bpf_func_state *cur,
4384 		      struct idpair *idmap)
4385 {
4386 	int i, spi;
4387 
4388 	/* if explored stack has more populated slots than current stack
4389 	 * such stacks are not equivalent
4390 	 */
4391 	if (old->allocated_stack > cur->allocated_stack)
4392 		return false;
4393 
4394 	/* walk slots of the explored stack and ignore any additional
4395 	 * slots in the current stack, since explored(safe) state
4396 	 * didn't use them
4397 	 */
4398 	for (i = 0; i < old->allocated_stack; i++) {
4399 		spi = i / BPF_REG_SIZE;
4400 
4401 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4402 			/* explored state didn't use this */
4403 			continue;
4404 
4405 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4406 			continue;
4407 		/* if old state was safe with misc data in the stack
4408 		 * it will be safe with zero-initialized stack.
4409 		 * The opposite is not true
4410 		 */
4411 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4412 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4413 			continue;
4414 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4415 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4416 			/* Ex: old explored (safe) state has STACK_SPILL in
4417 			 * this stack slot, but current has has STACK_MISC ->
4418 			 * this verifier states are not equivalent,
4419 			 * return false to continue verification of this path
4420 			 */
4421 			return false;
4422 		if (i % BPF_REG_SIZE)
4423 			continue;
4424 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
4425 			continue;
4426 		if (!regsafe(&old->stack[spi].spilled_ptr,
4427 			     &cur->stack[spi].spilled_ptr,
4428 			     idmap))
4429 			/* when explored and current stack slot are both storing
4430 			 * spilled registers, check that stored pointers types
4431 			 * are the same as well.
4432 			 * Ex: explored safe path could have stored
4433 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4434 			 * but current path has stored:
4435 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4436 			 * such verifier states are not equivalent.
4437 			 * return false to continue verification of this path
4438 			 */
4439 			return false;
4440 	}
4441 	return true;
4442 }
4443 
4444 /* compare two verifier states
4445  *
4446  * all states stored in state_list are known to be valid, since
4447  * verifier reached 'bpf_exit' instruction through them
4448  *
4449  * this function is called when verifier exploring different branches of
4450  * execution popped from the state stack. If it sees an old state that has
4451  * more strict register state and more strict stack state then this execution
4452  * branch doesn't need to be explored further, since verifier already
4453  * concluded that more strict state leads to valid finish.
4454  *
4455  * Therefore two states are equivalent if register state is more conservative
4456  * and explored stack state is more conservative than the current one.
4457  * Example:
4458  *       explored                   current
4459  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
4460  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
4461  *
4462  * In other words if current stack state (one being explored) has more
4463  * valid slots than old one that already passed validation, it means
4464  * the verifier can stop exploring and conclude that current state is valid too
4465  *
4466  * Similarly with registers. If explored state has register type as invalid
4467  * whereas register type in current state is meaningful, it means that
4468  * the current state will reach 'bpf_exit' instruction safely
4469  */
4470 static bool func_states_equal(struct bpf_func_state *old,
4471 			      struct bpf_func_state *cur)
4472 {
4473 	struct idpair *idmap;
4474 	bool ret = false;
4475 	int i;
4476 
4477 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4478 	/* If we failed to allocate the idmap, just say it's not safe */
4479 	if (!idmap)
4480 		return false;
4481 
4482 	for (i = 0; i < MAX_BPF_REG; i++) {
4483 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4484 			goto out_free;
4485 	}
4486 
4487 	if (!stacksafe(old, cur, idmap))
4488 		goto out_free;
4489 	ret = true;
4490 out_free:
4491 	kfree(idmap);
4492 	return ret;
4493 }
4494 
4495 static bool states_equal(struct bpf_verifier_env *env,
4496 			 struct bpf_verifier_state *old,
4497 			 struct bpf_verifier_state *cur)
4498 {
4499 	int i;
4500 
4501 	if (old->curframe != cur->curframe)
4502 		return false;
4503 
4504 	/* for states to be equal callsites have to be the same
4505 	 * and all frame states need to be equivalent
4506 	 */
4507 	for (i = 0; i <= old->curframe; i++) {
4508 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
4509 			return false;
4510 		if (!func_states_equal(old->frame[i], cur->frame[i]))
4511 			return false;
4512 	}
4513 	return true;
4514 }
4515 
4516 /* A write screens off any subsequent reads; but write marks come from the
4517  * straight-line code between a state and its parent.  When we arrive at an
4518  * equivalent state (jump target or such) we didn't arrive by the straight-line
4519  * code, so read marks in the state must propagate to the parent regardless
4520  * of the state's write marks. That's what 'parent == state->parent' comparison
4521  * in mark_reg_read() is for.
4522  */
4523 static int propagate_liveness(struct bpf_verifier_env *env,
4524 			      const struct bpf_verifier_state *vstate,
4525 			      struct bpf_verifier_state *vparent)
4526 {
4527 	int i, frame, err = 0;
4528 	struct bpf_func_state *state, *parent;
4529 
4530 	if (vparent->curframe != vstate->curframe) {
4531 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
4532 		     vparent->curframe, vstate->curframe);
4533 		return -EFAULT;
4534 	}
4535 	/* Propagate read liveness of registers... */
4536 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4537 	/* We don't need to worry about FP liveness because it's read-only */
4538 	for (i = 0; i < BPF_REG_FP; i++) {
4539 		if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
4540 			continue;
4541 		if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
4542 			err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i],
4543 					    &vparent->frame[vstate->curframe]->regs[i]);
4544 			if (err)
4545 				return err;
4546 		}
4547 	}
4548 
4549 	/* ... and stack slots */
4550 	for (frame = 0; frame <= vstate->curframe; frame++) {
4551 		state = vstate->frame[frame];
4552 		parent = vparent->frame[frame];
4553 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4554 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4555 			if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4556 				continue;
4557 			if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
4558 				mark_reg_read(env, &state->stack[i].spilled_ptr,
4559 					      &parent->stack[i].spilled_ptr);
4560 		}
4561 	}
4562 	return err;
4563 }
4564 
4565 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4566 {
4567 	struct bpf_verifier_state_list *new_sl;
4568 	struct bpf_verifier_state_list *sl;
4569 	struct bpf_verifier_state *cur = env->cur_state, *new;
4570 	int i, j, err;
4571 
4572 	sl = env->explored_states[insn_idx];
4573 	if (!sl)
4574 		/* this 'insn_idx' instruction wasn't marked, so we will not
4575 		 * be doing state search here
4576 		 */
4577 		return 0;
4578 
4579 	while (sl != STATE_LIST_MARK) {
4580 		if (states_equal(env, &sl->state, cur)) {
4581 			/* reached equivalent register/stack state,
4582 			 * prune the search.
4583 			 * Registers read by the continuation are read by us.
4584 			 * If we have any write marks in env->cur_state, they
4585 			 * will prevent corresponding reads in the continuation
4586 			 * from reaching our parent (an explored_state).  Our
4587 			 * own state will get the read marks recorded, but
4588 			 * they'll be immediately forgotten as we're pruning
4589 			 * this state and will pop a new one.
4590 			 */
4591 			err = propagate_liveness(env, &sl->state, cur);
4592 			if (err)
4593 				return err;
4594 			return 1;
4595 		}
4596 		sl = sl->next;
4597 	}
4598 
4599 	/* there were no equivalent states, remember current one.
4600 	 * technically the current state is not proven to be safe yet,
4601 	 * but it will either reach outer most bpf_exit (which means it's safe)
4602 	 * or it will be rejected. Since there are no loops, we won't be
4603 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
4604 	 * again on the way to bpf_exit
4605 	 */
4606 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4607 	if (!new_sl)
4608 		return -ENOMEM;
4609 
4610 	/* add new state to the head of linked list */
4611 	new = &new_sl->state;
4612 	err = copy_verifier_state(new, cur);
4613 	if (err) {
4614 		free_verifier_state(new, false);
4615 		kfree(new_sl);
4616 		return err;
4617 	}
4618 	new_sl->next = env->explored_states[insn_idx];
4619 	env->explored_states[insn_idx] = new_sl;
4620 	/* connect new state to parentage chain */
4621 	for (i = 0; i < BPF_REG_FP; i++)
4622 		cur_regs(env)[i].parent = &new->frame[new->curframe]->regs[i];
4623 	/* clear write marks in current state: the writes we did are not writes
4624 	 * our child did, so they don't screen off its reads from us.
4625 	 * (There are no read marks in current state, because reads always mark
4626 	 * their parent and current state never has children yet.  Only
4627 	 * explored_states can get read marks.)
4628 	 */
4629 	for (i = 0; i < BPF_REG_FP; i++)
4630 		cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
4631 
4632 	/* all stack frames are accessible from callee, clear them all */
4633 	for (j = 0; j <= cur->curframe; j++) {
4634 		struct bpf_func_state *frame = cur->frame[j];
4635 		struct bpf_func_state *newframe = new->frame[j];
4636 
4637 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
4638 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4639 			frame->stack[i].spilled_ptr.parent =
4640 						&newframe->stack[i].spilled_ptr;
4641 		}
4642 	}
4643 	return 0;
4644 }
4645 
4646 static int do_check(struct bpf_verifier_env *env)
4647 {
4648 	struct bpf_verifier_state *state;
4649 	struct bpf_insn *insns = env->prog->insnsi;
4650 	struct bpf_reg_state *regs;
4651 	int insn_cnt = env->prog->len, i;
4652 	int insn_idx, prev_insn_idx = 0;
4653 	int insn_processed = 0;
4654 	bool do_print_state = false;
4655 
4656 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4657 	if (!state)
4658 		return -ENOMEM;
4659 	state->curframe = 0;
4660 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
4661 	if (!state->frame[0]) {
4662 		kfree(state);
4663 		return -ENOMEM;
4664 	}
4665 	env->cur_state = state;
4666 	init_func_state(env, state->frame[0],
4667 			BPF_MAIN_FUNC /* callsite */,
4668 			0 /* frameno */,
4669 			0 /* subprogno, zero == main subprog */);
4670 	insn_idx = 0;
4671 	for (;;) {
4672 		struct bpf_insn *insn;
4673 		u8 class;
4674 		int err;
4675 
4676 		if (insn_idx >= insn_cnt) {
4677 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
4678 				insn_idx, insn_cnt);
4679 			return -EFAULT;
4680 		}
4681 
4682 		insn = &insns[insn_idx];
4683 		class = BPF_CLASS(insn->code);
4684 
4685 		if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4686 			verbose(env,
4687 				"BPF program is too large. Processed %d insn\n",
4688 				insn_processed);
4689 			return -E2BIG;
4690 		}
4691 
4692 		err = is_state_visited(env, insn_idx);
4693 		if (err < 0)
4694 			return err;
4695 		if (err == 1) {
4696 			/* found equivalent state, can prune the search */
4697 			if (env->log.level) {
4698 				if (do_print_state)
4699 					verbose(env, "\nfrom %d to %d: safe\n",
4700 						prev_insn_idx, insn_idx);
4701 				else
4702 					verbose(env, "%d: safe\n", insn_idx);
4703 			}
4704 			goto process_bpf_exit;
4705 		}
4706 
4707 		if (need_resched())
4708 			cond_resched();
4709 
4710 		if (env->log.level > 1 || (env->log.level && do_print_state)) {
4711 			if (env->log.level > 1)
4712 				verbose(env, "%d:", insn_idx);
4713 			else
4714 				verbose(env, "\nfrom %d to %d:",
4715 					prev_insn_idx, insn_idx);
4716 			print_verifier_state(env, state->frame[state->curframe]);
4717 			do_print_state = false;
4718 		}
4719 
4720 		if (env->log.level) {
4721 			const struct bpf_insn_cbs cbs = {
4722 				.cb_print	= verbose,
4723 				.private_data	= env,
4724 			};
4725 
4726 			verbose(env, "%d: ", insn_idx);
4727 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4728 		}
4729 
4730 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
4731 			err = bpf_prog_offload_verify_insn(env, insn_idx,
4732 							   prev_insn_idx);
4733 			if (err)
4734 				return err;
4735 		}
4736 
4737 		regs = cur_regs(env);
4738 		env->insn_aux_data[insn_idx].seen = true;
4739 		if (class == BPF_ALU || class == BPF_ALU64) {
4740 			err = check_alu_op(env, insn);
4741 			if (err)
4742 				return err;
4743 
4744 		} else if (class == BPF_LDX) {
4745 			enum bpf_reg_type *prev_src_type, src_reg_type;
4746 
4747 			/* check for reserved fields is already done */
4748 
4749 			/* check src operand */
4750 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
4751 			if (err)
4752 				return err;
4753 
4754 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4755 			if (err)
4756 				return err;
4757 
4758 			src_reg_type = regs[insn->src_reg].type;
4759 
4760 			/* check that memory (src_reg + off) is readable,
4761 			 * the state of dst_reg will be updated by this func
4762 			 */
4763 			err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
4764 					       BPF_SIZE(insn->code), BPF_READ,
4765 					       insn->dst_reg, false);
4766 			if (err)
4767 				return err;
4768 
4769 			prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
4770 
4771 			if (*prev_src_type == NOT_INIT) {
4772 				/* saw a valid insn
4773 				 * dst_reg = *(u32 *)(src_reg + off)
4774 				 * save type to validate intersecting paths
4775 				 */
4776 				*prev_src_type = src_reg_type;
4777 
4778 			} else if (src_reg_type != *prev_src_type &&
4779 				   (src_reg_type == PTR_TO_CTX ||
4780 				    *prev_src_type == PTR_TO_CTX)) {
4781 				/* ABuser program is trying to use the same insn
4782 				 * dst_reg = *(u32*) (src_reg + off)
4783 				 * with different pointer types:
4784 				 * src_reg == ctx in one branch and
4785 				 * src_reg == stack|map in some other branch.
4786 				 * Reject it.
4787 				 */
4788 				verbose(env, "same insn cannot be used with different pointers\n");
4789 				return -EINVAL;
4790 			}
4791 
4792 		} else if (class == BPF_STX) {
4793 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
4794 
4795 			if (BPF_MODE(insn->code) == BPF_XADD) {
4796 				err = check_xadd(env, insn_idx, insn);
4797 				if (err)
4798 					return err;
4799 				insn_idx++;
4800 				continue;
4801 			}
4802 
4803 			/* check src1 operand */
4804 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
4805 			if (err)
4806 				return err;
4807 			/* check src2 operand */
4808 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4809 			if (err)
4810 				return err;
4811 
4812 			dst_reg_type = regs[insn->dst_reg].type;
4813 
4814 			/* check that memory (dst_reg + off) is writeable */
4815 			err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4816 					       BPF_SIZE(insn->code), BPF_WRITE,
4817 					       insn->src_reg, false);
4818 			if (err)
4819 				return err;
4820 
4821 			prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
4822 
4823 			if (*prev_dst_type == NOT_INIT) {
4824 				*prev_dst_type = dst_reg_type;
4825 			} else if (dst_reg_type != *prev_dst_type &&
4826 				   (dst_reg_type == PTR_TO_CTX ||
4827 				    *prev_dst_type == PTR_TO_CTX)) {
4828 				verbose(env, "same insn cannot be used with different pointers\n");
4829 				return -EINVAL;
4830 			}
4831 
4832 		} else if (class == BPF_ST) {
4833 			if (BPF_MODE(insn->code) != BPF_MEM ||
4834 			    insn->src_reg != BPF_REG_0) {
4835 				verbose(env, "BPF_ST uses reserved fields\n");
4836 				return -EINVAL;
4837 			}
4838 			/* check src operand */
4839 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4840 			if (err)
4841 				return err;
4842 
4843 			if (is_ctx_reg(env, insn->dst_reg)) {
4844 				verbose(env, "BPF_ST stores into R%d context is not allowed\n",
4845 					insn->dst_reg);
4846 				return -EACCES;
4847 			}
4848 
4849 			/* check that memory (dst_reg + off) is writeable */
4850 			err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4851 					       BPF_SIZE(insn->code), BPF_WRITE,
4852 					       -1, false);
4853 			if (err)
4854 				return err;
4855 
4856 		} else if (class == BPF_JMP) {
4857 			u8 opcode = BPF_OP(insn->code);
4858 
4859 			if (opcode == BPF_CALL) {
4860 				if (BPF_SRC(insn->code) != BPF_K ||
4861 				    insn->off != 0 ||
4862 				    (insn->src_reg != BPF_REG_0 &&
4863 				     insn->src_reg != BPF_PSEUDO_CALL) ||
4864 				    insn->dst_reg != BPF_REG_0) {
4865 					verbose(env, "BPF_CALL uses reserved fields\n");
4866 					return -EINVAL;
4867 				}
4868 
4869 				if (insn->src_reg == BPF_PSEUDO_CALL)
4870 					err = check_func_call(env, insn, &insn_idx);
4871 				else
4872 					err = check_helper_call(env, insn->imm, insn_idx);
4873 				if (err)
4874 					return err;
4875 
4876 			} else if (opcode == BPF_JA) {
4877 				if (BPF_SRC(insn->code) != BPF_K ||
4878 				    insn->imm != 0 ||
4879 				    insn->src_reg != BPF_REG_0 ||
4880 				    insn->dst_reg != BPF_REG_0) {
4881 					verbose(env, "BPF_JA uses reserved fields\n");
4882 					return -EINVAL;
4883 				}
4884 
4885 				insn_idx += insn->off + 1;
4886 				continue;
4887 
4888 			} else if (opcode == BPF_EXIT) {
4889 				if (BPF_SRC(insn->code) != BPF_K ||
4890 				    insn->imm != 0 ||
4891 				    insn->src_reg != BPF_REG_0 ||
4892 				    insn->dst_reg != BPF_REG_0) {
4893 					verbose(env, "BPF_EXIT uses reserved fields\n");
4894 					return -EINVAL;
4895 				}
4896 
4897 				if (state->curframe) {
4898 					/* exit from nested function */
4899 					prev_insn_idx = insn_idx;
4900 					err = prepare_func_exit(env, &insn_idx);
4901 					if (err)
4902 						return err;
4903 					do_print_state = true;
4904 					continue;
4905 				}
4906 
4907 				/* eBPF calling convetion is such that R0 is used
4908 				 * to return the value from eBPF program.
4909 				 * Make sure that it's readable at this time
4910 				 * of bpf_exit, which means that program wrote
4911 				 * something into it earlier
4912 				 */
4913 				err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4914 				if (err)
4915 					return err;
4916 
4917 				if (is_pointer_value(env, BPF_REG_0)) {
4918 					verbose(env, "R0 leaks addr as return value\n");
4919 					return -EACCES;
4920 				}
4921 
4922 				err = check_return_code(env);
4923 				if (err)
4924 					return err;
4925 process_bpf_exit:
4926 				err = pop_stack(env, &prev_insn_idx, &insn_idx);
4927 				if (err < 0) {
4928 					if (err != -ENOENT)
4929 						return err;
4930 					break;
4931 				} else {
4932 					do_print_state = true;
4933 					continue;
4934 				}
4935 			} else {
4936 				err = check_cond_jmp_op(env, insn, &insn_idx);
4937 				if (err)
4938 					return err;
4939 			}
4940 		} else if (class == BPF_LD) {
4941 			u8 mode = BPF_MODE(insn->code);
4942 
4943 			if (mode == BPF_ABS || mode == BPF_IND) {
4944 				err = check_ld_abs(env, insn);
4945 				if (err)
4946 					return err;
4947 
4948 			} else if (mode == BPF_IMM) {
4949 				err = check_ld_imm(env, insn);
4950 				if (err)
4951 					return err;
4952 
4953 				insn_idx++;
4954 				env->insn_aux_data[insn_idx].seen = true;
4955 			} else {
4956 				verbose(env, "invalid BPF_LD mode\n");
4957 				return -EINVAL;
4958 			}
4959 		} else {
4960 			verbose(env, "unknown insn class %d\n", class);
4961 			return -EINVAL;
4962 		}
4963 
4964 		insn_idx++;
4965 	}
4966 
4967 	verbose(env, "processed %d insns (limit %d), stack depth ",
4968 		insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
4969 	for (i = 0; i < env->subprog_cnt; i++) {
4970 		u32 depth = env->subprog_info[i].stack_depth;
4971 
4972 		verbose(env, "%d", depth);
4973 		if (i + 1 < env->subprog_cnt)
4974 			verbose(env, "+");
4975 	}
4976 	verbose(env, "\n");
4977 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
4978 	return 0;
4979 }
4980 
4981 static int check_map_prealloc(struct bpf_map *map)
4982 {
4983 	return (map->map_type != BPF_MAP_TYPE_HASH &&
4984 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4985 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4986 		!(map->map_flags & BPF_F_NO_PREALLOC);
4987 }
4988 
4989 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
4990 					struct bpf_map *map,
4991 					struct bpf_prog *prog)
4992 
4993 {
4994 	/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4995 	 * preallocated hash maps, since doing memory allocation
4996 	 * in overflow_handler can crash depending on where nmi got
4997 	 * triggered.
4998 	 */
4999 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
5000 		if (!check_map_prealloc(map)) {
5001 			verbose(env, "perf_event programs can only use preallocated hash map\n");
5002 			return -EINVAL;
5003 		}
5004 		if (map->inner_map_meta &&
5005 		    !check_map_prealloc(map->inner_map_meta)) {
5006 			verbose(env, "perf_event programs can only use preallocated inner hash map\n");
5007 			return -EINVAL;
5008 		}
5009 	}
5010 
5011 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
5012 	    !bpf_offload_prog_map_match(prog, map)) {
5013 		verbose(env, "offload device mismatch between prog and map\n");
5014 		return -EINVAL;
5015 	}
5016 
5017 	return 0;
5018 }
5019 
5020 /* look for pseudo eBPF instructions that access map FDs and
5021  * replace them with actual map pointers
5022  */
5023 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
5024 {
5025 	struct bpf_insn *insn = env->prog->insnsi;
5026 	int insn_cnt = env->prog->len;
5027 	int i, j, err;
5028 
5029 	err = bpf_prog_calc_tag(env->prog);
5030 	if (err)
5031 		return err;
5032 
5033 	for (i = 0; i < insn_cnt; i++, insn++) {
5034 		if (BPF_CLASS(insn->code) == BPF_LDX &&
5035 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
5036 			verbose(env, "BPF_LDX uses reserved fields\n");
5037 			return -EINVAL;
5038 		}
5039 
5040 		if (BPF_CLASS(insn->code) == BPF_STX &&
5041 		    ((BPF_MODE(insn->code) != BPF_MEM &&
5042 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
5043 			verbose(env, "BPF_STX uses reserved fields\n");
5044 			return -EINVAL;
5045 		}
5046 
5047 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
5048 			struct bpf_map *map;
5049 			struct fd f;
5050 
5051 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
5052 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
5053 			    insn[1].off != 0) {
5054 				verbose(env, "invalid bpf_ld_imm64 insn\n");
5055 				return -EINVAL;
5056 			}
5057 
5058 			if (insn->src_reg == 0)
5059 				/* valid generic load 64-bit imm */
5060 				goto next_insn;
5061 
5062 			if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
5063 				verbose(env,
5064 					"unrecognized bpf_ld_imm64 insn\n");
5065 				return -EINVAL;
5066 			}
5067 
5068 			f = fdget(insn->imm);
5069 			map = __bpf_map_get(f);
5070 			if (IS_ERR(map)) {
5071 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
5072 					insn->imm);
5073 				return PTR_ERR(map);
5074 			}
5075 
5076 			err = check_map_prog_compatibility(env, map, env->prog);
5077 			if (err) {
5078 				fdput(f);
5079 				return err;
5080 			}
5081 
5082 			/* store map pointer inside BPF_LD_IMM64 instruction */
5083 			insn[0].imm = (u32) (unsigned long) map;
5084 			insn[1].imm = ((u64) (unsigned long) map) >> 32;
5085 
5086 			/* check whether we recorded this map already */
5087 			for (j = 0; j < env->used_map_cnt; j++)
5088 				if (env->used_maps[j] == map) {
5089 					fdput(f);
5090 					goto next_insn;
5091 				}
5092 
5093 			if (env->used_map_cnt >= MAX_USED_MAPS) {
5094 				fdput(f);
5095 				return -E2BIG;
5096 			}
5097 
5098 			/* hold the map. If the program is rejected by verifier,
5099 			 * the map will be released by release_maps() or it
5100 			 * will be used by the valid program until it's unloaded
5101 			 * and all maps are released in free_used_maps()
5102 			 */
5103 			map = bpf_map_inc(map, false);
5104 			if (IS_ERR(map)) {
5105 				fdput(f);
5106 				return PTR_ERR(map);
5107 			}
5108 			env->used_maps[env->used_map_cnt++] = map;
5109 
5110 			if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
5111 			    bpf_cgroup_storage_assign(env->prog, map)) {
5112 				verbose(env,
5113 					"only one cgroup storage is allowed\n");
5114 				fdput(f);
5115 				return -EBUSY;
5116 			}
5117 
5118 			fdput(f);
5119 next_insn:
5120 			insn++;
5121 			i++;
5122 			continue;
5123 		}
5124 
5125 		/* Basic sanity check before we invest more work here. */
5126 		if (!bpf_opcode_in_insntable(insn->code)) {
5127 			verbose(env, "unknown opcode %02x\n", insn->code);
5128 			return -EINVAL;
5129 		}
5130 	}
5131 
5132 	/* now all pseudo BPF_LD_IMM64 instructions load valid
5133 	 * 'struct bpf_map *' into a register instead of user map_fd.
5134 	 * These pointers will be used later by verifier to validate map access.
5135 	 */
5136 	return 0;
5137 }
5138 
5139 /* drop refcnt of maps used by the rejected program */
5140 static void release_maps(struct bpf_verifier_env *env)
5141 {
5142 	int i;
5143 
5144 	if (env->prog->aux->cgroup_storage)
5145 		bpf_cgroup_storage_release(env->prog,
5146 					   env->prog->aux->cgroup_storage);
5147 
5148 	for (i = 0; i < env->used_map_cnt; i++)
5149 		bpf_map_put(env->used_maps[i]);
5150 }
5151 
5152 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5153 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5154 {
5155 	struct bpf_insn *insn = env->prog->insnsi;
5156 	int insn_cnt = env->prog->len;
5157 	int i;
5158 
5159 	for (i = 0; i < insn_cnt; i++, insn++)
5160 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5161 			insn->src_reg = 0;
5162 }
5163 
5164 /* single env->prog->insni[off] instruction was replaced with the range
5165  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
5166  * [0, off) and [off, end) to new locations, so the patched range stays zero
5167  */
5168 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5169 				u32 off, u32 cnt)
5170 {
5171 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5172 	int i;
5173 
5174 	if (cnt == 1)
5175 		return 0;
5176 	new_data = vzalloc(array_size(prog_len,
5177 				      sizeof(struct bpf_insn_aux_data)));
5178 	if (!new_data)
5179 		return -ENOMEM;
5180 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5181 	memcpy(new_data + off + cnt - 1, old_data + off,
5182 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5183 	for (i = off; i < off + cnt - 1; i++)
5184 		new_data[i].seen = true;
5185 	env->insn_aux_data = new_data;
5186 	vfree(old_data);
5187 	return 0;
5188 }
5189 
5190 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5191 {
5192 	int i;
5193 
5194 	if (len == 1)
5195 		return;
5196 	/* NOTE: fake 'exit' subprog should be updated as well. */
5197 	for (i = 0; i <= env->subprog_cnt; i++) {
5198 		if (env->subprog_info[i].start < off)
5199 			continue;
5200 		env->subprog_info[i].start += len - 1;
5201 	}
5202 }
5203 
5204 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5205 					    const struct bpf_insn *patch, u32 len)
5206 {
5207 	struct bpf_prog *new_prog;
5208 
5209 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5210 	if (!new_prog)
5211 		return NULL;
5212 	if (adjust_insn_aux_data(env, new_prog->len, off, len))
5213 		return NULL;
5214 	adjust_subprog_starts(env, off, len);
5215 	return new_prog;
5216 }
5217 
5218 /* The verifier does more data flow analysis than llvm and will not
5219  * explore branches that are dead at run time. Malicious programs can
5220  * have dead code too. Therefore replace all dead at-run-time code
5221  * with 'ja -1'.
5222  *
5223  * Just nops are not optimal, e.g. if they would sit at the end of the
5224  * program and through another bug we would manage to jump there, then
5225  * we'd execute beyond program memory otherwise. Returning exception
5226  * code also wouldn't work since we can have subprogs where the dead
5227  * code could be located.
5228  */
5229 static void sanitize_dead_code(struct bpf_verifier_env *env)
5230 {
5231 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5232 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5233 	struct bpf_insn *insn = env->prog->insnsi;
5234 	const int insn_cnt = env->prog->len;
5235 	int i;
5236 
5237 	for (i = 0; i < insn_cnt; i++) {
5238 		if (aux_data[i].seen)
5239 			continue;
5240 		memcpy(insn + i, &trap, sizeof(trap));
5241 	}
5242 }
5243 
5244 /* convert load instructions that access fields of 'struct __sk_buff'
5245  * into sequence of instructions that access fields of 'struct sk_buff'
5246  */
5247 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5248 {
5249 	const struct bpf_verifier_ops *ops = env->ops;
5250 	int i, cnt, size, ctx_field_size, delta = 0;
5251 	const int insn_cnt = env->prog->len;
5252 	struct bpf_insn insn_buf[16], *insn;
5253 	struct bpf_prog *new_prog;
5254 	enum bpf_access_type type;
5255 	bool is_narrower_load;
5256 	u32 target_size;
5257 
5258 	if (ops->gen_prologue) {
5259 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5260 					env->prog);
5261 		if (cnt >= ARRAY_SIZE(insn_buf)) {
5262 			verbose(env, "bpf verifier is misconfigured\n");
5263 			return -EINVAL;
5264 		} else if (cnt) {
5265 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5266 			if (!new_prog)
5267 				return -ENOMEM;
5268 
5269 			env->prog = new_prog;
5270 			delta += cnt - 1;
5271 		}
5272 	}
5273 
5274 	if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
5275 		return 0;
5276 
5277 	insn = env->prog->insnsi + delta;
5278 
5279 	for (i = 0; i < insn_cnt; i++, insn++) {
5280 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5281 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5282 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5283 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5284 			type = BPF_READ;
5285 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5286 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5287 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5288 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5289 			type = BPF_WRITE;
5290 		else
5291 			continue;
5292 
5293 		if (type == BPF_WRITE &&
5294 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
5295 			struct bpf_insn patch[] = {
5296 				/* Sanitize suspicious stack slot with zero.
5297 				 * There are no memory dependencies for this store,
5298 				 * since it's only using frame pointer and immediate
5299 				 * constant of zero
5300 				 */
5301 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
5302 					   env->insn_aux_data[i + delta].sanitize_stack_off,
5303 					   0),
5304 				/* the original STX instruction will immediately
5305 				 * overwrite the same stack slot with appropriate value
5306 				 */
5307 				*insn,
5308 			};
5309 
5310 			cnt = ARRAY_SIZE(patch);
5311 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
5312 			if (!new_prog)
5313 				return -ENOMEM;
5314 
5315 			delta    += cnt - 1;
5316 			env->prog = new_prog;
5317 			insn      = new_prog->insnsi + i + delta;
5318 			continue;
5319 		}
5320 
5321 		if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5322 			continue;
5323 
5324 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5325 		size = BPF_LDST_BYTES(insn);
5326 
5327 		/* If the read access is a narrower load of the field,
5328 		 * convert to a 4/8-byte load, to minimum program type specific
5329 		 * convert_ctx_access changes. If conversion is successful,
5330 		 * we will apply proper mask to the result.
5331 		 */
5332 		is_narrower_load = size < ctx_field_size;
5333 		if (is_narrower_load) {
5334 			u32 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
5335 			u32 off = insn->off;
5336 			u8 size_code;
5337 
5338 			if (type == BPF_WRITE) {
5339 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5340 				return -EINVAL;
5341 			}
5342 
5343 			size_code = BPF_H;
5344 			if (ctx_field_size == 4)
5345 				size_code = BPF_W;
5346 			else if (ctx_field_size == 8)
5347 				size_code = BPF_DW;
5348 
5349 			insn->off = off & ~(size_default - 1);
5350 			insn->code = BPF_LDX | BPF_MEM | size_code;
5351 		}
5352 
5353 		target_size = 0;
5354 		cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5355 					      &target_size);
5356 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5357 		    (ctx_field_size && !target_size)) {
5358 			verbose(env, "bpf verifier is misconfigured\n");
5359 			return -EINVAL;
5360 		}
5361 
5362 		if (is_narrower_load && size < target_size) {
5363 			if (ctx_field_size <= 4)
5364 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5365 								(1 << size * 8) - 1);
5366 			else
5367 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5368 								(1 << size * 8) - 1);
5369 		}
5370 
5371 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5372 		if (!new_prog)
5373 			return -ENOMEM;
5374 
5375 		delta += cnt - 1;
5376 
5377 		/* keep walking new program and skip insns we just inserted */
5378 		env->prog = new_prog;
5379 		insn      = new_prog->insnsi + i + delta;
5380 	}
5381 
5382 	return 0;
5383 }
5384 
5385 static int jit_subprogs(struct bpf_verifier_env *env)
5386 {
5387 	struct bpf_prog *prog = env->prog, **func, *tmp;
5388 	int i, j, subprog_start, subprog_end = 0, len, subprog;
5389 	struct bpf_insn *insn;
5390 	void *old_bpf_func;
5391 	int err = -ENOMEM;
5392 
5393 	if (env->subprog_cnt <= 1)
5394 		return 0;
5395 
5396 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5397 		if (insn->code != (BPF_JMP | BPF_CALL) ||
5398 		    insn->src_reg != BPF_PSEUDO_CALL)
5399 			continue;
5400 		/* Upon error here we cannot fall back to interpreter but
5401 		 * need a hard reject of the program. Thus -EFAULT is
5402 		 * propagated in any case.
5403 		 */
5404 		subprog = find_subprog(env, i + insn->imm + 1);
5405 		if (subprog < 0) {
5406 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5407 				  i + insn->imm + 1);
5408 			return -EFAULT;
5409 		}
5410 		/* temporarily remember subprog id inside insn instead of
5411 		 * aux_data, since next loop will split up all insns into funcs
5412 		 */
5413 		insn->off = subprog;
5414 		/* remember original imm in case JIT fails and fallback
5415 		 * to interpreter will be needed
5416 		 */
5417 		env->insn_aux_data[i].call_imm = insn->imm;
5418 		/* point imm to __bpf_call_base+1 from JITs point of view */
5419 		insn->imm = 1;
5420 	}
5421 
5422 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
5423 	if (!func)
5424 		goto out_undo_insn;
5425 
5426 	for (i = 0; i < env->subprog_cnt; i++) {
5427 		subprog_start = subprog_end;
5428 		subprog_end = env->subprog_info[i + 1].start;
5429 
5430 		len = subprog_end - subprog_start;
5431 		func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
5432 		if (!func[i])
5433 			goto out_free;
5434 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
5435 		       len * sizeof(struct bpf_insn));
5436 		func[i]->type = prog->type;
5437 		func[i]->len = len;
5438 		if (bpf_prog_calc_tag(func[i]))
5439 			goto out_free;
5440 		func[i]->is_func = 1;
5441 		/* Use bpf_prog_F_tag to indicate functions in stack traces.
5442 		 * Long term would need debug info to populate names
5443 		 */
5444 		func[i]->aux->name[0] = 'F';
5445 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
5446 		func[i]->jit_requested = 1;
5447 		func[i] = bpf_int_jit_compile(func[i]);
5448 		if (!func[i]->jited) {
5449 			err = -ENOTSUPP;
5450 			goto out_free;
5451 		}
5452 		cond_resched();
5453 	}
5454 	/* at this point all bpf functions were successfully JITed
5455 	 * now populate all bpf_calls with correct addresses and
5456 	 * run last pass of JIT
5457 	 */
5458 	for (i = 0; i < env->subprog_cnt; i++) {
5459 		insn = func[i]->insnsi;
5460 		for (j = 0; j < func[i]->len; j++, insn++) {
5461 			if (insn->code != (BPF_JMP | BPF_CALL) ||
5462 			    insn->src_reg != BPF_PSEUDO_CALL)
5463 				continue;
5464 			subprog = insn->off;
5465 			insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5466 				func[subprog]->bpf_func -
5467 				__bpf_call_base;
5468 		}
5469 
5470 		/* we use the aux data to keep a list of the start addresses
5471 		 * of the JITed images for each function in the program
5472 		 *
5473 		 * for some architectures, such as powerpc64, the imm field
5474 		 * might not be large enough to hold the offset of the start
5475 		 * address of the callee's JITed image from __bpf_call_base
5476 		 *
5477 		 * in such cases, we can lookup the start address of a callee
5478 		 * by using its subprog id, available from the off field of
5479 		 * the call instruction, as an index for this list
5480 		 */
5481 		func[i]->aux->func = func;
5482 		func[i]->aux->func_cnt = env->subprog_cnt;
5483 	}
5484 	for (i = 0; i < env->subprog_cnt; i++) {
5485 		old_bpf_func = func[i]->bpf_func;
5486 		tmp = bpf_int_jit_compile(func[i]);
5487 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
5488 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
5489 			err = -ENOTSUPP;
5490 			goto out_free;
5491 		}
5492 		cond_resched();
5493 	}
5494 
5495 	/* finally lock prog and jit images for all functions and
5496 	 * populate kallsysm
5497 	 */
5498 	for (i = 0; i < env->subprog_cnt; i++) {
5499 		bpf_prog_lock_ro(func[i]);
5500 		bpf_prog_kallsyms_add(func[i]);
5501 	}
5502 
5503 	/* Last step: make now unused interpreter insns from main
5504 	 * prog consistent for later dump requests, so they can
5505 	 * later look the same as if they were interpreted only.
5506 	 */
5507 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5508 		if (insn->code != (BPF_JMP | BPF_CALL) ||
5509 		    insn->src_reg != BPF_PSEUDO_CALL)
5510 			continue;
5511 		insn->off = env->insn_aux_data[i].call_imm;
5512 		subprog = find_subprog(env, i + insn->off + 1);
5513 		insn->imm = subprog;
5514 	}
5515 
5516 	prog->jited = 1;
5517 	prog->bpf_func = func[0]->bpf_func;
5518 	prog->aux->func = func;
5519 	prog->aux->func_cnt = env->subprog_cnt;
5520 	return 0;
5521 out_free:
5522 	for (i = 0; i < env->subprog_cnt; i++)
5523 		if (func[i])
5524 			bpf_jit_free(func[i]);
5525 	kfree(func);
5526 out_undo_insn:
5527 	/* cleanup main prog to be interpreted */
5528 	prog->jit_requested = 0;
5529 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5530 		if (insn->code != (BPF_JMP | BPF_CALL) ||
5531 		    insn->src_reg != BPF_PSEUDO_CALL)
5532 			continue;
5533 		insn->off = 0;
5534 		insn->imm = env->insn_aux_data[i].call_imm;
5535 	}
5536 	return err;
5537 }
5538 
5539 static int fixup_call_args(struct bpf_verifier_env *env)
5540 {
5541 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5542 	struct bpf_prog *prog = env->prog;
5543 	struct bpf_insn *insn = prog->insnsi;
5544 	int i, depth;
5545 #endif
5546 	int err;
5547 
5548 	err = 0;
5549 	if (env->prog->jit_requested) {
5550 		err = jit_subprogs(env);
5551 		if (err == 0)
5552 			return 0;
5553 		if (err == -EFAULT)
5554 			return err;
5555 	}
5556 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5557 	for (i = 0; i < prog->len; i++, insn++) {
5558 		if (insn->code != (BPF_JMP | BPF_CALL) ||
5559 		    insn->src_reg != BPF_PSEUDO_CALL)
5560 			continue;
5561 		depth = get_callee_stack_depth(env, insn, i);
5562 		if (depth < 0)
5563 			return depth;
5564 		bpf_patch_call_args(insn, depth);
5565 	}
5566 	err = 0;
5567 #endif
5568 	return err;
5569 }
5570 
5571 /* fixup insn->imm field of bpf_call instructions
5572  * and inline eligible helpers as explicit sequence of BPF instructions
5573  *
5574  * this function is called after eBPF program passed verification
5575  */
5576 static int fixup_bpf_calls(struct bpf_verifier_env *env)
5577 {
5578 	struct bpf_prog *prog = env->prog;
5579 	struct bpf_insn *insn = prog->insnsi;
5580 	const struct bpf_func_proto *fn;
5581 	const int insn_cnt = prog->len;
5582 	const struct bpf_map_ops *ops;
5583 	struct bpf_insn_aux_data *aux;
5584 	struct bpf_insn insn_buf[16];
5585 	struct bpf_prog *new_prog;
5586 	struct bpf_map *map_ptr;
5587 	int i, cnt, delta = 0;
5588 
5589 	for (i = 0; i < insn_cnt; i++, insn++) {
5590 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
5591 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5592 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
5593 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5594 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
5595 			struct bpf_insn mask_and_div[] = {
5596 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5597 				/* Rx div 0 -> 0 */
5598 				BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
5599 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
5600 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
5601 				*insn,
5602 			};
5603 			struct bpf_insn mask_and_mod[] = {
5604 				BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5605 				/* Rx mod 0 -> Rx */
5606 				BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
5607 				*insn,
5608 			};
5609 			struct bpf_insn *patchlet;
5610 
5611 			if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5612 			    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5613 				patchlet = mask_and_div + (is64 ? 1 : 0);
5614 				cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
5615 			} else {
5616 				patchlet = mask_and_mod + (is64 ? 1 : 0);
5617 				cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
5618 			}
5619 
5620 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
5621 			if (!new_prog)
5622 				return -ENOMEM;
5623 
5624 			delta    += cnt - 1;
5625 			env->prog = prog = new_prog;
5626 			insn      = new_prog->insnsi + i + delta;
5627 			continue;
5628 		}
5629 
5630 		if (BPF_CLASS(insn->code) == BPF_LD &&
5631 		    (BPF_MODE(insn->code) == BPF_ABS ||
5632 		     BPF_MODE(insn->code) == BPF_IND)) {
5633 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
5634 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5635 				verbose(env, "bpf verifier is misconfigured\n");
5636 				return -EINVAL;
5637 			}
5638 
5639 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5640 			if (!new_prog)
5641 				return -ENOMEM;
5642 
5643 			delta    += cnt - 1;
5644 			env->prog = prog = new_prog;
5645 			insn      = new_prog->insnsi + i + delta;
5646 			continue;
5647 		}
5648 
5649 		if (insn->code != (BPF_JMP | BPF_CALL))
5650 			continue;
5651 		if (insn->src_reg == BPF_PSEUDO_CALL)
5652 			continue;
5653 
5654 		if (insn->imm == BPF_FUNC_get_route_realm)
5655 			prog->dst_needed = 1;
5656 		if (insn->imm == BPF_FUNC_get_prandom_u32)
5657 			bpf_user_rnd_init_once();
5658 		if (insn->imm == BPF_FUNC_override_return)
5659 			prog->kprobe_override = 1;
5660 		if (insn->imm == BPF_FUNC_tail_call) {
5661 			/* If we tail call into other programs, we
5662 			 * cannot make any assumptions since they can
5663 			 * be replaced dynamically during runtime in
5664 			 * the program array.
5665 			 */
5666 			prog->cb_access = 1;
5667 			env->prog->aux->stack_depth = MAX_BPF_STACK;
5668 
5669 			/* mark bpf_tail_call as different opcode to avoid
5670 			 * conditional branch in the interpeter for every normal
5671 			 * call and to prevent accidental JITing by JIT compiler
5672 			 * that doesn't support bpf_tail_call yet
5673 			 */
5674 			insn->imm = 0;
5675 			insn->code = BPF_JMP | BPF_TAIL_CALL;
5676 
5677 			aux = &env->insn_aux_data[i + delta];
5678 			if (!bpf_map_ptr_unpriv(aux))
5679 				continue;
5680 
5681 			/* instead of changing every JIT dealing with tail_call
5682 			 * emit two extra insns:
5683 			 * if (index >= max_entries) goto out;
5684 			 * index &= array->index_mask;
5685 			 * to avoid out-of-bounds cpu speculation
5686 			 */
5687 			if (bpf_map_ptr_poisoned(aux)) {
5688 				verbose(env, "tail_call abusing map_ptr\n");
5689 				return -EINVAL;
5690 			}
5691 
5692 			map_ptr = BPF_MAP_PTR(aux->map_state);
5693 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
5694 						  map_ptr->max_entries, 2);
5695 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
5696 						    container_of(map_ptr,
5697 								 struct bpf_array,
5698 								 map)->index_mask);
5699 			insn_buf[2] = *insn;
5700 			cnt = 3;
5701 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5702 			if (!new_prog)
5703 				return -ENOMEM;
5704 
5705 			delta    += cnt - 1;
5706 			env->prog = prog = new_prog;
5707 			insn      = new_prog->insnsi + i + delta;
5708 			continue;
5709 		}
5710 
5711 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
5712 		 * and other inlining handlers are currently limited to 64 bit
5713 		 * only.
5714 		 */
5715 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
5716 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
5717 		     insn->imm == BPF_FUNC_map_update_elem ||
5718 		     insn->imm == BPF_FUNC_map_delete_elem)) {
5719 			aux = &env->insn_aux_data[i + delta];
5720 			if (bpf_map_ptr_poisoned(aux))
5721 				goto patch_call_imm;
5722 
5723 			map_ptr = BPF_MAP_PTR(aux->map_state);
5724 			ops = map_ptr->ops;
5725 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
5726 			    ops->map_gen_lookup) {
5727 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
5728 				if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5729 					verbose(env, "bpf verifier is misconfigured\n");
5730 					return -EINVAL;
5731 				}
5732 
5733 				new_prog = bpf_patch_insn_data(env, i + delta,
5734 							       insn_buf, cnt);
5735 				if (!new_prog)
5736 					return -ENOMEM;
5737 
5738 				delta    += cnt - 1;
5739 				env->prog = prog = new_prog;
5740 				insn      = new_prog->insnsi + i + delta;
5741 				continue;
5742 			}
5743 
5744 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
5745 				     (void *(*)(struct bpf_map *map, void *key))NULL));
5746 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
5747 				     (int (*)(struct bpf_map *map, void *key))NULL));
5748 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
5749 				     (int (*)(struct bpf_map *map, void *key, void *value,
5750 					      u64 flags))NULL));
5751 			switch (insn->imm) {
5752 			case BPF_FUNC_map_lookup_elem:
5753 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
5754 					    __bpf_call_base;
5755 				continue;
5756 			case BPF_FUNC_map_update_elem:
5757 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
5758 					    __bpf_call_base;
5759 				continue;
5760 			case BPF_FUNC_map_delete_elem:
5761 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
5762 					    __bpf_call_base;
5763 				continue;
5764 			}
5765 
5766 			goto patch_call_imm;
5767 		}
5768 
5769 patch_call_imm:
5770 		fn = env->ops->get_func_proto(insn->imm, env->prog);
5771 		/* all functions that have prototype and verifier allowed
5772 		 * programs to call them, must be real in-kernel functions
5773 		 */
5774 		if (!fn->func) {
5775 			verbose(env,
5776 				"kernel subsystem misconfigured func %s#%d\n",
5777 				func_id_name(insn->imm), insn->imm);
5778 			return -EFAULT;
5779 		}
5780 		insn->imm = fn->func - __bpf_call_base;
5781 	}
5782 
5783 	return 0;
5784 }
5785 
5786 static void free_states(struct bpf_verifier_env *env)
5787 {
5788 	struct bpf_verifier_state_list *sl, *sln;
5789 	int i;
5790 
5791 	if (!env->explored_states)
5792 		return;
5793 
5794 	for (i = 0; i < env->prog->len; i++) {
5795 		sl = env->explored_states[i];
5796 
5797 		if (sl)
5798 			while (sl != STATE_LIST_MARK) {
5799 				sln = sl->next;
5800 				free_verifier_state(&sl->state, false);
5801 				kfree(sl);
5802 				sl = sln;
5803 			}
5804 	}
5805 
5806 	kfree(env->explored_states);
5807 }
5808 
5809 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5810 {
5811 	struct bpf_verifier_env *env;
5812 	struct bpf_verifier_log *log;
5813 	int ret = -EINVAL;
5814 
5815 	/* no program is valid */
5816 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
5817 		return -EINVAL;
5818 
5819 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
5820 	 * allocate/free it every time bpf_check() is called
5821 	 */
5822 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5823 	if (!env)
5824 		return -ENOMEM;
5825 	log = &env->log;
5826 
5827 	env->insn_aux_data =
5828 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
5829 				   (*prog)->len));
5830 	ret = -ENOMEM;
5831 	if (!env->insn_aux_data)
5832 		goto err_free_env;
5833 	env->prog = *prog;
5834 	env->ops = bpf_verifier_ops[env->prog->type];
5835 
5836 	/* grab the mutex to protect few globals used by verifier */
5837 	mutex_lock(&bpf_verifier_lock);
5838 
5839 	if (attr->log_level || attr->log_buf || attr->log_size) {
5840 		/* user requested verbose verifier output
5841 		 * and supplied buffer to store the verification trace
5842 		 */
5843 		log->level = attr->log_level;
5844 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
5845 		log->len_total = attr->log_size;
5846 
5847 		ret = -EINVAL;
5848 		/* log attributes have to be sane */
5849 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
5850 		    !log->level || !log->ubuf)
5851 			goto err_unlock;
5852 	}
5853 
5854 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5855 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5856 		env->strict_alignment = true;
5857 
5858 	ret = replace_map_fd_with_map_ptr(env);
5859 	if (ret < 0)
5860 		goto skip_full_check;
5861 
5862 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
5863 		ret = bpf_prog_offload_verifier_prep(env);
5864 		if (ret)
5865 			goto skip_full_check;
5866 	}
5867 
5868 	env->explored_states = kcalloc(env->prog->len,
5869 				       sizeof(struct bpf_verifier_state_list *),
5870 				       GFP_USER);
5871 	ret = -ENOMEM;
5872 	if (!env->explored_states)
5873 		goto skip_full_check;
5874 
5875 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5876 
5877 	ret = check_cfg(env);
5878 	if (ret < 0)
5879 		goto skip_full_check;
5880 
5881 	ret = do_check(env);
5882 	if (env->cur_state) {
5883 		free_verifier_state(env->cur_state, true);
5884 		env->cur_state = NULL;
5885 	}
5886 
5887 skip_full_check:
5888 	while (!pop_stack(env, NULL, NULL));
5889 	free_states(env);
5890 
5891 	if (ret == 0)
5892 		sanitize_dead_code(env);
5893 
5894 	if (ret == 0)
5895 		ret = check_max_stack_depth(env);
5896 
5897 	if (ret == 0)
5898 		/* program is valid, convert *(u32*)(ctx + off) accesses */
5899 		ret = convert_ctx_accesses(env);
5900 
5901 	if (ret == 0)
5902 		ret = fixup_bpf_calls(env);
5903 
5904 	if (ret == 0)
5905 		ret = fixup_call_args(env);
5906 
5907 	if (log->level && bpf_verifier_log_full(log))
5908 		ret = -ENOSPC;
5909 	if (log->level && !log->ubuf) {
5910 		ret = -EFAULT;
5911 		goto err_release_maps;
5912 	}
5913 
5914 	if (ret == 0 && env->used_map_cnt) {
5915 		/* if program passed verifier, update used_maps in bpf_prog_info */
5916 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5917 							  sizeof(env->used_maps[0]),
5918 							  GFP_KERNEL);
5919 
5920 		if (!env->prog->aux->used_maps) {
5921 			ret = -ENOMEM;
5922 			goto err_release_maps;
5923 		}
5924 
5925 		memcpy(env->prog->aux->used_maps, env->used_maps,
5926 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
5927 		env->prog->aux->used_map_cnt = env->used_map_cnt;
5928 
5929 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
5930 		 * bpf_ld_imm64 instructions
5931 		 */
5932 		convert_pseudo_ld_imm64(env);
5933 	}
5934 
5935 err_release_maps:
5936 	if (!env->prog->aux->used_maps)
5937 		/* if we didn't copy map pointers into bpf_prog_info, release
5938 		 * them now. Otherwise free_used_maps() will release them.
5939 		 */
5940 		release_maps(env);
5941 	*prog = env->prog;
5942 err_unlock:
5943 	mutex_unlock(&bpf_verifier_lock);
5944 	vfree(env->insn_aux_data);
5945 err_free_env:
5946 	kfree(env);
5947 	return ret;
5948 }
5949