xref: /linux/kernel/bpf/verifier.c (revision 7181e5590e5ba898804aef3ee6be7f27606e6f8b)
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 
23 /* bpf_check() is a static code analyzer that walks eBPF program
24  * instruction by instruction and updates register/stack state.
25  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
26  *
27  * The first pass is depth-first-search to check that the program is a DAG.
28  * It rejects the following programs:
29  * - larger than BPF_MAXINSNS insns
30  * - if loop is present (detected via back-edge)
31  * - unreachable insns exist (shouldn't be a forest. program = one function)
32  * - out of bounds or malformed jumps
33  * The second pass is all possible path descent from the 1st insn.
34  * Since it's analyzing all pathes through the program, the length of the
35  * analysis is limited to 32k insn, which may be hit even if total number of
36  * insn is less then 4K, but there are too many branches that change stack/regs.
37  * Number of 'branches to be analyzed' is limited to 1k
38  *
39  * On entry to each instruction, each register has a type, and the instruction
40  * changes the types of the registers depending on instruction semantics.
41  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
42  * copied to R1.
43  *
44  * All registers are 64-bit.
45  * R0 - return register
46  * R1-R5 argument passing registers
47  * R6-R9 callee saved registers
48  * R10 - frame pointer read-only
49  *
50  * At the start of BPF program the register R1 contains a pointer to bpf_context
51  * and has type PTR_TO_CTX.
52  *
53  * Verifier tracks arithmetic operations on pointers in case:
54  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
55  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
56  * 1st insn copies R10 (which has FRAME_PTR) type into R1
57  * and 2nd arithmetic instruction is pattern matched to recognize
58  * that it wants to construct a pointer to some element within stack.
59  * So after 2nd insn, the register R1 has type PTR_TO_STACK
60  * (and -20 constant is saved for further stack bounds checking).
61  * Meaning that this reg is a pointer to stack plus known immediate constant.
62  *
63  * Most of the time the registers have UNKNOWN_VALUE type, which
64  * means the register has some value, but it's not a valid pointer.
65  * (like pointer plus pointer becomes UNKNOWN_VALUE type)
66  *
67  * When verifier sees load or store instructions the type of base register
68  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
69  * types recognized by check_mem_access() function.
70  *
71  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
72  * and the range of [ptr, ptr + map's value_size) is accessible.
73  *
74  * registers used to pass values to function calls are checked against
75  * function argument constraints.
76  *
77  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
78  * It means that the register type passed to this function must be
79  * PTR_TO_STACK and it will be used inside the function as
80  * 'pointer to map element key'
81  *
82  * For example the argument constraints for bpf_map_lookup_elem():
83  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
84  *   .arg1_type = ARG_CONST_MAP_PTR,
85  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
86  *
87  * ret_type says that this function returns 'pointer to map elem value or null'
88  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
89  * 2nd argument should be a pointer to stack, which will be used inside
90  * the helper function as a pointer to map element key.
91  *
92  * On the kernel side the helper function looks like:
93  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
94  * {
95  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
96  *    void *key = (void *) (unsigned long) r2;
97  *    void *value;
98  *
99  *    here kernel can access 'key' and 'map' pointers safely, knowing that
100  *    [key, key + map->key_size) bytes are valid and were initialized on
101  *    the stack of eBPF program.
102  * }
103  *
104  * Corresponding eBPF program may look like:
105  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
106  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
107  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
108  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
109  * here verifier looks at prototype of map_lookup_elem() and sees:
110  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
111  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
112  *
113  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
114  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
115  * and were initialized prior to this call.
116  * If it's ok, then verifier allows this BPF_CALL insn and looks at
117  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
118  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
119  * returns ether pointer to map value or NULL.
120  *
121  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
122  * insn, the register holding that pointer in the true branch changes state to
123  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
124  * branch. See check_cond_jmp_op().
125  *
126  * After the call R0 is set to return type of the function and registers R1-R5
127  * are set to NOT_INIT to indicate that they are no longer readable.
128  */
129 
130 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
131 struct bpf_verifier_stack_elem {
132 	/* verifer state is 'st'
133 	 * before processing instruction 'insn_idx'
134 	 * and after processing instruction 'prev_insn_idx'
135 	 */
136 	struct bpf_verifier_state st;
137 	int insn_idx;
138 	int prev_insn_idx;
139 	struct bpf_verifier_stack_elem *next;
140 };
141 
142 #define BPF_COMPLEXITY_LIMIT_INSNS	65536
143 #define BPF_COMPLEXITY_LIMIT_STACK	1024
144 
145 struct bpf_call_arg_meta {
146 	struct bpf_map *map_ptr;
147 	bool raw_mode;
148 	bool pkt_access;
149 	int regno;
150 	int access_size;
151 };
152 
153 /* verbose verifier prints what it's seeing
154  * bpf_check() is called under lock, so no race to access these global vars
155  */
156 static u32 log_level, log_size, log_len;
157 static char *log_buf;
158 
159 static DEFINE_MUTEX(bpf_verifier_lock);
160 
161 /* log_level controls verbosity level of eBPF verifier.
162  * verbose() is used to dump the verification trace to the log, so the user
163  * can figure out what's wrong with the program
164  */
165 static __printf(1, 2) void verbose(const char *fmt, ...)
166 {
167 	va_list args;
168 
169 	if (log_level == 0 || log_len >= log_size - 1)
170 		return;
171 
172 	va_start(args, fmt);
173 	log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
174 	va_end(args);
175 }
176 
177 /* string representation of 'enum bpf_reg_type' */
178 static const char * const reg_type_str[] = {
179 	[NOT_INIT]		= "?",
180 	[UNKNOWN_VALUE]		= "inv",
181 	[PTR_TO_CTX]		= "ctx",
182 	[CONST_PTR_TO_MAP]	= "map_ptr",
183 	[PTR_TO_MAP_VALUE]	= "map_value",
184 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
185 	[PTR_TO_MAP_VALUE_ADJ]	= "map_value_adj",
186 	[FRAME_PTR]		= "fp",
187 	[PTR_TO_STACK]		= "fp",
188 	[CONST_IMM]		= "imm",
189 	[PTR_TO_PACKET]		= "pkt",
190 	[PTR_TO_PACKET_END]	= "pkt_end",
191 };
192 
193 static void print_verifier_state(struct bpf_verifier_state *state)
194 {
195 	struct bpf_reg_state *reg;
196 	enum bpf_reg_type t;
197 	int i;
198 
199 	for (i = 0; i < MAX_BPF_REG; i++) {
200 		reg = &state->regs[i];
201 		t = reg->type;
202 		if (t == NOT_INIT)
203 			continue;
204 		verbose(" R%d=%s", i, reg_type_str[t]);
205 		if (t == CONST_IMM || t == PTR_TO_STACK)
206 			verbose("%lld", reg->imm);
207 		else if (t == PTR_TO_PACKET)
208 			verbose("(id=%d,off=%d,r=%d)",
209 				reg->id, reg->off, reg->range);
210 		else if (t == UNKNOWN_VALUE && reg->imm)
211 			verbose("%lld", reg->imm);
212 		else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
213 			 t == PTR_TO_MAP_VALUE_OR_NULL ||
214 			 t == PTR_TO_MAP_VALUE_ADJ)
215 			verbose("(ks=%d,vs=%d)",
216 				reg->map_ptr->key_size,
217 				reg->map_ptr->value_size);
218 		if (reg->min_value != BPF_REGISTER_MIN_RANGE)
219 			verbose(",min_value=%llu",
220 				(unsigned long long)reg->min_value);
221 		if (reg->max_value != BPF_REGISTER_MAX_RANGE)
222 			verbose(",max_value=%llu",
223 				(unsigned long long)reg->max_value);
224 	}
225 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
226 		if (state->stack_slot_type[i] == STACK_SPILL)
227 			verbose(" fp%d=%s", -MAX_BPF_STACK + i,
228 				reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
229 	}
230 	verbose("\n");
231 }
232 
233 static const char *const bpf_class_string[] = {
234 	[BPF_LD]    = "ld",
235 	[BPF_LDX]   = "ldx",
236 	[BPF_ST]    = "st",
237 	[BPF_STX]   = "stx",
238 	[BPF_ALU]   = "alu",
239 	[BPF_JMP]   = "jmp",
240 	[BPF_RET]   = "BUG",
241 	[BPF_ALU64] = "alu64",
242 };
243 
244 static const char *const bpf_alu_string[16] = {
245 	[BPF_ADD >> 4]  = "+=",
246 	[BPF_SUB >> 4]  = "-=",
247 	[BPF_MUL >> 4]  = "*=",
248 	[BPF_DIV >> 4]  = "/=",
249 	[BPF_OR  >> 4]  = "|=",
250 	[BPF_AND >> 4]  = "&=",
251 	[BPF_LSH >> 4]  = "<<=",
252 	[BPF_RSH >> 4]  = ">>=",
253 	[BPF_NEG >> 4]  = "neg",
254 	[BPF_MOD >> 4]  = "%=",
255 	[BPF_XOR >> 4]  = "^=",
256 	[BPF_MOV >> 4]  = "=",
257 	[BPF_ARSH >> 4] = "s>>=",
258 	[BPF_END >> 4]  = "endian",
259 };
260 
261 static const char *const bpf_ldst_string[] = {
262 	[BPF_W >> 3]  = "u32",
263 	[BPF_H >> 3]  = "u16",
264 	[BPF_B >> 3]  = "u8",
265 	[BPF_DW >> 3] = "u64",
266 };
267 
268 static const char *const bpf_jmp_string[16] = {
269 	[BPF_JA >> 4]   = "jmp",
270 	[BPF_JEQ >> 4]  = "==",
271 	[BPF_JGT >> 4]  = ">",
272 	[BPF_JGE >> 4]  = ">=",
273 	[BPF_JSET >> 4] = "&",
274 	[BPF_JNE >> 4]  = "!=",
275 	[BPF_JSGT >> 4] = "s>",
276 	[BPF_JSGE >> 4] = "s>=",
277 	[BPF_CALL >> 4] = "call",
278 	[BPF_EXIT >> 4] = "exit",
279 };
280 
281 static void print_bpf_insn(struct bpf_insn *insn)
282 {
283 	u8 class = BPF_CLASS(insn->code);
284 
285 	if (class == BPF_ALU || class == BPF_ALU64) {
286 		if (BPF_SRC(insn->code) == BPF_X)
287 			verbose("(%02x) %sr%d %s %sr%d\n",
288 				insn->code, class == BPF_ALU ? "(u32) " : "",
289 				insn->dst_reg,
290 				bpf_alu_string[BPF_OP(insn->code) >> 4],
291 				class == BPF_ALU ? "(u32) " : "",
292 				insn->src_reg);
293 		else
294 			verbose("(%02x) %sr%d %s %s%d\n",
295 				insn->code, class == BPF_ALU ? "(u32) " : "",
296 				insn->dst_reg,
297 				bpf_alu_string[BPF_OP(insn->code) >> 4],
298 				class == BPF_ALU ? "(u32) " : "",
299 				insn->imm);
300 	} else if (class == BPF_STX) {
301 		if (BPF_MODE(insn->code) == BPF_MEM)
302 			verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
303 				insn->code,
304 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
305 				insn->dst_reg,
306 				insn->off, insn->src_reg);
307 		else if (BPF_MODE(insn->code) == BPF_XADD)
308 			verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
309 				insn->code,
310 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
311 				insn->dst_reg, insn->off,
312 				insn->src_reg);
313 		else
314 			verbose("BUG_%02x\n", insn->code);
315 	} else if (class == BPF_ST) {
316 		if (BPF_MODE(insn->code) != BPF_MEM) {
317 			verbose("BUG_st_%02x\n", insn->code);
318 			return;
319 		}
320 		verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
321 			insn->code,
322 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
323 			insn->dst_reg,
324 			insn->off, insn->imm);
325 	} else if (class == BPF_LDX) {
326 		if (BPF_MODE(insn->code) != BPF_MEM) {
327 			verbose("BUG_ldx_%02x\n", insn->code);
328 			return;
329 		}
330 		verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
331 			insn->code, insn->dst_reg,
332 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
333 			insn->src_reg, insn->off);
334 	} else if (class == BPF_LD) {
335 		if (BPF_MODE(insn->code) == BPF_ABS) {
336 			verbose("(%02x) r0 = *(%s *)skb[%d]\n",
337 				insn->code,
338 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
339 				insn->imm);
340 		} else if (BPF_MODE(insn->code) == BPF_IND) {
341 			verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
342 				insn->code,
343 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
344 				insn->src_reg, insn->imm);
345 		} else if (BPF_MODE(insn->code) == BPF_IMM) {
346 			verbose("(%02x) r%d = 0x%x\n",
347 				insn->code, insn->dst_reg, insn->imm);
348 		} else {
349 			verbose("BUG_ld_%02x\n", insn->code);
350 			return;
351 		}
352 	} else if (class == BPF_JMP) {
353 		u8 opcode = BPF_OP(insn->code);
354 
355 		if (opcode == BPF_CALL) {
356 			verbose("(%02x) call %d\n", insn->code, insn->imm);
357 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
358 			verbose("(%02x) goto pc%+d\n",
359 				insn->code, insn->off);
360 		} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
361 			verbose("(%02x) exit\n", insn->code);
362 		} else if (BPF_SRC(insn->code) == BPF_X) {
363 			verbose("(%02x) if r%d %s r%d goto pc%+d\n",
364 				insn->code, insn->dst_reg,
365 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
366 				insn->src_reg, insn->off);
367 		} else {
368 			verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
369 				insn->code, insn->dst_reg,
370 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
371 				insn->imm, insn->off);
372 		}
373 	} else {
374 		verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
375 	}
376 }
377 
378 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
379 {
380 	struct bpf_verifier_stack_elem *elem;
381 	int insn_idx;
382 
383 	if (env->head == NULL)
384 		return -1;
385 
386 	memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
387 	insn_idx = env->head->insn_idx;
388 	if (prev_insn_idx)
389 		*prev_insn_idx = env->head->prev_insn_idx;
390 	elem = env->head->next;
391 	kfree(env->head);
392 	env->head = elem;
393 	env->stack_size--;
394 	return insn_idx;
395 }
396 
397 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
398 					     int insn_idx, int prev_insn_idx)
399 {
400 	struct bpf_verifier_stack_elem *elem;
401 
402 	elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
403 	if (!elem)
404 		goto err;
405 
406 	memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
407 	elem->insn_idx = insn_idx;
408 	elem->prev_insn_idx = prev_insn_idx;
409 	elem->next = env->head;
410 	env->head = elem;
411 	env->stack_size++;
412 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
413 		verbose("BPF program is too complex\n");
414 		goto err;
415 	}
416 	return &elem->st;
417 err:
418 	/* pop all elements and return */
419 	while (pop_stack(env, NULL) >= 0);
420 	return NULL;
421 }
422 
423 #define CALLER_SAVED_REGS 6
424 static const int caller_saved[CALLER_SAVED_REGS] = {
425 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
426 };
427 
428 static void init_reg_state(struct bpf_reg_state *regs)
429 {
430 	int i;
431 
432 	for (i = 0; i < MAX_BPF_REG; i++) {
433 		regs[i].type = NOT_INIT;
434 		regs[i].imm = 0;
435 		regs[i].min_value = BPF_REGISTER_MIN_RANGE;
436 		regs[i].max_value = BPF_REGISTER_MAX_RANGE;
437 	}
438 
439 	/* frame pointer */
440 	regs[BPF_REG_FP].type = FRAME_PTR;
441 
442 	/* 1st arg to a function */
443 	regs[BPF_REG_1].type = PTR_TO_CTX;
444 }
445 
446 static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
447 {
448 	BUG_ON(regno >= MAX_BPF_REG);
449 	regs[regno].type = UNKNOWN_VALUE;
450 	regs[regno].imm = 0;
451 }
452 
453 static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
454 {
455 	regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
456 	regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
457 }
458 
459 enum reg_arg_type {
460 	SRC_OP,		/* register is used as source operand */
461 	DST_OP,		/* register is used as destination operand */
462 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
463 };
464 
465 static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
466 			 enum reg_arg_type t)
467 {
468 	if (regno >= MAX_BPF_REG) {
469 		verbose("R%d is invalid\n", regno);
470 		return -EINVAL;
471 	}
472 
473 	if (t == SRC_OP) {
474 		/* check whether register used as source operand can be read */
475 		if (regs[regno].type == NOT_INIT) {
476 			verbose("R%d !read_ok\n", regno);
477 			return -EACCES;
478 		}
479 	} else {
480 		/* check whether register used as dest operand can be written to */
481 		if (regno == BPF_REG_FP) {
482 			verbose("frame pointer is read only\n");
483 			return -EACCES;
484 		}
485 		if (t == DST_OP)
486 			mark_reg_unknown_value(regs, regno);
487 	}
488 	return 0;
489 }
490 
491 static int bpf_size_to_bytes(int bpf_size)
492 {
493 	if (bpf_size == BPF_W)
494 		return 4;
495 	else if (bpf_size == BPF_H)
496 		return 2;
497 	else if (bpf_size == BPF_B)
498 		return 1;
499 	else if (bpf_size == BPF_DW)
500 		return 8;
501 	else
502 		return -EINVAL;
503 }
504 
505 static bool is_spillable_regtype(enum bpf_reg_type type)
506 {
507 	switch (type) {
508 	case PTR_TO_MAP_VALUE:
509 	case PTR_TO_MAP_VALUE_OR_NULL:
510 	case PTR_TO_STACK:
511 	case PTR_TO_CTX:
512 	case PTR_TO_PACKET:
513 	case PTR_TO_PACKET_END:
514 	case FRAME_PTR:
515 	case CONST_PTR_TO_MAP:
516 		return true;
517 	default:
518 		return false;
519 	}
520 }
521 
522 /* check_stack_read/write functions track spill/fill of registers,
523  * stack boundary and alignment are checked in check_mem_access()
524  */
525 static int check_stack_write(struct bpf_verifier_state *state, int off,
526 			     int size, int value_regno)
527 {
528 	int i;
529 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
530 	 * so it's aligned access and [off, off + size) are within stack limits
531 	 */
532 
533 	if (value_regno >= 0 &&
534 	    is_spillable_regtype(state->regs[value_regno].type)) {
535 
536 		/* register containing pointer is being spilled into stack */
537 		if (size != BPF_REG_SIZE) {
538 			verbose("invalid size of register spill\n");
539 			return -EACCES;
540 		}
541 
542 		/* save register state */
543 		state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
544 			state->regs[value_regno];
545 
546 		for (i = 0; i < BPF_REG_SIZE; i++)
547 			state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
548 	} else {
549 		/* regular write of data into stack */
550 		state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
551 			(struct bpf_reg_state) {};
552 
553 		for (i = 0; i < size; i++)
554 			state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
555 	}
556 	return 0;
557 }
558 
559 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
560 			    int value_regno)
561 {
562 	u8 *slot_type;
563 	int i;
564 
565 	slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
566 
567 	if (slot_type[0] == STACK_SPILL) {
568 		if (size != BPF_REG_SIZE) {
569 			verbose("invalid size of register spill\n");
570 			return -EACCES;
571 		}
572 		for (i = 1; i < BPF_REG_SIZE; i++) {
573 			if (slot_type[i] != STACK_SPILL) {
574 				verbose("corrupted spill memory\n");
575 				return -EACCES;
576 			}
577 		}
578 
579 		if (value_regno >= 0)
580 			/* restore register state from stack */
581 			state->regs[value_regno] =
582 				state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
583 		return 0;
584 	} else {
585 		for (i = 0; i < size; i++) {
586 			if (slot_type[i] != STACK_MISC) {
587 				verbose("invalid read from stack off %d+%d size %d\n",
588 					off, i, size);
589 				return -EACCES;
590 			}
591 		}
592 		if (value_regno >= 0)
593 			/* have read misc data from the stack */
594 			mark_reg_unknown_value(state->regs, value_regno);
595 		return 0;
596 	}
597 }
598 
599 /* check read/write into map element returned by bpf_map_lookup_elem() */
600 static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
601 			    int size)
602 {
603 	struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
604 
605 	if (off < 0 || off + size > map->value_size) {
606 		verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
607 			map->value_size, off, size);
608 		return -EACCES;
609 	}
610 	return 0;
611 }
612 
613 #define MAX_PACKET_OFF 0xffff
614 
615 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
616 				       const struct bpf_call_arg_meta *meta)
617 {
618 	switch (env->prog->type) {
619 	case BPF_PROG_TYPE_SCHED_CLS:
620 	case BPF_PROG_TYPE_SCHED_ACT:
621 	case BPF_PROG_TYPE_XDP:
622 		if (meta)
623 			return meta->pkt_access;
624 
625 		env->seen_direct_write = true;
626 		return true;
627 	default:
628 		return false;
629 	}
630 }
631 
632 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
633 			       int size)
634 {
635 	struct bpf_reg_state *regs = env->cur_state.regs;
636 	struct bpf_reg_state *reg = &regs[regno];
637 
638 	off += reg->off;
639 	if (off < 0 || size <= 0 || off + size > reg->range) {
640 		verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
641 			off, size, regno, reg->id, reg->off, reg->range);
642 		return -EACCES;
643 	}
644 	return 0;
645 }
646 
647 /* check access to 'struct bpf_context' fields */
648 static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
649 			    enum bpf_access_type t, enum bpf_reg_type *reg_type)
650 {
651 	/* for analyzer ctx accesses are already validated and converted */
652 	if (env->analyzer_ops)
653 		return 0;
654 
655 	if (env->prog->aux->ops->is_valid_access &&
656 	    env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
657 		/* remember the offset of last byte accessed in ctx */
658 		if (env->prog->aux->max_ctx_offset < off + size)
659 			env->prog->aux->max_ctx_offset = off + size;
660 		return 0;
661 	}
662 
663 	verbose("invalid bpf_context access off=%d size=%d\n", off, size);
664 	return -EACCES;
665 }
666 
667 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
668 {
669 	if (env->allow_ptr_leaks)
670 		return false;
671 
672 	switch (env->cur_state.regs[regno].type) {
673 	case UNKNOWN_VALUE:
674 	case CONST_IMM:
675 		return false;
676 	default:
677 		return true;
678 	}
679 }
680 
681 static int check_ptr_alignment(struct bpf_verifier_env *env,
682 			       struct bpf_reg_state *reg, int off, int size)
683 {
684 	if (reg->type != PTR_TO_PACKET && reg->type != PTR_TO_MAP_VALUE_ADJ) {
685 		if (off % size != 0) {
686 			verbose("misaligned access off %d size %d\n",
687 				off, size);
688 			return -EACCES;
689 		} else {
690 			return 0;
691 		}
692 	}
693 
694 	if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
695 		/* misaligned access to packet is ok on x86,arm,arm64 */
696 		return 0;
697 
698 	if (reg->id && size != 1) {
699 		verbose("Unknown packet alignment. Only byte-sized access allowed\n");
700 		return -EACCES;
701 	}
702 
703 	/* skb->data is NET_IP_ALIGN-ed */
704 	if (reg->type == PTR_TO_PACKET &&
705 	    (NET_IP_ALIGN + reg->off + off) % size != 0) {
706 		verbose("misaligned packet access off %d+%d+%d size %d\n",
707 			NET_IP_ALIGN, reg->off, off, size);
708 		return -EACCES;
709 	}
710 	return 0;
711 }
712 
713 /* check whether memory at (regno + off) is accessible for t = (read | write)
714  * if t==write, value_regno is a register which value is stored into memory
715  * if t==read, value_regno is a register which will receive the value from memory
716  * if t==write && value_regno==-1, some unknown value is stored into memory
717  * if t==read && value_regno==-1, don't care what we read from memory
718  */
719 static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
720 			    int bpf_size, enum bpf_access_type t,
721 			    int value_regno)
722 {
723 	struct bpf_verifier_state *state = &env->cur_state;
724 	struct bpf_reg_state *reg = &state->regs[regno];
725 	int size, err = 0;
726 
727 	if (reg->type == PTR_TO_STACK)
728 		off += reg->imm;
729 
730 	size = bpf_size_to_bytes(bpf_size);
731 	if (size < 0)
732 		return size;
733 
734 	err = check_ptr_alignment(env, reg, off, size);
735 	if (err)
736 		return err;
737 
738 	if (reg->type == PTR_TO_MAP_VALUE ||
739 	    reg->type == PTR_TO_MAP_VALUE_ADJ) {
740 		if (t == BPF_WRITE && value_regno >= 0 &&
741 		    is_pointer_value(env, value_regno)) {
742 			verbose("R%d leaks addr into map\n", value_regno);
743 			return -EACCES;
744 		}
745 
746 		/* If we adjusted the register to this map value at all then we
747 		 * need to change off and size to min_value and max_value
748 		 * respectively to make sure our theoretical access will be
749 		 * safe.
750 		 */
751 		if (reg->type == PTR_TO_MAP_VALUE_ADJ) {
752 			if (log_level)
753 				print_verifier_state(state);
754 			env->varlen_map_value_access = true;
755 			/* The minimum value is only important with signed
756 			 * comparisons where we can't assume the floor of a
757 			 * value is 0.  If we are using signed variables for our
758 			 * index'es we need to make sure that whatever we use
759 			 * will have a set floor within our range.
760 			 */
761 			if ((s64)reg->min_value < 0) {
762 				verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
763 					regno);
764 				return -EACCES;
765 			}
766 			err = check_map_access(env, regno, reg->min_value + off,
767 					       size);
768 			if (err) {
769 				verbose("R%d min value is outside of the array range\n",
770 					regno);
771 				return err;
772 			}
773 
774 			/* If we haven't set a max value then we need to bail
775 			 * since we can't be sure we won't do bad things.
776 			 */
777 			if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
778 				verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
779 					regno);
780 				return -EACCES;
781 			}
782 			off += reg->max_value;
783 		}
784 		err = check_map_access(env, regno, off, size);
785 		if (!err && t == BPF_READ && value_regno >= 0)
786 			mark_reg_unknown_value(state->regs, value_regno);
787 
788 	} else if (reg->type == PTR_TO_CTX) {
789 		enum bpf_reg_type reg_type = UNKNOWN_VALUE;
790 
791 		if (t == BPF_WRITE && value_regno >= 0 &&
792 		    is_pointer_value(env, value_regno)) {
793 			verbose("R%d leaks addr into ctx\n", value_regno);
794 			return -EACCES;
795 		}
796 		err = check_ctx_access(env, off, size, t, &reg_type);
797 		if (!err && t == BPF_READ && value_regno >= 0) {
798 			mark_reg_unknown_value(state->regs, value_regno);
799 			/* note that reg.[id|off|range] == 0 */
800 			state->regs[value_regno].type = reg_type;
801 		}
802 
803 	} else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
804 		if (off >= 0 || off < -MAX_BPF_STACK) {
805 			verbose("invalid stack off=%d size=%d\n", off, size);
806 			return -EACCES;
807 		}
808 		if (t == BPF_WRITE) {
809 			if (!env->allow_ptr_leaks &&
810 			    state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
811 			    size != BPF_REG_SIZE) {
812 				verbose("attempt to corrupt spilled pointer on stack\n");
813 				return -EACCES;
814 			}
815 			err = check_stack_write(state, off, size, value_regno);
816 		} else {
817 			err = check_stack_read(state, off, size, value_regno);
818 		}
819 	} else if (state->regs[regno].type == PTR_TO_PACKET) {
820 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL)) {
821 			verbose("cannot write into packet\n");
822 			return -EACCES;
823 		}
824 		if (t == BPF_WRITE && value_regno >= 0 &&
825 		    is_pointer_value(env, value_regno)) {
826 			verbose("R%d leaks addr into packet\n", value_regno);
827 			return -EACCES;
828 		}
829 		err = check_packet_access(env, regno, off, size);
830 		if (!err && t == BPF_READ && value_regno >= 0)
831 			mark_reg_unknown_value(state->regs, value_regno);
832 	} else {
833 		verbose("R%d invalid mem access '%s'\n",
834 			regno, reg_type_str[reg->type]);
835 		return -EACCES;
836 	}
837 
838 	if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
839 	    state->regs[value_regno].type == UNKNOWN_VALUE) {
840 		/* 1 or 2 byte load zero-extends, determine the number of
841 		 * zero upper bits. Not doing it fo 4 byte load, since
842 		 * such values cannot be added to ptr_to_packet anyway.
843 		 */
844 		state->regs[value_regno].imm = 64 - size * 8;
845 	}
846 	return err;
847 }
848 
849 static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
850 {
851 	struct bpf_reg_state *regs = env->cur_state.regs;
852 	int err;
853 
854 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
855 	    insn->imm != 0) {
856 		verbose("BPF_XADD uses reserved fields\n");
857 		return -EINVAL;
858 	}
859 
860 	/* check src1 operand */
861 	err = check_reg_arg(regs, insn->src_reg, SRC_OP);
862 	if (err)
863 		return err;
864 
865 	/* check src2 operand */
866 	err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
867 	if (err)
868 		return err;
869 
870 	/* check whether atomic_add can read the memory */
871 	err = check_mem_access(env, insn->dst_reg, insn->off,
872 			       BPF_SIZE(insn->code), BPF_READ, -1);
873 	if (err)
874 		return err;
875 
876 	/* check whether atomic_add can write into the same memory */
877 	return check_mem_access(env, insn->dst_reg, insn->off,
878 				BPF_SIZE(insn->code), BPF_WRITE, -1);
879 }
880 
881 /* when register 'regno' is passed into function that will read 'access_size'
882  * bytes from that pointer, make sure that it's within stack boundary
883  * and all elements of stack are initialized
884  */
885 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
886 				int access_size, bool zero_size_allowed,
887 				struct bpf_call_arg_meta *meta)
888 {
889 	struct bpf_verifier_state *state = &env->cur_state;
890 	struct bpf_reg_state *regs = state->regs;
891 	int off, i;
892 
893 	if (regs[regno].type != PTR_TO_STACK) {
894 		if (zero_size_allowed && access_size == 0 &&
895 		    regs[regno].type == CONST_IMM &&
896 		    regs[regno].imm  == 0)
897 			return 0;
898 
899 		verbose("R%d type=%s expected=%s\n", regno,
900 			reg_type_str[regs[regno].type],
901 			reg_type_str[PTR_TO_STACK]);
902 		return -EACCES;
903 	}
904 
905 	off = regs[regno].imm;
906 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
907 	    access_size <= 0) {
908 		verbose("invalid stack type R%d off=%d access_size=%d\n",
909 			regno, off, access_size);
910 		return -EACCES;
911 	}
912 
913 	if (meta && meta->raw_mode) {
914 		meta->access_size = access_size;
915 		meta->regno = regno;
916 		return 0;
917 	}
918 
919 	for (i = 0; i < access_size; i++) {
920 		if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
921 			verbose("invalid indirect read from stack off %d+%d size %d\n",
922 				off, i, access_size);
923 			return -EACCES;
924 		}
925 	}
926 	return 0;
927 }
928 
929 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
930 			  enum bpf_arg_type arg_type,
931 			  struct bpf_call_arg_meta *meta)
932 {
933 	struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
934 	enum bpf_reg_type expected_type, type = reg->type;
935 	int err = 0;
936 
937 	if (arg_type == ARG_DONTCARE)
938 		return 0;
939 
940 	if (type == NOT_INIT) {
941 		verbose("R%d !read_ok\n", regno);
942 		return -EACCES;
943 	}
944 
945 	if (arg_type == ARG_ANYTHING) {
946 		if (is_pointer_value(env, regno)) {
947 			verbose("R%d leaks addr into helper function\n", regno);
948 			return -EACCES;
949 		}
950 		return 0;
951 	}
952 
953 	if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta)) {
954 		verbose("helper access to the packet is not allowed\n");
955 		return -EACCES;
956 	}
957 
958 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
959 	    arg_type == ARG_PTR_TO_MAP_VALUE) {
960 		expected_type = PTR_TO_STACK;
961 		if (type != PTR_TO_PACKET && type != expected_type)
962 			goto err_type;
963 	} else if (arg_type == ARG_CONST_STACK_SIZE ||
964 		   arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
965 		expected_type = CONST_IMM;
966 		if (type != expected_type)
967 			goto err_type;
968 	} else if (arg_type == ARG_CONST_MAP_PTR) {
969 		expected_type = CONST_PTR_TO_MAP;
970 		if (type != expected_type)
971 			goto err_type;
972 	} else if (arg_type == ARG_PTR_TO_CTX) {
973 		expected_type = PTR_TO_CTX;
974 		if (type != expected_type)
975 			goto err_type;
976 	} else if (arg_type == ARG_PTR_TO_STACK ||
977 		   arg_type == ARG_PTR_TO_RAW_STACK) {
978 		expected_type = PTR_TO_STACK;
979 		/* One exception here. In case function allows for NULL to be
980 		 * passed in as argument, it's a CONST_IMM type. Final test
981 		 * happens during stack boundary checking.
982 		 */
983 		if (type == CONST_IMM && reg->imm == 0)
984 			/* final test in check_stack_boundary() */;
985 		else if (type != PTR_TO_PACKET && type != expected_type)
986 			goto err_type;
987 		meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
988 	} else {
989 		verbose("unsupported arg_type %d\n", arg_type);
990 		return -EFAULT;
991 	}
992 
993 	if (arg_type == ARG_CONST_MAP_PTR) {
994 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
995 		meta->map_ptr = reg->map_ptr;
996 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
997 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
998 		 * check that [key, key + map->key_size) are within
999 		 * stack limits and initialized
1000 		 */
1001 		if (!meta->map_ptr) {
1002 			/* in function declaration map_ptr must come before
1003 			 * map_key, so that it's verified and known before
1004 			 * we have to check map_key here. Otherwise it means
1005 			 * that kernel subsystem misconfigured verifier
1006 			 */
1007 			verbose("invalid map_ptr to access map->key\n");
1008 			return -EACCES;
1009 		}
1010 		if (type == PTR_TO_PACKET)
1011 			err = check_packet_access(env, regno, 0,
1012 						  meta->map_ptr->key_size);
1013 		else
1014 			err = check_stack_boundary(env, regno,
1015 						   meta->map_ptr->key_size,
1016 						   false, NULL);
1017 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1018 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
1019 		 * check [value, value + map->value_size) validity
1020 		 */
1021 		if (!meta->map_ptr) {
1022 			/* kernel subsystem misconfigured verifier */
1023 			verbose("invalid map_ptr to access map->value\n");
1024 			return -EACCES;
1025 		}
1026 		if (type == PTR_TO_PACKET)
1027 			err = check_packet_access(env, regno, 0,
1028 						  meta->map_ptr->value_size);
1029 		else
1030 			err = check_stack_boundary(env, regno,
1031 						   meta->map_ptr->value_size,
1032 						   false, NULL);
1033 	} else if (arg_type == ARG_CONST_STACK_SIZE ||
1034 		   arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
1035 		bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
1036 
1037 		/* bpf_xxx(..., buf, len) call will access 'len' bytes
1038 		 * from stack pointer 'buf'. Check it
1039 		 * note: regno == len, regno - 1 == buf
1040 		 */
1041 		if (regno == 0) {
1042 			/* kernel subsystem misconfigured verifier */
1043 			verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
1044 			return -EACCES;
1045 		}
1046 		if (regs[regno - 1].type == PTR_TO_PACKET)
1047 			err = check_packet_access(env, regno - 1, 0, reg->imm);
1048 		else
1049 			err = check_stack_boundary(env, regno - 1, reg->imm,
1050 						   zero_size_allowed, meta);
1051 	}
1052 
1053 	return err;
1054 err_type:
1055 	verbose("R%d type=%s expected=%s\n", regno,
1056 		reg_type_str[type], reg_type_str[expected_type]);
1057 	return -EACCES;
1058 }
1059 
1060 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1061 {
1062 	if (!map)
1063 		return 0;
1064 
1065 	/* We need a two way check, first is from map perspective ... */
1066 	switch (map->map_type) {
1067 	case BPF_MAP_TYPE_PROG_ARRAY:
1068 		if (func_id != BPF_FUNC_tail_call)
1069 			goto error;
1070 		break;
1071 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1072 		if (func_id != BPF_FUNC_perf_event_read &&
1073 		    func_id != BPF_FUNC_perf_event_output)
1074 			goto error;
1075 		break;
1076 	case BPF_MAP_TYPE_STACK_TRACE:
1077 		if (func_id != BPF_FUNC_get_stackid)
1078 			goto error;
1079 		break;
1080 	case BPF_MAP_TYPE_CGROUP_ARRAY:
1081 		if (func_id != BPF_FUNC_skb_under_cgroup &&
1082 		    func_id != BPF_FUNC_current_task_under_cgroup)
1083 			goto error;
1084 		break;
1085 	default:
1086 		break;
1087 	}
1088 
1089 	/* ... and second from the function itself. */
1090 	switch (func_id) {
1091 	case BPF_FUNC_tail_call:
1092 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1093 			goto error;
1094 		break;
1095 	case BPF_FUNC_perf_event_read:
1096 	case BPF_FUNC_perf_event_output:
1097 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1098 			goto error;
1099 		break;
1100 	case BPF_FUNC_get_stackid:
1101 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1102 			goto error;
1103 		break;
1104 	case BPF_FUNC_current_task_under_cgroup:
1105 	case BPF_FUNC_skb_under_cgroup:
1106 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1107 			goto error;
1108 		break;
1109 	default:
1110 		break;
1111 	}
1112 
1113 	return 0;
1114 error:
1115 	verbose("cannot pass map_type %d into func %d\n",
1116 		map->map_type, func_id);
1117 	return -EINVAL;
1118 }
1119 
1120 static int check_raw_mode(const struct bpf_func_proto *fn)
1121 {
1122 	int count = 0;
1123 
1124 	if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1125 		count++;
1126 	if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1127 		count++;
1128 	if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1129 		count++;
1130 	if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1131 		count++;
1132 	if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1133 		count++;
1134 
1135 	return count > 1 ? -EINVAL : 0;
1136 }
1137 
1138 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1139 {
1140 	struct bpf_verifier_state *state = &env->cur_state;
1141 	struct bpf_reg_state *regs = state->regs, *reg;
1142 	int i;
1143 
1144 	for (i = 0; i < MAX_BPF_REG; i++)
1145 		if (regs[i].type == PTR_TO_PACKET ||
1146 		    regs[i].type == PTR_TO_PACKET_END)
1147 			mark_reg_unknown_value(regs, i);
1148 
1149 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1150 		if (state->stack_slot_type[i] != STACK_SPILL)
1151 			continue;
1152 		reg = &state->spilled_regs[i / BPF_REG_SIZE];
1153 		if (reg->type != PTR_TO_PACKET &&
1154 		    reg->type != PTR_TO_PACKET_END)
1155 			continue;
1156 		reg->type = UNKNOWN_VALUE;
1157 		reg->imm = 0;
1158 	}
1159 }
1160 
1161 static int check_call(struct bpf_verifier_env *env, int func_id)
1162 {
1163 	struct bpf_verifier_state *state = &env->cur_state;
1164 	const struct bpf_func_proto *fn = NULL;
1165 	struct bpf_reg_state *regs = state->regs;
1166 	struct bpf_reg_state *reg;
1167 	struct bpf_call_arg_meta meta;
1168 	bool changes_data;
1169 	int i, err;
1170 
1171 	/* find function prototype */
1172 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1173 		verbose("invalid func %d\n", func_id);
1174 		return -EINVAL;
1175 	}
1176 
1177 	if (env->prog->aux->ops->get_func_proto)
1178 		fn = env->prog->aux->ops->get_func_proto(func_id);
1179 
1180 	if (!fn) {
1181 		verbose("unknown func %d\n", func_id);
1182 		return -EINVAL;
1183 	}
1184 
1185 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
1186 	if (!env->prog->gpl_compatible && fn->gpl_only) {
1187 		verbose("cannot call GPL only function from proprietary program\n");
1188 		return -EINVAL;
1189 	}
1190 
1191 	changes_data = bpf_helper_changes_skb_data(fn->func);
1192 
1193 	memset(&meta, 0, sizeof(meta));
1194 	meta.pkt_access = fn->pkt_access;
1195 
1196 	/* We only support one arg being in raw mode at the moment, which
1197 	 * is sufficient for the helper functions we have right now.
1198 	 */
1199 	err = check_raw_mode(fn);
1200 	if (err) {
1201 		verbose("kernel subsystem misconfigured func %d\n", func_id);
1202 		return err;
1203 	}
1204 
1205 	/* check args */
1206 	err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1207 	if (err)
1208 		return err;
1209 	err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1210 	if (err)
1211 		return err;
1212 	err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1213 	if (err)
1214 		return err;
1215 	err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1216 	if (err)
1217 		return err;
1218 	err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1219 	if (err)
1220 		return err;
1221 
1222 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
1223 	 * is inferred from register state.
1224 	 */
1225 	for (i = 0; i < meta.access_size; i++) {
1226 		err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1227 		if (err)
1228 			return err;
1229 	}
1230 
1231 	/* reset caller saved regs */
1232 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
1233 		reg = regs + caller_saved[i];
1234 		reg->type = NOT_INIT;
1235 		reg->imm = 0;
1236 	}
1237 
1238 	/* update return register */
1239 	if (fn->ret_type == RET_INTEGER) {
1240 		regs[BPF_REG_0].type = UNKNOWN_VALUE;
1241 	} else if (fn->ret_type == RET_VOID) {
1242 		regs[BPF_REG_0].type = NOT_INIT;
1243 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1244 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1245 		regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
1246 		/* remember map_ptr, so that check_map_access()
1247 		 * can check 'value_size' boundary of memory access
1248 		 * to map element returned from bpf_map_lookup_elem()
1249 		 */
1250 		if (meta.map_ptr == NULL) {
1251 			verbose("kernel subsystem misconfigured verifier\n");
1252 			return -EINVAL;
1253 		}
1254 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
1255 	} else {
1256 		verbose("unknown return type %d of func %d\n",
1257 			fn->ret_type, func_id);
1258 		return -EINVAL;
1259 	}
1260 
1261 	err = check_map_func_compatibility(meta.map_ptr, func_id);
1262 	if (err)
1263 		return err;
1264 
1265 	if (changes_data)
1266 		clear_all_pkt_pointers(env);
1267 	return 0;
1268 }
1269 
1270 static int check_packet_ptr_add(struct bpf_verifier_env *env,
1271 				struct bpf_insn *insn)
1272 {
1273 	struct bpf_reg_state *regs = env->cur_state.regs;
1274 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1275 	struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1276 	struct bpf_reg_state tmp_reg;
1277 	s32 imm;
1278 
1279 	if (BPF_SRC(insn->code) == BPF_K) {
1280 		/* pkt_ptr += imm */
1281 		imm = insn->imm;
1282 
1283 add_imm:
1284 		if (imm <= 0) {
1285 			verbose("addition of negative constant to packet pointer is not allowed\n");
1286 			return -EACCES;
1287 		}
1288 		if (imm >= MAX_PACKET_OFF ||
1289 		    imm + dst_reg->off >= MAX_PACKET_OFF) {
1290 			verbose("constant %d is too large to add to packet pointer\n",
1291 				imm);
1292 			return -EACCES;
1293 		}
1294 		/* a constant was added to pkt_ptr.
1295 		 * Remember it while keeping the same 'id'
1296 		 */
1297 		dst_reg->off += imm;
1298 	} else {
1299 		if (src_reg->type == PTR_TO_PACKET) {
1300 			/* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1301 			tmp_reg = *dst_reg;  /* save r7 state */
1302 			*dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1303 			src_reg = &tmp_reg;  /* pretend it's src_reg state */
1304 			/* if the checks below reject it, the copy won't matter,
1305 			 * since we're rejecting the whole program. If all ok,
1306 			 * then imm22 state will be added to r7
1307 			 * and r7 will be pkt(id=0,off=22,r=62) while
1308 			 * r6 will stay as pkt(id=0,off=0,r=62)
1309 			 */
1310 		}
1311 
1312 		if (src_reg->type == CONST_IMM) {
1313 			/* pkt_ptr += reg where reg is known constant */
1314 			imm = src_reg->imm;
1315 			goto add_imm;
1316 		}
1317 		/* disallow pkt_ptr += reg
1318 		 * if reg is not uknown_value with guaranteed zero upper bits
1319 		 * otherwise pkt_ptr may overflow and addition will become
1320 		 * subtraction which is not allowed
1321 		 */
1322 		if (src_reg->type != UNKNOWN_VALUE) {
1323 			verbose("cannot add '%s' to ptr_to_packet\n",
1324 				reg_type_str[src_reg->type]);
1325 			return -EACCES;
1326 		}
1327 		if (src_reg->imm < 48) {
1328 			verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1329 				src_reg->imm);
1330 			return -EACCES;
1331 		}
1332 		/* dst_reg stays as pkt_ptr type and since some positive
1333 		 * integer value was added to the pointer, increment its 'id'
1334 		 */
1335 		dst_reg->id = ++env->id_gen;
1336 
1337 		/* something was added to pkt_ptr, set range and off to zero */
1338 		dst_reg->off = 0;
1339 		dst_reg->range = 0;
1340 	}
1341 	return 0;
1342 }
1343 
1344 static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
1345 {
1346 	struct bpf_reg_state *regs = env->cur_state.regs;
1347 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1348 	u8 opcode = BPF_OP(insn->code);
1349 	s64 imm_log2;
1350 
1351 	/* for type == UNKNOWN_VALUE:
1352 	 * imm > 0 -> number of zero upper bits
1353 	 * imm == 0 -> don't track which is the same as all bits can be non-zero
1354 	 */
1355 
1356 	if (BPF_SRC(insn->code) == BPF_X) {
1357 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1358 
1359 		if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1360 		    dst_reg->imm && opcode == BPF_ADD) {
1361 			/* dreg += sreg
1362 			 * where both have zero upper bits. Adding them
1363 			 * can only result making one more bit non-zero
1364 			 * in the larger value.
1365 			 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1366 			 *     0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1367 			 */
1368 			dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1369 			dst_reg->imm--;
1370 			return 0;
1371 		}
1372 		if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1373 		    dst_reg->imm && opcode == BPF_ADD) {
1374 			/* dreg += sreg
1375 			 * where dreg has zero upper bits and sreg is const.
1376 			 * Adding them can only result making one more bit
1377 			 * non-zero in the larger value.
1378 			 */
1379 			imm_log2 = __ilog2_u64((long long)src_reg->imm);
1380 			dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1381 			dst_reg->imm--;
1382 			return 0;
1383 		}
1384 		/* all other cases non supported yet, just mark dst_reg */
1385 		dst_reg->imm = 0;
1386 		return 0;
1387 	}
1388 
1389 	/* sign extend 32-bit imm into 64-bit to make sure that
1390 	 * negative values occupy bit 63. Note ilog2() would have
1391 	 * been incorrect, since sizeof(insn->imm) == 4
1392 	 */
1393 	imm_log2 = __ilog2_u64((long long)insn->imm);
1394 
1395 	if (dst_reg->imm && opcode == BPF_LSH) {
1396 		/* reg <<= imm
1397 		 * if reg was a result of 2 byte load, then its imm == 48
1398 		 * which means that upper 48 bits are zero and shifting this reg
1399 		 * left by 4 would mean that upper 44 bits are still zero
1400 		 */
1401 		dst_reg->imm -= insn->imm;
1402 	} else if (dst_reg->imm && opcode == BPF_MUL) {
1403 		/* reg *= imm
1404 		 * if multiplying by 14 subtract 4
1405 		 * This is conservative calculation of upper zero bits.
1406 		 * It's not trying to special case insn->imm == 1 or 0 cases
1407 		 */
1408 		dst_reg->imm -= imm_log2 + 1;
1409 	} else if (opcode == BPF_AND) {
1410 		/* reg &= imm */
1411 		dst_reg->imm = 63 - imm_log2;
1412 	} else if (dst_reg->imm && opcode == BPF_ADD) {
1413 		/* reg += imm */
1414 		dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1415 		dst_reg->imm--;
1416 	} else if (opcode == BPF_RSH) {
1417 		/* reg >>= imm
1418 		 * which means that after right shift, upper bits will be zero
1419 		 * note that verifier already checked that
1420 		 * 0 <= imm < 64 for shift insn
1421 		 */
1422 		dst_reg->imm += insn->imm;
1423 		if (unlikely(dst_reg->imm > 64))
1424 			/* some dumb code did:
1425 			 * r2 = *(u32 *)mem;
1426 			 * r2 >>= 32;
1427 			 * and all bits are zero now */
1428 			dst_reg->imm = 64;
1429 	} else {
1430 		/* all other alu ops, means that we don't know what will
1431 		 * happen to the value, mark it with unknown number of zero bits
1432 		 */
1433 		dst_reg->imm = 0;
1434 	}
1435 
1436 	if (dst_reg->imm < 0) {
1437 		/* all 64 bits of the register can contain non-zero bits
1438 		 * and such value cannot be added to ptr_to_packet, since it
1439 		 * may overflow, mark it as unknown to avoid further eval
1440 		 */
1441 		dst_reg->imm = 0;
1442 	}
1443 	return 0;
1444 }
1445 
1446 static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1447 				struct bpf_insn *insn)
1448 {
1449 	struct bpf_reg_state *regs = env->cur_state.regs;
1450 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1451 	struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1452 	u8 opcode = BPF_OP(insn->code);
1453 
1454 	/* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1455 	 * Don't care about overflow or negative values, just add them
1456 	 */
1457 	if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1458 		dst_reg->imm += insn->imm;
1459 	else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1460 		 src_reg->type == CONST_IMM)
1461 		dst_reg->imm += src_reg->imm;
1462 	else
1463 		mark_reg_unknown_value(regs, insn->dst_reg);
1464 	return 0;
1465 }
1466 
1467 static void check_reg_overflow(struct bpf_reg_state *reg)
1468 {
1469 	if (reg->max_value > BPF_REGISTER_MAX_RANGE)
1470 		reg->max_value = BPF_REGISTER_MAX_RANGE;
1471 	if ((s64)reg->min_value < BPF_REGISTER_MIN_RANGE)
1472 		reg->min_value = BPF_REGISTER_MIN_RANGE;
1473 }
1474 
1475 static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
1476 				    struct bpf_insn *insn)
1477 {
1478 	struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1479 	u64 min_val = BPF_REGISTER_MIN_RANGE, max_val = BPF_REGISTER_MAX_RANGE;
1480 	bool min_set = false, max_set = false;
1481 	u8 opcode = BPF_OP(insn->code);
1482 
1483 	dst_reg = &regs[insn->dst_reg];
1484 	if (BPF_SRC(insn->code) == BPF_X) {
1485 		check_reg_overflow(&regs[insn->src_reg]);
1486 		min_val = regs[insn->src_reg].min_value;
1487 		max_val = regs[insn->src_reg].max_value;
1488 
1489 		/* If the source register is a random pointer then the
1490 		 * min_value/max_value values represent the range of the known
1491 		 * accesses into that value, not the actual min/max value of the
1492 		 * register itself.  In this case we have to reset the reg range
1493 		 * values so we know it is not safe to look at.
1494 		 */
1495 		if (regs[insn->src_reg].type != CONST_IMM &&
1496 		    regs[insn->src_reg].type != UNKNOWN_VALUE) {
1497 			min_val = BPF_REGISTER_MIN_RANGE;
1498 			max_val = BPF_REGISTER_MAX_RANGE;
1499 		}
1500 	} else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
1501 		   (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
1502 		min_val = max_val = insn->imm;
1503 		min_set = max_set = true;
1504 	}
1505 
1506 	/* We don't know anything about what was done to this register, mark it
1507 	 * as unknown.
1508 	 */
1509 	if (min_val == BPF_REGISTER_MIN_RANGE &&
1510 	    max_val == BPF_REGISTER_MAX_RANGE) {
1511 		reset_reg_range_values(regs, insn->dst_reg);
1512 		return;
1513 	}
1514 
1515 	switch (opcode) {
1516 	case BPF_ADD:
1517 		dst_reg->min_value += min_val;
1518 		dst_reg->max_value += max_val;
1519 		break;
1520 	case BPF_SUB:
1521 		dst_reg->min_value -= min_val;
1522 		dst_reg->max_value -= max_val;
1523 		break;
1524 	case BPF_MUL:
1525 		dst_reg->min_value *= min_val;
1526 		dst_reg->max_value *= max_val;
1527 		break;
1528 	case BPF_AND:
1529 		/* & is special since it could end up with 0 bits set. */
1530 		dst_reg->min_value &= min_val;
1531 		dst_reg->max_value = max_val;
1532 		break;
1533 	case BPF_LSH:
1534 		/* Gotta have special overflow logic here, if we're shifting
1535 		 * more than MAX_RANGE then just assume we have an invalid
1536 		 * range.
1537 		 */
1538 		if (min_val > ilog2(BPF_REGISTER_MAX_RANGE))
1539 			dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1540 		else
1541 			dst_reg->min_value <<= min_val;
1542 
1543 		if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
1544 			dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1545 		else
1546 			dst_reg->max_value <<= max_val;
1547 		break;
1548 	case BPF_RSH:
1549 		dst_reg->min_value >>= min_val;
1550 		dst_reg->max_value >>= max_val;
1551 		break;
1552 	case BPF_MOD:
1553 		/* % is special since it is an unsigned modulus, so the floor
1554 		 * will always be 0.
1555 		 */
1556 		dst_reg->min_value = 0;
1557 		dst_reg->max_value = max_val - 1;
1558 		break;
1559 	default:
1560 		reset_reg_range_values(regs, insn->dst_reg);
1561 		break;
1562 	}
1563 
1564 	check_reg_overflow(dst_reg);
1565 }
1566 
1567 /* check validity of 32-bit and 64-bit arithmetic operations */
1568 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
1569 {
1570 	struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1571 	u8 opcode = BPF_OP(insn->code);
1572 	int err;
1573 
1574 	if (opcode == BPF_END || opcode == BPF_NEG) {
1575 		if (opcode == BPF_NEG) {
1576 			if (BPF_SRC(insn->code) != 0 ||
1577 			    insn->src_reg != BPF_REG_0 ||
1578 			    insn->off != 0 || insn->imm != 0) {
1579 				verbose("BPF_NEG uses reserved fields\n");
1580 				return -EINVAL;
1581 			}
1582 		} else {
1583 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1584 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1585 				verbose("BPF_END uses reserved fields\n");
1586 				return -EINVAL;
1587 			}
1588 		}
1589 
1590 		/* check src operand */
1591 		err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1592 		if (err)
1593 			return err;
1594 
1595 		if (is_pointer_value(env, insn->dst_reg)) {
1596 			verbose("R%d pointer arithmetic prohibited\n",
1597 				insn->dst_reg);
1598 			return -EACCES;
1599 		}
1600 
1601 		/* check dest operand */
1602 		err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1603 		if (err)
1604 			return err;
1605 
1606 	} else if (opcode == BPF_MOV) {
1607 
1608 		if (BPF_SRC(insn->code) == BPF_X) {
1609 			if (insn->imm != 0 || insn->off != 0) {
1610 				verbose("BPF_MOV uses reserved fields\n");
1611 				return -EINVAL;
1612 			}
1613 
1614 			/* check src operand */
1615 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1616 			if (err)
1617 				return err;
1618 		} else {
1619 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1620 				verbose("BPF_MOV uses reserved fields\n");
1621 				return -EINVAL;
1622 			}
1623 		}
1624 
1625 		/* check dest operand */
1626 		err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1627 		if (err)
1628 			return err;
1629 
1630 		/* we are setting our register to something new, we need to
1631 		 * reset its range values.
1632 		 */
1633 		reset_reg_range_values(regs, insn->dst_reg);
1634 
1635 		if (BPF_SRC(insn->code) == BPF_X) {
1636 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
1637 				/* case: R1 = R2
1638 				 * copy register state to dest reg
1639 				 */
1640 				regs[insn->dst_reg] = regs[insn->src_reg];
1641 			} else {
1642 				if (is_pointer_value(env, insn->src_reg)) {
1643 					verbose("R%d partial copy of pointer\n",
1644 						insn->src_reg);
1645 					return -EACCES;
1646 				}
1647 				regs[insn->dst_reg].type = UNKNOWN_VALUE;
1648 				regs[insn->dst_reg].map_ptr = NULL;
1649 			}
1650 		} else {
1651 			/* case: R = imm
1652 			 * remember the value we stored into this reg
1653 			 */
1654 			regs[insn->dst_reg].type = CONST_IMM;
1655 			regs[insn->dst_reg].imm = insn->imm;
1656 			regs[insn->dst_reg].max_value = insn->imm;
1657 			regs[insn->dst_reg].min_value = insn->imm;
1658 		}
1659 
1660 	} else if (opcode > BPF_END) {
1661 		verbose("invalid BPF_ALU opcode %x\n", opcode);
1662 		return -EINVAL;
1663 
1664 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
1665 
1666 		if (BPF_SRC(insn->code) == BPF_X) {
1667 			if (insn->imm != 0 || insn->off != 0) {
1668 				verbose("BPF_ALU uses reserved fields\n");
1669 				return -EINVAL;
1670 			}
1671 			/* check src1 operand */
1672 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1673 			if (err)
1674 				return err;
1675 		} else {
1676 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1677 				verbose("BPF_ALU uses reserved fields\n");
1678 				return -EINVAL;
1679 			}
1680 		}
1681 
1682 		/* check src2 operand */
1683 		err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1684 		if (err)
1685 			return err;
1686 
1687 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1688 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1689 			verbose("div by zero\n");
1690 			return -EINVAL;
1691 		}
1692 
1693 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1694 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1695 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1696 
1697 			if (insn->imm < 0 || insn->imm >= size) {
1698 				verbose("invalid shift %d\n", insn->imm);
1699 				return -EINVAL;
1700 			}
1701 		}
1702 
1703 		/* check dest operand */
1704 		err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1705 		if (err)
1706 			return err;
1707 
1708 		dst_reg = &regs[insn->dst_reg];
1709 
1710 		/* first we want to adjust our ranges. */
1711 		adjust_reg_min_max_vals(env, insn);
1712 
1713 		/* pattern match 'bpf_add Rx, imm' instruction */
1714 		if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1715 		    dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1716 			dst_reg->type = PTR_TO_STACK;
1717 			dst_reg->imm = insn->imm;
1718 			return 0;
1719 		} else if (opcode == BPF_ADD &&
1720 			   BPF_CLASS(insn->code) == BPF_ALU64 &&
1721 			   (dst_reg->type == PTR_TO_PACKET ||
1722 			    (BPF_SRC(insn->code) == BPF_X &&
1723 			     regs[insn->src_reg].type == PTR_TO_PACKET))) {
1724 			/* ptr_to_packet += K|X */
1725 			return check_packet_ptr_add(env, insn);
1726 		} else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1727 			   dst_reg->type == UNKNOWN_VALUE &&
1728 			   env->allow_ptr_leaks) {
1729 			/* unknown += K|X */
1730 			return evaluate_reg_alu(env, insn);
1731 		} else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1732 			   dst_reg->type == CONST_IMM &&
1733 			   env->allow_ptr_leaks) {
1734 			/* reg_imm += K|X */
1735 			return evaluate_reg_imm_alu(env, insn);
1736 		} else if (is_pointer_value(env, insn->dst_reg)) {
1737 			verbose("R%d pointer arithmetic prohibited\n",
1738 				insn->dst_reg);
1739 			return -EACCES;
1740 		} else if (BPF_SRC(insn->code) == BPF_X &&
1741 			   is_pointer_value(env, insn->src_reg)) {
1742 			verbose("R%d pointer arithmetic prohibited\n",
1743 				insn->src_reg);
1744 			return -EACCES;
1745 		}
1746 
1747 		/* If we did pointer math on a map value then just set it to our
1748 		 * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
1749 		 * loads to this register appropriately, otherwise just mark the
1750 		 * register as unknown.
1751 		 */
1752 		if (env->allow_ptr_leaks &&
1753 		    (dst_reg->type == PTR_TO_MAP_VALUE ||
1754 		     dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
1755 			dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
1756 		else
1757 			mark_reg_unknown_value(regs, insn->dst_reg);
1758 	}
1759 
1760 	return 0;
1761 }
1762 
1763 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
1764 				   struct bpf_reg_state *dst_reg)
1765 {
1766 	struct bpf_reg_state *regs = state->regs, *reg;
1767 	int i;
1768 
1769 	/* LLVM can generate two kind of checks:
1770 	 *
1771 	 * Type 1:
1772 	 *
1773 	 *   r2 = r3;
1774 	 *   r2 += 8;
1775 	 *   if (r2 > pkt_end) goto <handle exception>
1776 	 *   <access okay>
1777 	 *
1778 	 *   Where:
1779 	 *     r2 == dst_reg, pkt_end == src_reg
1780 	 *     r2=pkt(id=n,off=8,r=0)
1781 	 *     r3=pkt(id=n,off=0,r=0)
1782 	 *
1783 	 * Type 2:
1784 	 *
1785 	 *   r2 = r3;
1786 	 *   r2 += 8;
1787 	 *   if (pkt_end >= r2) goto <access okay>
1788 	 *   <handle exception>
1789 	 *
1790 	 *   Where:
1791 	 *     pkt_end == dst_reg, r2 == src_reg
1792 	 *     r2=pkt(id=n,off=8,r=0)
1793 	 *     r3=pkt(id=n,off=0,r=0)
1794 	 *
1795 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1796 	 * so that range of bytes [r3, r3 + 8) is safe to access.
1797 	 */
1798 
1799 	for (i = 0; i < MAX_BPF_REG; i++)
1800 		if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
1801 			regs[i].range = dst_reg->off;
1802 
1803 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1804 		if (state->stack_slot_type[i] != STACK_SPILL)
1805 			continue;
1806 		reg = &state->spilled_regs[i / BPF_REG_SIZE];
1807 		if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
1808 			reg->range = dst_reg->off;
1809 	}
1810 }
1811 
1812 /* Adjusts the register min/max values in the case that the dst_reg is the
1813  * variable register that we are working on, and src_reg is a constant or we're
1814  * simply doing a BPF_K check.
1815  */
1816 static void reg_set_min_max(struct bpf_reg_state *true_reg,
1817 			    struct bpf_reg_state *false_reg, u64 val,
1818 			    u8 opcode)
1819 {
1820 	switch (opcode) {
1821 	case BPF_JEQ:
1822 		/* If this is false then we know nothing Jon Snow, but if it is
1823 		 * true then we know for sure.
1824 		 */
1825 		true_reg->max_value = true_reg->min_value = val;
1826 		break;
1827 	case BPF_JNE:
1828 		/* If this is true we know nothing Jon Snow, but if it is false
1829 		 * we know the value for sure;
1830 		 */
1831 		false_reg->max_value = false_reg->min_value = val;
1832 		break;
1833 	case BPF_JGT:
1834 		/* Unsigned comparison, the minimum value is 0. */
1835 		false_reg->min_value = 0;
1836 	case BPF_JSGT:
1837 		/* If this is false then we know the maximum val is val,
1838 		 * otherwise we know the min val is val+1.
1839 		 */
1840 		false_reg->max_value = val;
1841 		true_reg->min_value = val + 1;
1842 		break;
1843 	case BPF_JGE:
1844 		/* Unsigned comparison, the minimum value is 0. */
1845 		false_reg->min_value = 0;
1846 	case BPF_JSGE:
1847 		/* If this is false then we know the maximum value is val - 1,
1848 		 * otherwise we know the mimimum value is val.
1849 		 */
1850 		false_reg->max_value = val - 1;
1851 		true_reg->min_value = val;
1852 		break;
1853 	default:
1854 		break;
1855 	}
1856 
1857 	check_reg_overflow(false_reg);
1858 	check_reg_overflow(true_reg);
1859 }
1860 
1861 /* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
1862  * is the variable reg.
1863  */
1864 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
1865 				struct bpf_reg_state *false_reg, u64 val,
1866 				u8 opcode)
1867 {
1868 	switch (opcode) {
1869 	case BPF_JEQ:
1870 		/* If this is false then we know nothing Jon Snow, but if it is
1871 		 * true then we know for sure.
1872 		 */
1873 		true_reg->max_value = true_reg->min_value = val;
1874 		break;
1875 	case BPF_JNE:
1876 		/* If this is true we know nothing Jon Snow, but if it is false
1877 		 * we know the value for sure;
1878 		 */
1879 		false_reg->max_value = false_reg->min_value = val;
1880 		break;
1881 	case BPF_JGT:
1882 		/* Unsigned comparison, the minimum value is 0. */
1883 		true_reg->min_value = 0;
1884 	case BPF_JSGT:
1885 		/*
1886 		 * If this is false, then the val is <= the register, if it is
1887 		 * true the register <= to the val.
1888 		 */
1889 		false_reg->min_value = val;
1890 		true_reg->max_value = val - 1;
1891 		break;
1892 	case BPF_JGE:
1893 		/* Unsigned comparison, the minimum value is 0. */
1894 		true_reg->min_value = 0;
1895 	case BPF_JSGE:
1896 		/* If this is false then constant < register, if it is true then
1897 		 * the register < constant.
1898 		 */
1899 		false_reg->min_value = val + 1;
1900 		true_reg->max_value = val;
1901 		break;
1902 	default:
1903 		break;
1904 	}
1905 
1906 	check_reg_overflow(false_reg);
1907 	check_reg_overflow(true_reg);
1908 }
1909 
1910 static int check_cond_jmp_op(struct bpf_verifier_env *env,
1911 			     struct bpf_insn *insn, int *insn_idx)
1912 {
1913 	struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
1914 	struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
1915 	u8 opcode = BPF_OP(insn->code);
1916 	int err;
1917 
1918 	if (opcode > BPF_EXIT) {
1919 		verbose("invalid BPF_JMP opcode %x\n", opcode);
1920 		return -EINVAL;
1921 	}
1922 
1923 	if (BPF_SRC(insn->code) == BPF_X) {
1924 		if (insn->imm != 0) {
1925 			verbose("BPF_JMP uses reserved fields\n");
1926 			return -EINVAL;
1927 		}
1928 
1929 		/* check src1 operand */
1930 		err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1931 		if (err)
1932 			return err;
1933 
1934 		if (is_pointer_value(env, insn->src_reg)) {
1935 			verbose("R%d pointer comparison prohibited\n",
1936 				insn->src_reg);
1937 			return -EACCES;
1938 		}
1939 	} else {
1940 		if (insn->src_reg != BPF_REG_0) {
1941 			verbose("BPF_JMP uses reserved fields\n");
1942 			return -EINVAL;
1943 		}
1944 	}
1945 
1946 	/* check src2 operand */
1947 	err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1948 	if (err)
1949 		return err;
1950 
1951 	dst_reg = &regs[insn->dst_reg];
1952 
1953 	/* detect if R == 0 where R was initialized to zero earlier */
1954 	if (BPF_SRC(insn->code) == BPF_K &&
1955 	    (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1956 	    dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
1957 		if (opcode == BPF_JEQ) {
1958 			/* if (imm == imm) goto pc+off;
1959 			 * only follow the goto, ignore fall-through
1960 			 */
1961 			*insn_idx += insn->off;
1962 			return 0;
1963 		} else {
1964 			/* if (imm != imm) goto pc+off;
1965 			 * only follow fall-through branch, since
1966 			 * that's where the program will go
1967 			 */
1968 			return 0;
1969 		}
1970 	}
1971 
1972 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
1973 	if (!other_branch)
1974 		return -EFAULT;
1975 
1976 	/* detect if we are comparing against a constant value so we can adjust
1977 	 * our min/max values for our dst register.
1978 	 */
1979 	if (BPF_SRC(insn->code) == BPF_X) {
1980 		if (regs[insn->src_reg].type == CONST_IMM)
1981 			reg_set_min_max(&other_branch->regs[insn->dst_reg],
1982 					dst_reg, regs[insn->src_reg].imm,
1983 					opcode);
1984 		else if (dst_reg->type == CONST_IMM)
1985 			reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
1986 					    &regs[insn->src_reg], dst_reg->imm,
1987 					    opcode);
1988 	} else {
1989 		reg_set_min_max(&other_branch->regs[insn->dst_reg],
1990 					dst_reg, insn->imm, opcode);
1991 	}
1992 
1993 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
1994 	if (BPF_SRC(insn->code) == BPF_K &&
1995 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1996 	    dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1997 		if (opcode == BPF_JEQ) {
1998 			/* next fallthrough insn can access memory via
1999 			 * this register
2000 			 */
2001 			regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
2002 			/* branch targer cannot access it, since reg == 0 */
2003 			mark_reg_unknown_value(other_branch->regs,
2004 					       insn->dst_reg);
2005 		} else {
2006 			other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
2007 			mark_reg_unknown_value(regs, insn->dst_reg);
2008 		}
2009 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2010 		   dst_reg->type == PTR_TO_PACKET &&
2011 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
2012 		find_good_pkt_pointers(this_branch, dst_reg);
2013 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2014 		   dst_reg->type == PTR_TO_PACKET_END &&
2015 		   regs[insn->src_reg].type == PTR_TO_PACKET) {
2016 		find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
2017 	} else if (is_pointer_value(env, insn->dst_reg)) {
2018 		verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
2019 		return -EACCES;
2020 	}
2021 	if (log_level)
2022 		print_verifier_state(this_branch);
2023 	return 0;
2024 }
2025 
2026 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
2027 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2028 {
2029 	u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2030 
2031 	return (struct bpf_map *) (unsigned long) imm64;
2032 }
2033 
2034 /* verify BPF_LD_IMM64 instruction */
2035 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
2036 {
2037 	struct bpf_reg_state *regs = env->cur_state.regs;
2038 	int err;
2039 
2040 	if (BPF_SIZE(insn->code) != BPF_DW) {
2041 		verbose("invalid BPF_LD_IMM insn\n");
2042 		return -EINVAL;
2043 	}
2044 	if (insn->off != 0) {
2045 		verbose("BPF_LD_IMM64 uses reserved fields\n");
2046 		return -EINVAL;
2047 	}
2048 
2049 	err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2050 	if (err)
2051 		return err;
2052 
2053 	if (insn->src_reg == 0) {
2054 		/* generic move 64-bit immediate into a register,
2055 		 * only analyzer needs to collect the ld_imm value.
2056 		 */
2057 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
2058 
2059 		if (!env->analyzer_ops)
2060 			return 0;
2061 
2062 		regs[insn->dst_reg].type = CONST_IMM;
2063 		regs[insn->dst_reg].imm = imm;
2064 		return 0;
2065 	}
2066 
2067 	/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
2068 	BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
2069 
2070 	regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
2071 	regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
2072 	return 0;
2073 }
2074 
2075 static bool may_access_skb(enum bpf_prog_type type)
2076 {
2077 	switch (type) {
2078 	case BPF_PROG_TYPE_SOCKET_FILTER:
2079 	case BPF_PROG_TYPE_SCHED_CLS:
2080 	case BPF_PROG_TYPE_SCHED_ACT:
2081 		return true;
2082 	default:
2083 		return false;
2084 	}
2085 }
2086 
2087 /* verify safety of LD_ABS|LD_IND instructions:
2088  * - they can only appear in the programs where ctx == skb
2089  * - since they are wrappers of function calls, they scratch R1-R5 registers,
2090  *   preserve R6-R9, and store return value into R0
2091  *
2092  * Implicit input:
2093  *   ctx == skb == R6 == CTX
2094  *
2095  * Explicit input:
2096  *   SRC == any register
2097  *   IMM == 32-bit immediate
2098  *
2099  * Output:
2100  *   R0 - 8/16/32-bit skb data converted to cpu endianness
2101  */
2102 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
2103 {
2104 	struct bpf_reg_state *regs = env->cur_state.regs;
2105 	u8 mode = BPF_MODE(insn->code);
2106 	struct bpf_reg_state *reg;
2107 	int i, err;
2108 
2109 	if (!may_access_skb(env->prog->type)) {
2110 		verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
2111 		return -EINVAL;
2112 	}
2113 
2114 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
2115 	    BPF_SIZE(insn->code) == BPF_DW ||
2116 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
2117 		verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
2118 		return -EINVAL;
2119 	}
2120 
2121 	/* check whether implicit source operand (register R6) is readable */
2122 	err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
2123 	if (err)
2124 		return err;
2125 
2126 	if (regs[BPF_REG_6].type != PTR_TO_CTX) {
2127 		verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
2128 		return -EINVAL;
2129 	}
2130 
2131 	if (mode == BPF_IND) {
2132 		/* check explicit source operand */
2133 		err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2134 		if (err)
2135 			return err;
2136 	}
2137 
2138 	/* reset caller saved regs to unreadable */
2139 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
2140 		reg = regs + caller_saved[i];
2141 		reg->type = NOT_INIT;
2142 		reg->imm = 0;
2143 	}
2144 
2145 	/* mark destination R0 register as readable, since it contains
2146 	 * the value fetched from the packet
2147 	 */
2148 	regs[BPF_REG_0].type = UNKNOWN_VALUE;
2149 	return 0;
2150 }
2151 
2152 /* non-recursive DFS pseudo code
2153  * 1  procedure DFS-iterative(G,v):
2154  * 2      label v as discovered
2155  * 3      let S be a stack
2156  * 4      S.push(v)
2157  * 5      while S is not empty
2158  * 6            t <- S.pop()
2159  * 7            if t is what we're looking for:
2160  * 8                return t
2161  * 9            for all edges e in G.adjacentEdges(t) do
2162  * 10               if edge e is already labelled
2163  * 11                   continue with the next edge
2164  * 12               w <- G.adjacentVertex(t,e)
2165  * 13               if vertex w is not discovered and not explored
2166  * 14                   label e as tree-edge
2167  * 15                   label w as discovered
2168  * 16                   S.push(w)
2169  * 17                   continue at 5
2170  * 18               else if vertex w is discovered
2171  * 19                   label e as back-edge
2172  * 20               else
2173  * 21                   // vertex w is explored
2174  * 22                   label e as forward- or cross-edge
2175  * 23           label t as explored
2176  * 24           S.pop()
2177  *
2178  * convention:
2179  * 0x10 - discovered
2180  * 0x11 - discovered and fall-through edge labelled
2181  * 0x12 - discovered and fall-through and branch edges labelled
2182  * 0x20 - explored
2183  */
2184 
2185 enum {
2186 	DISCOVERED = 0x10,
2187 	EXPLORED = 0x20,
2188 	FALLTHROUGH = 1,
2189 	BRANCH = 2,
2190 };
2191 
2192 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
2193 
2194 static int *insn_stack;	/* stack of insns to process */
2195 static int cur_stack;	/* current stack index */
2196 static int *insn_state;
2197 
2198 /* t, w, e - match pseudo-code above:
2199  * t - index of current instruction
2200  * w - next instruction
2201  * e - edge
2202  */
2203 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
2204 {
2205 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
2206 		return 0;
2207 
2208 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
2209 		return 0;
2210 
2211 	if (w < 0 || w >= env->prog->len) {
2212 		verbose("jump out of range from insn %d to %d\n", t, w);
2213 		return -EINVAL;
2214 	}
2215 
2216 	if (e == BRANCH)
2217 		/* mark branch target for state pruning */
2218 		env->explored_states[w] = STATE_LIST_MARK;
2219 
2220 	if (insn_state[w] == 0) {
2221 		/* tree-edge */
2222 		insn_state[t] = DISCOVERED | e;
2223 		insn_state[w] = DISCOVERED;
2224 		if (cur_stack >= env->prog->len)
2225 			return -E2BIG;
2226 		insn_stack[cur_stack++] = w;
2227 		return 1;
2228 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2229 		verbose("back-edge from insn %d to %d\n", t, w);
2230 		return -EINVAL;
2231 	} else if (insn_state[w] == EXPLORED) {
2232 		/* forward- or cross-edge */
2233 		insn_state[t] = DISCOVERED | e;
2234 	} else {
2235 		verbose("insn state internal bug\n");
2236 		return -EFAULT;
2237 	}
2238 	return 0;
2239 }
2240 
2241 /* non-recursive depth-first-search to detect loops in BPF program
2242  * loop == back-edge in directed graph
2243  */
2244 static int check_cfg(struct bpf_verifier_env *env)
2245 {
2246 	struct bpf_insn *insns = env->prog->insnsi;
2247 	int insn_cnt = env->prog->len;
2248 	int ret = 0;
2249 	int i, t;
2250 
2251 	insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2252 	if (!insn_state)
2253 		return -ENOMEM;
2254 
2255 	insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2256 	if (!insn_stack) {
2257 		kfree(insn_state);
2258 		return -ENOMEM;
2259 	}
2260 
2261 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
2262 	insn_stack[0] = 0; /* 0 is the first instruction */
2263 	cur_stack = 1;
2264 
2265 peek_stack:
2266 	if (cur_stack == 0)
2267 		goto check_state;
2268 	t = insn_stack[cur_stack - 1];
2269 
2270 	if (BPF_CLASS(insns[t].code) == BPF_JMP) {
2271 		u8 opcode = BPF_OP(insns[t].code);
2272 
2273 		if (opcode == BPF_EXIT) {
2274 			goto mark_explored;
2275 		} else if (opcode == BPF_CALL) {
2276 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
2277 			if (ret == 1)
2278 				goto peek_stack;
2279 			else if (ret < 0)
2280 				goto err_free;
2281 			if (t + 1 < insn_cnt)
2282 				env->explored_states[t + 1] = STATE_LIST_MARK;
2283 		} else if (opcode == BPF_JA) {
2284 			if (BPF_SRC(insns[t].code) != BPF_K) {
2285 				ret = -EINVAL;
2286 				goto err_free;
2287 			}
2288 			/* unconditional jump with single edge */
2289 			ret = push_insn(t, t + insns[t].off + 1,
2290 					FALLTHROUGH, env);
2291 			if (ret == 1)
2292 				goto peek_stack;
2293 			else if (ret < 0)
2294 				goto err_free;
2295 			/* tell verifier to check for equivalent states
2296 			 * after every call and jump
2297 			 */
2298 			if (t + 1 < insn_cnt)
2299 				env->explored_states[t + 1] = STATE_LIST_MARK;
2300 		} else {
2301 			/* conditional jump with two edges */
2302 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
2303 			if (ret == 1)
2304 				goto peek_stack;
2305 			else if (ret < 0)
2306 				goto err_free;
2307 
2308 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2309 			if (ret == 1)
2310 				goto peek_stack;
2311 			else if (ret < 0)
2312 				goto err_free;
2313 		}
2314 	} else {
2315 		/* all other non-branch instructions with single
2316 		 * fall-through edge
2317 		 */
2318 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
2319 		if (ret == 1)
2320 			goto peek_stack;
2321 		else if (ret < 0)
2322 			goto err_free;
2323 	}
2324 
2325 mark_explored:
2326 	insn_state[t] = EXPLORED;
2327 	if (cur_stack-- <= 0) {
2328 		verbose("pop stack internal bug\n");
2329 		ret = -EFAULT;
2330 		goto err_free;
2331 	}
2332 	goto peek_stack;
2333 
2334 check_state:
2335 	for (i = 0; i < insn_cnt; i++) {
2336 		if (insn_state[i] != EXPLORED) {
2337 			verbose("unreachable insn %d\n", i);
2338 			ret = -EINVAL;
2339 			goto err_free;
2340 		}
2341 	}
2342 	ret = 0; /* cfg looks good */
2343 
2344 err_free:
2345 	kfree(insn_state);
2346 	kfree(insn_stack);
2347 	return ret;
2348 }
2349 
2350 /* the following conditions reduce the number of explored insns
2351  * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2352  */
2353 static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
2354 				   struct bpf_reg_state *cur)
2355 {
2356 	if (old->id != cur->id)
2357 		return false;
2358 
2359 	/* old ptr_to_packet is more conservative, since it allows smaller
2360 	 * range. Ex:
2361 	 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2362 	 * old(off=0,r=10) means that with range=10 the verifier proceeded
2363 	 * further and found no issues with the program. Now we're in the same
2364 	 * spot with cur(off=0,r=20), so we're safe too, since anything further
2365 	 * will only be looking at most 10 bytes after this pointer.
2366 	 */
2367 	if (old->off == cur->off && old->range < cur->range)
2368 		return true;
2369 
2370 	/* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2371 	 * since both cannot be used for packet access and safe(old)
2372 	 * pointer has smaller off that could be used for further
2373 	 * 'if (ptr > data_end)' check
2374 	 * Ex:
2375 	 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2376 	 * that we cannot access the packet.
2377 	 * The safe range is:
2378 	 * [ptr, ptr + range - off)
2379 	 * so whenever off >=range, it means no safe bytes from this pointer.
2380 	 * When comparing old->off <= cur->off, it means that older code
2381 	 * went with smaller offset and that offset was later
2382 	 * used to figure out the safe range after 'if (ptr > data_end)' check
2383 	 * Say, 'old' state was explored like:
2384 	 * ... R3(off=0, r=0)
2385 	 * R4 = R3 + 20
2386 	 * ... now R4(off=20,r=0)  <-- here
2387 	 * if (R4 > data_end)
2388 	 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2389 	 * ... the code further went all the way to bpf_exit.
2390 	 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2391 	 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2392 	 * goes further, such cur_R4 will give larger safe packet range after
2393 	 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2394 	 * so they will be good with r=30 and we can prune the search.
2395 	 */
2396 	if (old->off <= cur->off &&
2397 	    old->off >= old->range && cur->off >= cur->range)
2398 		return true;
2399 
2400 	return false;
2401 }
2402 
2403 /* compare two verifier states
2404  *
2405  * all states stored in state_list are known to be valid, since
2406  * verifier reached 'bpf_exit' instruction through them
2407  *
2408  * this function is called when verifier exploring different branches of
2409  * execution popped from the state stack. If it sees an old state that has
2410  * more strict register state and more strict stack state then this execution
2411  * branch doesn't need to be explored further, since verifier already
2412  * concluded that more strict state leads to valid finish.
2413  *
2414  * Therefore two states are equivalent if register state is more conservative
2415  * and explored stack state is more conservative than the current one.
2416  * Example:
2417  *       explored                   current
2418  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2419  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2420  *
2421  * In other words if current stack state (one being explored) has more
2422  * valid slots than old one that already passed validation, it means
2423  * the verifier can stop exploring and conclude that current state is valid too
2424  *
2425  * Similarly with registers. If explored state has register type as invalid
2426  * whereas register type in current state is meaningful, it means that
2427  * the current state will reach 'bpf_exit' instruction safely
2428  */
2429 static bool states_equal(struct bpf_verifier_env *env,
2430 			 struct bpf_verifier_state *old,
2431 			 struct bpf_verifier_state *cur)
2432 {
2433 	struct bpf_reg_state *rold, *rcur;
2434 	int i;
2435 
2436 	for (i = 0; i < MAX_BPF_REG; i++) {
2437 		rold = &old->regs[i];
2438 		rcur = &cur->regs[i];
2439 
2440 		if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2441 			continue;
2442 
2443 		/* If the ranges were not the same, but everything else was and
2444 		 * we didn't do a variable access into a map then we are a-ok.
2445 		 */
2446 		if (!env->varlen_map_value_access &&
2447 		    rold->type == rcur->type && rold->imm == rcur->imm)
2448 			continue;
2449 
2450 		if (rold->type == NOT_INIT ||
2451 		    (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
2452 			continue;
2453 
2454 		if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2455 		    compare_ptrs_to_packet(rold, rcur))
2456 			continue;
2457 
2458 		return false;
2459 	}
2460 
2461 	for (i = 0; i < MAX_BPF_STACK; i++) {
2462 		if (old->stack_slot_type[i] == STACK_INVALID)
2463 			continue;
2464 		if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2465 			/* Ex: old explored (safe) state has STACK_SPILL in
2466 			 * this stack slot, but current has has STACK_MISC ->
2467 			 * this verifier states are not equivalent,
2468 			 * return false to continue verification of this path
2469 			 */
2470 			return false;
2471 		if (i % BPF_REG_SIZE)
2472 			continue;
2473 		if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2474 			   &cur->spilled_regs[i / BPF_REG_SIZE],
2475 			   sizeof(old->spilled_regs[0])))
2476 			/* when explored and current stack slot types are
2477 			 * the same, check that stored pointers types
2478 			 * are the same as well.
2479 			 * Ex: explored safe path could have stored
2480 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
2481 			 * but current path has stored:
2482 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
2483 			 * such verifier states are not equivalent.
2484 			 * return false to continue verification of this path
2485 			 */
2486 			return false;
2487 		else
2488 			continue;
2489 	}
2490 	return true;
2491 }
2492 
2493 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
2494 {
2495 	struct bpf_verifier_state_list *new_sl;
2496 	struct bpf_verifier_state_list *sl;
2497 
2498 	sl = env->explored_states[insn_idx];
2499 	if (!sl)
2500 		/* this 'insn_idx' instruction wasn't marked, so we will not
2501 		 * be doing state search here
2502 		 */
2503 		return 0;
2504 
2505 	while (sl != STATE_LIST_MARK) {
2506 		if (states_equal(env, &sl->state, &env->cur_state))
2507 			/* reached equivalent register/stack state,
2508 			 * prune the search
2509 			 */
2510 			return 1;
2511 		sl = sl->next;
2512 	}
2513 
2514 	/* there were no equivalent states, remember current one.
2515 	 * technically the current state is not proven to be safe yet,
2516 	 * but it will either reach bpf_exit (which means it's safe) or
2517 	 * it will be rejected. Since there are no loops, we won't be
2518 	 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2519 	 */
2520 	new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
2521 	if (!new_sl)
2522 		return -ENOMEM;
2523 
2524 	/* add new state to the head of linked list */
2525 	memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2526 	new_sl->next = env->explored_states[insn_idx];
2527 	env->explored_states[insn_idx] = new_sl;
2528 	return 0;
2529 }
2530 
2531 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2532 				  int insn_idx, int prev_insn_idx)
2533 {
2534 	if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2535 		return 0;
2536 
2537 	return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2538 }
2539 
2540 static int do_check(struct bpf_verifier_env *env)
2541 {
2542 	struct bpf_verifier_state *state = &env->cur_state;
2543 	struct bpf_insn *insns = env->prog->insnsi;
2544 	struct bpf_reg_state *regs = state->regs;
2545 	int insn_cnt = env->prog->len;
2546 	int insn_idx, prev_insn_idx = 0;
2547 	int insn_processed = 0;
2548 	bool do_print_state = false;
2549 
2550 	init_reg_state(regs);
2551 	insn_idx = 0;
2552 	env->varlen_map_value_access = false;
2553 	for (;;) {
2554 		struct bpf_insn *insn;
2555 		u8 class;
2556 		int err;
2557 
2558 		if (insn_idx >= insn_cnt) {
2559 			verbose("invalid insn idx %d insn_cnt %d\n",
2560 				insn_idx, insn_cnt);
2561 			return -EFAULT;
2562 		}
2563 
2564 		insn = &insns[insn_idx];
2565 		class = BPF_CLASS(insn->code);
2566 
2567 		if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2568 			verbose("BPF program is too large. Proccessed %d insn\n",
2569 				insn_processed);
2570 			return -E2BIG;
2571 		}
2572 
2573 		err = is_state_visited(env, insn_idx);
2574 		if (err < 0)
2575 			return err;
2576 		if (err == 1) {
2577 			/* found equivalent state, can prune the search */
2578 			if (log_level) {
2579 				if (do_print_state)
2580 					verbose("\nfrom %d to %d: safe\n",
2581 						prev_insn_idx, insn_idx);
2582 				else
2583 					verbose("%d: safe\n", insn_idx);
2584 			}
2585 			goto process_bpf_exit;
2586 		}
2587 
2588 		if (log_level && do_print_state) {
2589 			verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
2590 			print_verifier_state(&env->cur_state);
2591 			do_print_state = false;
2592 		}
2593 
2594 		if (log_level) {
2595 			verbose("%d: ", insn_idx);
2596 			print_bpf_insn(insn);
2597 		}
2598 
2599 		err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2600 		if (err)
2601 			return err;
2602 
2603 		if (class == BPF_ALU || class == BPF_ALU64) {
2604 			err = check_alu_op(env, insn);
2605 			if (err)
2606 				return err;
2607 
2608 		} else if (class == BPF_LDX) {
2609 			enum bpf_reg_type *prev_src_type, src_reg_type;
2610 
2611 			/* check for reserved fields is already done */
2612 
2613 			/* check src operand */
2614 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2615 			if (err)
2616 				return err;
2617 
2618 			err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2619 			if (err)
2620 				return err;
2621 
2622 			src_reg_type = regs[insn->src_reg].type;
2623 
2624 			/* check that memory (src_reg + off) is readable,
2625 			 * the state of dst_reg will be updated by this func
2626 			 */
2627 			err = check_mem_access(env, insn->src_reg, insn->off,
2628 					       BPF_SIZE(insn->code), BPF_READ,
2629 					       insn->dst_reg);
2630 			if (err)
2631 				return err;
2632 
2633 			reset_reg_range_values(regs, insn->dst_reg);
2634 			if (BPF_SIZE(insn->code) != BPF_W &&
2635 			    BPF_SIZE(insn->code) != BPF_DW) {
2636 				insn_idx++;
2637 				continue;
2638 			}
2639 
2640 			prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
2641 
2642 			if (*prev_src_type == NOT_INIT) {
2643 				/* saw a valid insn
2644 				 * dst_reg = *(u32 *)(src_reg + off)
2645 				 * save type to validate intersecting paths
2646 				 */
2647 				*prev_src_type = src_reg_type;
2648 
2649 			} else if (src_reg_type != *prev_src_type &&
2650 				   (src_reg_type == PTR_TO_CTX ||
2651 				    *prev_src_type == PTR_TO_CTX)) {
2652 				/* ABuser program is trying to use the same insn
2653 				 * dst_reg = *(u32*) (src_reg + off)
2654 				 * with different pointer types:
2655 				 * src_reg == ctx in one branch and
2656 				 * src_reg == stack|map in some other branch.
2657 				 * Reject it.
2658 				 */
2659 				verbose("same insn cannot be used with different pointers\n");
2660 				return -EINVAL;
2661 			}
2662 
2663 		} else if (class == BPF_STX) {
2664 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
2665 
2666 			if (BPF_MODE(insn->code) == BPF_XADD) {
2667 				err = check_xadd(env, insn);
2668 				if (err)
2669 					return err;
2670 				insn_idx++;
2671 				continue;
2672 			}
2673 
2674 			/* check src1 operand */
2675 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2676 			if (err)
2677 				return err;
2678 			/* check src2 operand */
2679 			err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2680 			if (err)
2681 				return err;
2682 
2683 			dst_reg_type = regs[insn->dst_reg].type;
2684 
2685 			/* check that memory (dst_reg + off) is writeable */
2686 			err = check_mem_access(env, insn->dst_reg, insn->off,
2687 					       BPF_SIZE(insn->code), BPF_WRITE,
2688 					       insn->src_reg);
2689 			if (err)
2690 				return err;
2691 
2692 			prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
2693 
2694 			if (*prev_dst_type == NOT_INIT) {
2695 				*prev_dst_type = dst_reg_type;
2696 			} else if (dst_reg_type != *prev_dst_type &&
2697 				   (dst_reg_type == PTR_TO_CTX ||
2698 				    *prev_dst_type == PTR_TO_CTX)) {
2699 				verbose("same insn cannot be used with different pointers\n");
2700 				return -EINVAL;
2701 			}
2702 
2703 		} else if (class == BPF_ST) {
2704 			if (BPF_MODE(insn->code) != BPF_MEM ||
2705 			    insn->src_reg != BPF_REG_0) {
2706 				verbose("BPF_ST uses reserved fields\n");
2707 				return -EINVAL;
2708 			}
2709 			/* check src operand */
2710 			err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2711 			if (err)
2712 				return err;
2713 
2714 			/* check that memory (dst_reg + off) is writeable */
2715 			err = check_mem_access(env, insn->dst_reg, insn->off,
2716 					       BPF_SIZE(insn->code), BPF_WRITE,
2717 					       -1);
2718 			if (err)
2719 				return err;
2720 
2721 		} else if (class == BPF_JMP) {
2722 			u8 opcode = BPF_OP(insn->code);
2723 
2724 			if (opcode == BPF_CALL) {
2725 				if (BPF_SRC(insn->code) != BPF_K ||
2726 				    insn->off != 0 ||
2727 				    insn->src_reg != BPF_REG_0 ||
2728 				    insn->dst_reg != BPF_REG_0) {
2729 					verbose("BPF_CALL uses reserved fields\n");
2730 					return -EINVAL;
2731 				}
2732 
2733 				err = check_call(env, insn->imm);
2734 				if (err)
2735 					return err;
2736 
2737 			} else if (opcode == BPF_JA) {
2738 				if (BPF_SRC(insn->code) != BPF_K ||
2739 				    insn->imm != 0 ||
2740 				    insn->src_reg != BPF_REG_0 ||
2741 				    insn->dst_reg != BPF_REG_0) {
2742 					verbose("BPF_JA uses reserved fields\n");
2743 					return -EINVAL;
2744 				}
2745 
2746 				insn_idx += insn->off + 1;
2747 				continue;
2748 
2749 			} else if (opcode == BPF_EXIT) {
2750 				if (BPF_SRC(insn->code) != BPF_K ||
2751 				    insn->imm != 0 ||
2752 				    insn->src_reg != BPF_REG_0 ||
2753 				    insn->dst_reg != BPF_REG_0) {
2754 					verbose("BPF_EXIT uses reserved fields\n");
2755 					return -EINVAL;
2756 				}
2757 
2758 				/* eBPF calling convetion is such that R0 is used
2759 				 * to return the value from eBPF program.
2760 				 * Make sure that it's readable at this time
2761 				 * of bpf_exit, which means that program wrote
2762 				 * something into it earlier
2763 				 */
2764 				err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2765 				if (err)
2766 					return err;
2767 
2768 				if (is_pointer_value(env, BPF_REG_0)) {
2769 					verbose("R0 leaks addr as return value\n");
2770 					return -EACCES;
2771 				}
2772 
2773 process_bpf_exit:
2774 				insn_idx = pop_stack(env, &prev_insn_idx);
2775 				if (insn_idx < 0) {
2776 					break;
2777 				} else {
2778 					do_print_state = true;
2779 					continue;
2780 				}
2781 			} else {
2782 				err = check_cond_jmp_op(env, insn, &insn_idx);
2783 				if (err)
2784 					return err;
2785 			}
2786 		} else if (class == BPF_LD) {
2787 			u8 mode = BPF_MODE(insn->code);
2788 
2789 			if (mode == BPF_ABS || mode == BPF_IND) {
2790 				err = check_ld_abs(env, insn);
2791 				if (err)
2792 					return err;
2793 
2794 			} else if (mode == BPF_IMM) {
2795 				err = check_ld_imm(env, insn);
2796 				if (err)
2797 					return err;
2798 
2799 				insn_idx++;
2800 			} else {
2801 				verbose("invalid BPF_LD mode\n");
2802 				return -EINVAL;
2803 			}
2804 			reset_reg_range_values(regs, insn->dst_reg);
2805 		} else {
2806 			verbose("unknown insn class %d\n", class);
2807 			return -EINVAL;
2808 		}
2809 
2810 		insn_idx++;
2811 	}
2812 
2813 	verbose("processed %d insns\n", insn_processed);
2814 	return 0;
2815 }
2816 
2817 static int check_map_prog_compatibility(struct bpf_map *map,
2818 					struct bpf_prog *prog)
2819 
2820 {
2821 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
2822 	    (map->map_type == BPF_MAP_TYPE_HASH ||
2823 	     map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
2824 	    (map->map_flags & BPF_F_NO_PREALLOC)) {
2825 		verbose("perf_event programs can only use preallocated hash map\n");
2826 		return -EINVAL;
2827 	}
2828 	return 0;
2829 }
2830 
2831 /* look for pseudo eBPF instructions that access map FDs and
2832  * replace them with actual map pointers
2833  */
2834 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
2835 {
2836 	struct bpf_insn *insn = env->prog->insnsi;
2837 	int insn_cnt = env->prog->len;
2838 	int i, j, err;
2839 
2840 	for (i = 0; i < insn_cnt; i++, insn++) {
2841 		if (BPF_CLASS(insn->code) == BPF_LDX &&
2842 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
2843 			verbose("BPF_LDX uses reserved fields\n");
2844 			return -EINVAL;
2845 		}
2846 
2847 		if (BPF_CLASS(insn->code) == BPF_STX &&
2848 		    ((BPF_MODE(insn->code) != BPF_MEM &&
2849 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2850 			verbose("BPF_STX uses reserved fields\n");
2851 			return -EINVAL;
2852 		}
2853 
2854 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2855 			struct bpf_map *map;
2856 			struct fd f;
2857 
2858 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
2859 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2860 			    insn[1].off != 0) {
2861 				verbose("invalid bpf_ld_imm64 insn\n");
2862 				return -EINVAL;
2863 			}
2864 
2865 			if (insn->src_reg == 0)
2866 				/* valid generic load 64-bit imm */
2867 				goto next_insn;
2868 
2869 			if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2870 				verbose("unrecognized bpf_ld_imm64 insn\n");
2871 				return -EINVAL;
2872 			}
2873 
2874 			f = fdget(insn->imm);
2875 			map = __bpf_map_get(f);
2876 			if (IS_ERR(map)) {
2877 				verbose("fd %d is not pointing to valid bpf_map\n",
2878 					insn->imm);
2879 				return PTR_ERR(map);
2880 			}
2881 
2882 			err = check_map_prog_compatibility(map, env->prog);
2883 			if (err) {
2884 				fdput(f);
2885 				return err;
2886 			}
2887 
2888 			/* store map pointer inside BPF_LD_IMM64 instruction */
2889 			insn[0].imm = (u32) (unsigned long) map;
2890 			insn[1].imm = ((u64) (unsigned long) map) >> 32;
2891 
2892 			/* check whether we recorded this map already */
2893 			for (j = 0; j < env->used_map_cnt; j++)
2894 				if (env->used_maps[j] == map) {
2895 					fdput(f);
2896 					goto next_insn;
2897 				}
2898 
2899 			if (env->used_map_cnt >= MAX_USED_MAPS) {
2900 				fdput(f);
2901 				return -E2BIG;
2902 			}
2903 
2904 			/* hold the map. If the program is rejected by verifier,
2905 			 * the map will be released by release_maps() or it
2906 			 * will be used by the valid program until it's unloaded
2907 			 * and all maps are released in free_bpf_prog_info()
2908 			 */
2909 			map = bpf_map_inc(map, false);
2910 			if (IS_ERR(map)) {
2911 				fdput(f);
2912 				return PTR_ERR(map);
2913 			}
2914 			env->used_maps[env->used_map_cnt++] = map;
2915 
2916 			fdput(f);
2917 next_insn:
2918 			insn++;
2919 			i++;
2920 		}
2921 	}
2922 
2923 	/* now all pseudo BPF_LD_IMM64 instructions load valid
2924 	 * 'struct bpf_map *' into a register instead of user map_fd.
2925 	 * These pointers will be used later by verifier to validate map access.
2926 	 */
2927 	return 0;
2928 }
2929 
2930 /* drop refcnt of maps used by the rejected program */
2931 static void release_maps(struct bpf_verifier_env *env)
2932 {
2933 	int i;
2934 
2935 	for (i = 0; i < env->used_map_cnt; i++)
2936 		bpf_map_put(env->used_maps[i]);
2937 }
2938 
2939 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
2940 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
2941 {
2942 	struct bpf_insn *insn = env->prog->insnsi;
2943 	int insn_cnt = env->prog->len;
2944 	int i;
2945 
2946 	for (i = 0; i < insn_cnt; i++, insn++)
2947 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2948 			insn->src_reg = 0;
2949 }
2950 
2951 /* convert load instructions that access fields of 'struct __sk_buff'
2952  * into sequence of instructions that access fields of 'struct sk_buff'
2953  */
2954 static int convert_ctx_accesses(struct bpf_verifier_env *env)
2955 {
2956 	const struct bpf_verifier_ops *ops = env->prog->aux->ops;
2957 	const int insn_cnt = env->prog->len;
2958 	struct bpf_insn insn_buf[16], *insn;
2959 	struct bpf_prog *new_prog;
2960 	enum bpf_access_type type;
2961 	int i, cnt, delta = 0;
2962 
2963 	if (ops->gen_prologue) {
2964 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
2965 					env->prog);
2966 		if (cnt >= ARRAY_SIZE(insn_buf)) {
2967 			verbose("bpf verifier is misconfigured\n");
2968 			return -EINVAL;
2969 		} else if (cnt) {
2970 			new_prog = bpf_patch_insn_single(env->prog, 0,
2971 							 insn_buf, cnt);
2972 			if (!new_prog)
2973 				return -ENOMEM;
2974 			env->prog = new_prog;
2975 			delta += cnt - 1;
2976 		}
2977 	}
2978 
2979 	if (!ops->convert_ctx_access)
2980 		return 0;
2981 
2982 	insn = env->prog->insnsi + delta;
2983 
2984 	for (i = 0; i < insn_cnt; i++, insn++) {
2985 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
2986 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
2987 			type = BPF_READ;
2988 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
2989 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
2990 			type = BPF_WRITE;
2991 		else
2992 			continue;
2993 
2994 		if (env->insn_aux_data[i].ptr_type != PTR_TO_CTX)
2995 			continue;
2996 
2997 		cnt = ops->convert_ctx_access(type, insn->dst_reg, insn->src_reg,
2998 					      insn->off, insn_buf, env->prog);
2999 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3000 			verbose("bpf verifier is misconfigured\n");
3001 			return -EINVAL;
3002 		}
3003 
3004 		new_prog = bpf_patch_insn_single(env->prog, i + delta, insn_buf,
3005 						 cnt);
3006 		if (!new_prog)
3007 			return -ENOMEM;
3008 
3009 		delta += cnt - 1;
3010 
3011 		/* keep walking new program and skip insns we just inserted */
3012 		env->prog = new_prog;
3013 		insn      = new_prog->insnsi + i + delta;
3014 	}
3015 
3016 	return 0;
3017 }
3018 
3019 static void free_states(struct bpf_verifier_env *env)
3020 {
3021 	struct bpf_verifier_state_list *sl, *sln;
3022 	int i;
3023 
3024 	if (!env->explored_states)
3025 		return;
3026 
3027 	for (i = 0; i < env->prog->len; i++) {
3028 		sl = env->explored_states[i];
3029 
3030 		if (sl)
3031 			while (sl != STATE_LIST_MARK) {
3032 				sln = sl->next;
3033 				kfree(sl);
3034 				sl = sln;
3035 			}
3036 	}
3037 
3038 	kfree(env->explored_states);
3039 }
3040 
3041 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
3042 {
3043 	char __user *log_ubuf = NULL;
3044 	struct bpf_verifier_env *env;
3045 	int ret = -EINVAL;
3046 
3047 	if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
3048 		return -E2BIG;
3049 
3050 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
3051 	 * allocate/free it every time bpf_check() is called
3052 	 */
3053 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3054 	if (!env)
3055 		return -ENOMEM;
3056 
3057 	env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3058 				     (*prog)->len);
3059 	ret = -ENOMEM;
3060 	if (!env->insn_aux_data)
3061 		goto err_free_env;
3062 	env->prog = *prog;
3063 
3064 	/* grab the mutex to protect few globals used by verifier */
3065 	mutex_lock(&bpf_verifier_lock);
3066 
3067 	if (attr->log_level || attr->log_buf || attr->log_size) {
3068 		/* user requested verbose verifier output
3069 		 * and supplied buffer to store the verification trace
3070 		 */
3071 		log_level = attr->log_level;
3072 		log_ubuf = (char __user *) (unsigned long) attr->log_buf;
3073 		log_size = attr->log_size;
3074 		log_len = 0;
3075 
3076 		ret = -EINVAL;
3077 		/* log_* values have to be sane */
3078 		if (log_size < 128 || log_size > UINT_MAX >> 8 ||
3079 		    log_level == 0 || log_ubuf == NULL)
3080 			goto err_unlock;
3081 
3082 		ret = -ENOMEM;
3083 		log_buf = vmalloc(log_size);
3084 		if (!log_buf)
3085 			goto err_unlock;
3086 	} else {
3087 		log_level = 0;
3088 	}
3089 
3090 	ret = replace_map_fd_with_map_ptr(env);
3091 	if (ret < 0)
3092 		goto skip_full_check;
3093 
3094 	env->explored_states = kcalloc(env->prog->len,
3095 				       sizeof(struct bpf_verifier_state_list *),
3096 				       GFP_USER);
3097 	ret = -ENOMEM;
3098 	if (!env->explored_states)
3099 		goto skip_full_check;
3100 
3101 	ret = check_cfg(env);
3102 	if (ret < 0)
3103 		goto skip_full_check;
3104 
3105 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3106 
3107 	ret = do_check(env);
3108 
3109 skip_full_check:
3110 	while (pop_stack(env, NULL) >= 0);
3111 	free_states(env);
3112 
3113 	if (ret == 0)
3114 		/* program is valid, convert *(u32*)(ctx + off) accesses */
3115 		ret = convert_ctx_accesses(env);
3116 
3117 	if (log_level && log_len >= log_size - 1) {
3118 		BUG_ON(log_len >= log_size);
3119 		/* verifier log exceeded user supplied buffer */
3120 		ret = -ENOSPC;
3121 		/* fall through to return what was recorded */
3122 	}
3123 
3124 	/* copy verifier log back to user space including trailing zero */
3125 	if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
3126 		ret = -EFAULT;
3127 		goto free_log_buf;
3128 	}
3129 
3130 	if (ret == 0 && env->used_map_cnt) {
3131 		/* if program passed verifier, update used_maps in bpf_prog_info */
3132 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
3133 							  sizeof(env->used_maps[0]),
3134 							  GFP_KERNEL);
3135 
3136 		if (!env->prog->aux->used_maps) {
3137 			ret = -ENOMEM;
3138 			goto free_log_buf;
3139 		}
3140 
3141 		memcpy(env->prog->aux->used_maps, env->used_maps,
3142 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
3143 		env->prog->aux->used_map_cnt = env->used_map_cnt;
3144 
3145 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
3146 		 * bpf_ld_imm64 instructions
3147 		 */
3148 		convert_pseudo_ld_imm64(env);
3149 	}
3150 
3151 free_log_buf:
3152 	if (log_level)
3153 		vfree(log_buf);
3154 	if (!env->prog->aux->used_maps)
3155 		/* if we didn't copy map pointers into bpf_prog_info, release
3156 		 * them now. Otherwise free_bpf_prog_info() will release them.
3157 		 */
3158 		release_maps(env);
3159 	*prog = env->prog;
3160 err_unlock:
3161 	mutex_unlock(&bpf_verifier_lock);
3162 	vfree(env->insn_aux_data);
3163 err_free_env:
3164 	kfree(env);
3165 	return ret;
3166 }
3167 
3168 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
3169 		 void *priv)
3170 {
3171 	struct bpf_verifier_env *env;
3172 	int ret;
3173 
3174 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3175 	if (!env)
3176 		return -ENOMEM;
3177 
3178 	env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3179 				     prog->len);
3180 	ret = -ENOMEM;
3181 	if (!env->insn_aux_data)
3182 		goto err_free_env;
3183 	env->prog = prog;
3184 	env->analyzer_ops = ops;
3185 	env->analyzer_priv = priv;
3186 
3187 	/* grab the mutex to protect few globals used by verifier */
3188 	mutex_lock(&bpf_verifier_lock);
3189 
3190 	log_level = 0;
3191 
3192 	env->explored_states = kcalloc(env->prog->len,
3193 				       sizeof(struct bpf_verifier_state_list *),
3194 				       GFP_KERNEL);
3195 	ret = -ENOMEM;
3196 	if (!env->explored_states)
3197 		goto skip_full_check;
3198 
3199 	ret = check_cfg(env);
3200 	if (ret < 0)
3201 		goto skip_full_check;
3202 
3203 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3204 
3205 	ret = do_check(env);
3206 
3207 skip_full_check:
3208 	while (pop_stack(env, NULL) >= 0);
3209 	free_states(env);
3210 
3211 	mutex_unlock(&bpf_verifier_lock);
3212 	vfree(env->insn_aux_data);
3213 err_free_env:
3214 	kfree(env);
3215 	return ret;
3216 }
3217 EXPORT_SYMBOL_GPL(bpf_analyzer);
3218