xref: /linux/include/linux/bpf_verifier.h (revision 5a8cd539ac19f7a68e68e1d25ef9ca2ff55b8500)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #ifndef _LINUX_BPF_VERIFIER_H
5 #define _LINUX_BPF_VERIFIER_H 1
6 
7 #include <linux/bpf.h> /* for enum bpf_reg_type */
8 #include <linux/btf.h> /* for struct btf and btf_id() */
9 #include <linux/filter.h> /* for MAX_BPF_STACK */
10 #include <linux/tnum.h>
11 #include <linux/cnum.h>
12 
13 /* Maximum variable offset umax_value permitted when resolving memory accesses.
14  * In practice this is far bigger than any realistic pointer offset; this limit
15  * ensures that umax_value + (int)off + (int)size cannot overflow a u64.
16  */
17 #define BPF_MAX_VAR_OFF	(1 << 29)
18 /* Maximum variable size permitted for ARG_MEM_SIZE[_OR_ZERO].  This ensures
19  * that converting umax_value to int cannot overflow.
20  */
21 #define BPF_MAX_VAR_SIZ	(1 << 29)
22 /* size of tmp_str_buf in bpf_verifier.
23  * we need at least 306 bytes to fit full stack mask representation
24  * (in the "-8,-16,...,-512" form)
25  */
26 #define TMP_STR_BUF_LEN 320
27 /* Patch buffer size */
28 #define INSN_BUF_SIZE 32
29 
30 #define ITER_PREFIX "bpf_iter_"
31 
32 enum bpf_iter_state {
33 	BPF_ITER_STATE_INVALID, /* for non-first slot */
34 	BPF_ITER_STATE_ACTIVE,
35 	BPF_ITER_STATE_DRAINED,
36 };
37 
38 struct bpf_reg_state {
39 	/* Ordering of fields matters.  See states_equal() */
40 	enum bpf_reg_type type;
41 	/*
42 	 * Constant delta between "linked" scalars with the same ID.
43 	 */
44 	s32 delta;
45 	union {
46 		/* valid when type == PTR_TO_PACKET */
47 		int range;
48 
49 		/* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
50 		 *   PTR_TO_MAP_VALUE_OR_NULL
51 		 */
52 		struct {
53 			struct bpf_map *map_ptr;
54 			/* To distinguish map lookups from outer map
55 			 * the map_uid is non-zero for registers
56 			 * pointing to inner maps.
57 			 */
58 			u32 map_uid;
59 		};
60 
61 		/* for PTR_TO_BTF_ID */
62 		struct {
63 			struct btf *btf;
64 			u32 btf_id;
65 		};
66 
67 		struct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */
68 			u32 mem_size;
69 		};
70 
71 		/* For dynptr stack slots */
72 		struct {
73 			enum bpf_dynptr_type type;
74 			/* A dynptr is 16 bytes so it takes up 2 stack slots.
75 			 * We need to track which slot is the first slot
76 			 * to protect against cases where the user may try to
77 			 * pass in an address starting at the second slot of the
78 			 * dynptr.
79 			 */
80 			bool first_slot;
81 		} dynptr;
82 
83 		/* For bpf_iter stack slots */
84 		struct {
85 			/* BTF container and BTF type ID describing
86 			 * struct bpf_iter_<type> of an iterator state
87 			 */
88 			struct btf *btf;
89 			u32 btf_id;
90 			/* packing following two fields to fit iter state into 16 bytes */
91 			enum bpf_iter_state state:2;
92 			int depth:30;
93 		} iter;
94 
95 		/* For irq stack slots */
96 		struct {
97 			enum {
98 				IRQ_NATIVE_KFUNC,
99 				IRQ_LOCK_KFUNC,
100 			} kfunc_class;
101 		} irq;
102 
103 		/* Max size from any of the above. */
104 		struct {
105 			unsigned long raw1;
106 			unsigned long raw2;
107 		} raw;
108 
109 		u32 subprogno; /* for PTR_TO_FUNC */
110 	};
111 	/* For scalar types (SCALAR_VALUE), this represents our knowledge of
112 	 * the actual value.
113 	 * For pointer types, this represents the variable part of the offset
114 	 * from the pointed-to object, and is shared with all bpf_reg_states
115 	 * with the same id as us.
116 	 */
117 	struct tnum var_off;
118 	/* Used to determine if any memory access using this register will
119 	 * result in a bad access.
120 	 * These refer to the same value as var_off, not necessarily the actual
121 	 * contents of the register.
122 	 */
123 	struct cnum64 r64; /* 64-bit range as circular number */
124 	struct cnum32 r32; /* 32-bit range as circular number */
125 	/* For PTR_TO_PACKET, used to find other pointers with the same variable
126 	 * offset, so they can share range knowledge.
127 	 * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we
128 	 * came from, when one is tested for != NULL.
129 	 * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation
130 	 * for the purpose of tracking that it's freed.
131 	 * For PTR_TO_SOCKET this is used to share which pointers retain the
132 	 * same reference to the socket, to determine proper reference freeing.
133 	 * For stack slots that are dynptrs, this is used to track references to
134 	 * the dynptr to determine proper reference freeing.
135 	 * Similarly to dynptrs, we use ID to track "belonging" of a reference
136 	 * to a specific instance of bpf_iter.
137 	 */
138 	/*
139 	 * Upper bit of ID is used to remember relationship between "linked"
140 	 * registers. Example:
141 	 * r1 = r2;    both will have r1->id == r2->id == N
142 	 * r1 += 10;   r1->id == N | BPF_ADD_CONST and r1->delta == 10
143 	 * r3 = r2;    both will have r3->id == r2->id == N
144 	 * w3 += 10;   r3->id == N | BPF_ADD_CONST32 and r3->delta == 10
145 	 */
146 #define BPF_ADD_CONST64 (1U << 31)
147 #define BPF_ADD_CONST32 (1U << 30)
148 #define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32)
149 	u32 id;
150 	/*
151 	 * Tracks the parent object this register was derived from.
152 	 * Used for cascading invalidation: when the parent object is
153 	 * released or invalidated, all registers with matching parent_id
154 	 * are also invalidated. For example, a slice from bpf_dynptr_data()
155 	 * gets parent_id set to the dynptr's id.
156 	 */
157 	u32 parent_id;
158 	/* Inside the callee two registers can be both PTR_TO_STACK like
159 	 * R1=fp-8 and R2=fp-8, but one of them points to this function stack
160 	 * while another to the caller's stack. To differentiate them 'frameno'
161 	 * is used which is an index in bpf_verifier_state->frame[] array
162 	 * pointing to bpf_func_state.
163 	 */
164 	u32 frameno;
165 	/* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
166 	bool precise;
167 };
168 
reg_smin(const struct bpf_reg_state * reg)169 static inline s64 reg_smin(const struct bpf_reg_state *reg)
170 {
171 	return cnum64_smin(reg->r64);
172 }
173 
reg_smax(const struct bpf_reg_state * reg)174 static inline s64 reg_smax(const struct bpf_reg_state *reg)
175 {
176 	return cnum64_smax(reg->r64);
177 }
178 
reg_umin(const struct bpf_reg_state * reg)179 static inline u64 reg_umin(const struct bpf_reg_state *reg)
180 {
181 	return cnum64_umin(reg->r64);
182 }
183 
reg_umax(const struct bpf_reg_state * reg)184 static inline u64 reg_umax(const struct bpf_reg_state *reg)
185 {
186 	return cnum64_umax(reg->r64);
187 }
188 
reg_s32_min(const struct bpf_reg_state * reg)189 static inline s32 reg_s32_min(const struct bpf_reg_state *reg)
190 {
191 	return cnum32_smin(reg->r32);
192 }
193 
reg_s32_max(const struct bpf_reg_state * reg)194 static inline s32 reg_s32_max(const struct bpf_reg_state *reg)
195 {
196 	return cnum32_smax(reg->r32);
197 }
198 
reg_u32_min(const struct bpf_reg_state * reg)199 static inline u32 reg_u32_min(const struct bpf_reg_state *reg)
200 {
201 	return cnum32_umin(reg->r32);
202 }
203 
reg_u32_max(const struct bpf_reg_state * reg)204 static inline u32 reg_u32_max(const struct bpf_reg_state *reg)
205 {
206 	return cnum32_umax(reg->r32);
207 }
208 
reg_set_srange32(struct bpf_reg_state * reg,s32 smin,s32 smax)209 static inline void reg_set_srange32(struct bpf_reg_state *reg, s32 smin, s32 smax)
210 {
211 	reg->r32 = cnum32_from_srange(smin, smax);
212 }
213 
reg_set_urange32(struct bpf_reg_state * reg,u32 umin,u32 umax)214 static inline void reg_set_urange32(struct bpf_reg_state *reg, u32 umin, u32 umax)
215 {
216 	reg->r32 = cnum32_from_urange(umin, umax);
217 }
218 
reg_set_srange64(struct bpf_reg_state * reg,s64 smin,s64 smax)219 static inline void reg_set_srange64(struct bpf_reg_state *reg, s64 smin, s64 smax)
220 {
221 	reg->r64 = cnum64_from_srange(smin, smax);
222 }
223 
reg_set_urange64(struct bpf_reg_state * reg,u64 umin,u64 umax)224 static inline void reg_set_urange64(struct bpf_reg_state *reg, u64 umin, u64 umax)
225 {
226 	reg->r64 = cnum64_from_urange(umin, umax);
227 }
228 
229 enum bpf_stack_slot_type {
230 	STACK_INVALID,    /* nothing was stored in this stack slot */
231 	STACK_SPILL,      /* register spilled into stack */
232 	STACK_MISC,	  /* BPF program wrote some data into this slot */
233 	STACK_ZERO,	  /* BPF program wrote constant zero */
234 	/* A dynptr is stored in this stack slot. The type of dynptr
235 	 * is stored in bpf_stack_state->spilled_ptr.dynptr.type
236 	 */
237 	STACK_DYNPTR,
238 	STACK_ITER,
239 	STACK_IRQ_FLAG,
240 	STACK_POISON,
241 };
242 
243 #define BPF_REG_SIZE 8	/* size of eBPF register in bytes */
244 
245 /* 4-byte stack slot granularity for liveness analysis */
246 #define BPF_HALF_REG_SIZE	4
247 #define STACK_SLOT_SZ		4
248 #define STACK_SLOTS		(MAX_BPF_STACK / BPF_HALF_REG_SIZE)	/* 128 */
249 
250 typedef struct {
251 	u64 v[2];
252 } spis_t;
253 
254 #define SPIS_ZERO	((spis_t){})
255 #define SPIS_ALL	((spis_t){{ U64_MAX, U64_MAX }})
256 
spis_is_zero(spis_t s)257 static inline bool spis_is_zero(spis_t s)
258 {
259 	return s.v[0] == 0 && s.v[1] == 0;
260 }
261 
spis_equal(spis_t a,spis_t b)262 static inline bool spis_equal(spis_t a, spis_t b)
263 {
264 	return a.v[0] == b.v[0] && a.v[1] == b.v[1];
265 }
266 
spis_or(spis_t a,spis_t b)267 static inline spis_t spis_or(spis_t a, spis_t b)
268 {
269 	return (spis_t){{ a.v[0] | b.v[0], a.v[1] | b.v[1] }};
270 }
271 
spis_and(spis_t a,spis_t b)272 static inline spis_t spis_and(spis_t a, spis_t b)
273 {
274 	return (spis_t){{ a.v[0] & b.v[0], a.v[1] & b.v[1] }};
275 }
276 
spis_not(spis_t s)277 static inline spis_t spis_not(spis_t s)
278 {
279 	return (spis_t){{ ~s.v[0], ~s.v[1] }};
280 }
281 
spis_test_bit(spis_t s,u32 slot)282 static inline bool spis_test_bit(spis_t s, u32 slot)
283 {
284 	return s.v[slot / 64] & BIT_ULL(slot % 64);
285 }
286 
spis_or_range(spis_t * mask,u32 lo,u32 hi)287 static inline void spis_or_range(spis_t *mask, u32 lo, u32 hi)
288 {
289 	u32 w;
290 
291 	for (w = lo; w <= hi && w < STACK_SLOTS; w++)
292 		mask->v[w / 64] |= BIT_ULL(w % 64);
293 }
294 
295 #define BPF_REGMASK_ARGS ((1 << BPF_REG_1) | (1 << BPF_REG_2) | \
296 			  (1 << BPF_REG_3) | (1 << BPF_REG_4) | \
297 			  (1 << BPF_REG_5))
298 
299 #define BPF_MAIN_FUNC (-1)
300 
301 #define BPF_DYNPTR_SIZE		sizeof(struct bpf_dynptr_kern)
302 #define BPF_DYNPTR_NR_SLOTS		(BPF_DYNPTR_SIZE / BPF_REG_SIZE)
303 
304 struct bpf_stack_state {
305 	struct bpf_reg_state spilled_ptr;
306 	u8 slot_type[BPF_REG_SIZE];
307 };
308 
309 struct bpf_reference_state {
310 	/* Each reference object has a type. Ensure REF_TYPE_PTR is zero to
311 	 * default to pointer reference on zero initialization of a state.
312 	 */
313 	enum ref_state_type {
314 		REF_TYPE_PTR		= (1 << 1),
315 		REF_TYPE_IRQ		= (1 << 2),
316 		REF_TYPE_LOCK		= (1 << 3),
317 		REF_TYPE_RES_LOCK 	= (1 << 4),
318 		REF_TYPE_RES_LOCK_IRQ	= (1 << 5),
319 		REF_TYPE_LOCK_MASK	= REF_TYPE_LOCK | REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ,
320 	} type;
321 	/* Track each reference created with a unique id, even if the same
322 	 * instruction creates the reference multiple times (eg, via CALL).
323 	 */
324 	int id;
325 	/* Instruction where the allocation of this reference occurred. This
326 	 * is used purely to inform the user of a reference leak.
327 	 */
328 	int insn_idx;
329 	union {
330 		/* For REF_TYPE_PTR */
331 		int parent_id;
332 		/* Use to keep track of the source object of a lock, to ensure
333 		 * it matches on unlock.
334 		 */
335 		void *ptr;
336 	};
337 };
338 
339 struct bpf_retval_range {
340 	s32 minval;
341 	s32 maxval;
342 	bool return_32bit;
343 };
344 
345 /* state of the program:
346  * type of all registers and stack info
347  */
348 struct bpf_func_state {
349 	struct bpf_reg_state regs[MAX_BPF_REG];
350 	/* index of call instruction that called into this func */
351 	int callsite;
352 	/* stack frame number of this function state from pov of
353 	 * enclosing bpf_verifier_state.
354 	 * 0 = main function, 1 = first callee.
355 	 */
356 	u32 frameno;
357 	/*
358 	 * Unique diagnostic identity for this function invocation. Frame depth is
359 	 * reused after returns, while this ID is preserved across state clones.
360 	 */
361 	u32 diag_frame_id;
362 	/* subprog number == index within subprog_info
363 	 * zero == main subprog
364 	 */
365 	u32 subprogno;
366 	/* Every bpf_timer_start will increment async_entry_cnt.
367 	 * It's used to distinguish:
368 	 * void foo(void) { for(;;); }
369 	 * void foo(void) { bpf_timer_set_callback(,foo); }
370 	 */
371 	u32 async_entry_cnt;
372 	struct bpf_retval_range callback_ret_range;
373 	bool in_callback_fn;
374 	bool in_async_callback_fn;
375 	bool in_exception_callback_fn;
376 	bool no_stack_arg_load;
377 	/* For callback calling functions that limit number of possible
378 	 * callback executions (e.g. bpf_loop) keeps track of current
379 	 * simulated iteration number.
380 	 * Value in frame N refers to number of times callback with frame
381 	 * N+1 was simulated, e.g. for the following call:
382 	 *
383 	 *   bpf_loop(..., fn, ...); | suppose current frame is N
384 	 *                           | fn would be simulated in frame N+1
385 	 *                           | number of simulations is tracked in frame N
386 	 */
387 	u32 callback_depth;
388 	/* Instructions processed in this frame and callees on the current path. */
389 	u32 insns_subtotal;
390 
391 	/* The following fields should be last. See copy_func_state() */
392 	/* The state of the stack. Each element of the array describes BPF_REG_SIZE
393 	 * (i.e. 8) bytes worth of stack memory.
394 	 * stack[0] represents bytes [*(r10-8)..*(r10-1)]
395 	 * stack[1] represents bytes [*(r10-16)..*(r10-9)]
396 	 * ...
397 	 * stack[allocated_stack/8 - 1] represents [*(r10-allocated_stack)..*(r10-allocated_stack+7)]
398 	 */
399 	struct bpf_stack_state *stack;
400 	/* Size of the current stack, in bytes. The stack state is tracked below, in
401 	 * `stack`. allocated_stack is always a multiple of BPF_REG_SIZE.
402 	 */
403 	int allocated_stack;
404 
405 	u16 out_stack_arg_cnt; /* Number of outgoing on-stack argument slots */
406 	struct bpf_reg_state *stack_arg_regs; /* Outgoing on-stack arguments */
407 };
408 
409 #define MAX_CALL_FRAMES 16
410 
411 /* instruction history flags, used in bpf_jmp_history_entry.flags field.
412  * Frame number and SPI are stored in dedicated fields of bpf_jmp_history_entry.
413  */
414 enum {
415 	INSN_F_STACK_ACCESS = BIT(0),
416 
417 	INSN_F_DST_REG_STACK = BIT(1), /* dst_reg is PTR_TO_STACK */
418 	INSN_F_SRC_REG_STACK = BIT(2), /* src_reg is PTR_TO_STACK */
419 
420 	INSN_F_STACK_ARG_ACCESS = BIT(3),
421 };
422 
423 struct bpf_jmp_history_entry {
424 	/* insn idx can't be bigger than 1 million */
425 	u32 idx : 20;
426 	u32 frame : 4;	/* stack access frame number */
427 	u32 spi : 6;	/* stack slot index (0..63) */
428 	u32 : 2;
429 	u32 prev_idx : 20;
430 	/* special INSN_F_xxx flags */
431 	u32 flags : 4;
432 	u32 : 8;
433 	/*
434 	 * additional registers that need precision tracking when this
435 	 * jump is backtracked, vector of five 11-bit records
436 	 */
437 	u64 linked_regs;
438 };
439 
440 static_assert(MAX_CALL_FRAMES <= (1 << 4));
441 static_assert(MAX_BPF_STACK / 8 <= (1 << 6));
442 
443 /* Maximum number of bpf_reg_state objects that can exist at once */
444 #define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS)
445 #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE + \
446 			  MAX_STACK_ARG_SLOTS) * MAX_CALL_FRAMES)
447 struct bpf_verifier_state {
448 	/* call stack tracking */
449 	struct bpf_func_state *frame[MAX_CALL_FRAMES];
450 	struct bpf_verifier_state *parent;
451 	/* Acquired reference states */
452 	struct bpf_reference_state *refs;
453 	/*
454 	 * 'branches' field is the number of branches left to explore:
455 	 * 0 - all possible paths from this state reached bpf_exit or
456 	 * were safely pruned
457 	 * 1 - at least one path is being explored.
458 	 * This state hasn't reached bpf_exit
459 	 * 2 - at least two paths are being explored.
460 	 * This state is an immediate parent of two children.
461 	 * One is fallthrough branch with branches==1 and another
462 	 * state is pushed into stack (to be explored later) also with
463 	 * branches==1. The parent of this state has branches==1.
464 	 * The verifier state tree connected via 'parent' pointer looks like:
465 	 * 1
466 	 * 1
467 	 * 2 -> 1 (first 'if' pushed into stack)
468 	 * 1
469 	 * 2 -> 1 (second 'if' pushed into stack)
470 	 * 1
471 	 * 1
472 	 * 1 bpf_exit.
473 	 *
474 	 * Once do_check() reaches bpf_exit, it calls update_branch_counts()
475 	 * and the verifier state tree will look:
476 	 * 1
477 	 * 1
478 	 * 2 -> 1 (first 'if' pushed into stack)
479 	 * 1
480 	 * 1 -> 1 (second 'if' pushed into stack)
481 	 * 0
482 	 * 0
483 	 * 0 bpf_exit.
484 	 * After pop_stack() the do_check() will resume at second 'if'.
485 	 *
486 	 * If is_state_visited() sees a state with branches > 0 it means
487 	 * there is a loop. If such state is exactly equal to the current state
488 	 * it's an infinite loop. Note states_equal() checks for states
489 	 * equivalency, so two states being 'states_equal' does not mean
490 	 * infinite loop. The exact comparison is provided by
491 	 * states_maybe_looping() function. It's a stronger pre-check and
492 	 * much faster than states_equal().
493 	 *
494 	 * This algorithm may not find all possible infinite loops or
495 	 * loop iteration count may be too high.
496 	 * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in.
497 	 */
498 	u32 branches;
499 	u32 insn_idx;
500 	u32 curframe;
501 
502 	u32 acquired_refs;
503 	u32 active_locks;
504 	u32 active_preempt_locks;
505 	u32 active_irq_id;
506 	u32 active_lock_id;
507 	void *active_lock_ptr;
508 	u32 active_rcu_locks;
509 
510 	bool speculative;
511 	bool in_sleepable;
512 
513 	/* first and last insn idx of this verifier state */
514 	u32 first_insn_idx;
515 	u32 last_insn_idx;
516 	/* if this state is a backedge state then equal_state
517 	 * records cached state to which this state is equal.
518 	 */
519 	struct bpf_verifier_state *equal_state;
520 	/* jmp history recorded from first to last.
521 	 * backtracking is using it to go from last to first.
522 	 * For most states jmp_history_cnt is [0-3].
523 	 * For loops can go up to ~40.
524 	 */
525 	struct bpf_jmp_history_entry *jmp_history;
526 	u32 jmp_history_cnt;
527 	u32 dfs_depth;
528 	u32 callback_unroll_depth;
529 	u32 may_goto_depth;
530 };
531 
532 static inline struct bpf_reg_state *
bpf_get_spilled_reg(int slot,struct bpf_func_state * frame,u32 mask)533 bpf_get_spilled_reg(int slot, struct bpf_func_state *frame, u32 mask)
534 {
535 	if (slot < frame->allocated_stack / BPF_REG_SIZE &&
536 	    (1 << frame->stack[slot].slot_type[BPF_REG_SIZE - 1]) & mask)
537 		return &frame->stack[slot].spilled_ptr;
538 	return NULL;
539 }
540 
541 static inline struct bpf_reg_state *
bpf_get_spilled_stack_arg(int slot,struct bpf_func_state * frame)542 bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame)
543 {
544 	if (slot < frame->out_stack_arg_cnt &&
545 	    frame->stack_arg_regs[slot].type != NOT_INIT)
546 		return &frame->stack_arg_regs[slot];
547 	return NULL;
548 }
549 
550 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */
551 #define bpf_for_each_spilled_reg(iter, frame, reg, mask)			\
552 	for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask);		\
553 	     iter < frame->allocated_stack / BPF_REG_SIZE;		\
554 	     iter++, reg = bpf_get_spilled_reg(iter, frame, mask))
555 
556 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled stack arg. */
557 #define bpf_for_each_spilled_stack_arg(iter, frame, reg)               \
558 	for (iter = 0, reg = bpf_get_spilled_stack_arg(iter, frame);   \
559 	     iter < frame->out_stack_arg_cnt;                          \
560 	     iter++, reg = bpf_get_spilled_stack_arg(iter, frame))
561 
562 #define bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, __stack, __mask, __expr)   \
563 	({                                                               \
564 		struct bpf_verifier_state *___vstate = __vst;            \
565 		int ___i, ___j;                                          \
566 		for (___i = 0; ___i <= ___vstate->curframe; ___i++) {    \
567 			struct bpf_reg_state *___regs;                   \
568 			__state = ___vstate->frame[___i];                \
569 			___regs = __state->regs;                         \
570 			__stack = NULL;                                  \
571 			for (___j = 0; ___j < MAX_BPF_REG; ___j++) {     \
572 				__reg = &___regs[___j];                  \
573 				(void)(__expr);                          \
574 			}                                                \
575 			bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \
576 				if (!__reg)                              \
577 					continue;                        \
578 				__stack = &__state->stack[___j];         \
579 				(void)(__expr);                          \
580 			}                                                \
581 			__stack = NULL;                                  \
582 			bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \
583 				if (!__reg)                              \
584 					continue;                        \
585 				(void)(__expr);                          \
586 			}						 \
587 		}                                                        \
588 		(void)__stack;                                           \
589 	})
590 
591 /* Invoke __expr over regsiters in __vst, setting __state and __reg */
592 #define bpf_for_each_reg_in_vstate(__vst, __state, __reg, __expr)		\
593 	({									\
594 		struct bpf_stack_state * ___stack;                        	\
595 		(void)___stack;							\
596 		bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, ___stack,\
597 						1 << STACK_SPILL, __expr);	\
598 	})
599 
600 /* linked list of verifier states used to prune search */
601 struct bpf_verifier_state_list {
602 	struct bpf_verifier_state state;
603 	struct list_head node;
604 	u32 miss_cnt;
605 	u32 hit_cnt:31;
606 	u32 in_free_list:1;
607 };
608 
609 struct bpf_loop_inline_state {
610 	unsigned int initialized:1; /* set to true upon first entry */
611 	unsigned int fit_for_inline:1; /* true if callback function is the same
612 					* at each call and flags are always zero
613 					*/
614 	u32 callback_subprogno; /* valid when fit_for_inline is true */
615 };
616 
617 /* pointer and state for maps */
618 struct bpf_map_ptr_state {
619 	struct bpf_map *map_ptr;
620 	bool poison;
621 	bool unpriv;
622 };
623 
624 /* Possible states for alu_state member. */
625 #define BPF_ALU_SANITIZE_SRC		(1U << 0)
626 #define BPF_ALU_SANITIZE_DST		(1U << 1)
627 #define BPF_ALU_NEG_VALUE		(1U << 2)
628 #define BPF_ALU_NON_POINTER		(1U << 3)
629 #define BPF_ALU_IMMEDIATE		(1U << 4)
630 #define BPF_ALU_SANITIZE		(BPF_ALU_SANITIZE_SRC | \
631 					 BPF_ALU_SANITIZE_DST)
632 
633 /*
634  * An array of BPF instructions.
635  * Primary usage: return value of bpf_insn_successors.
636  */
637 struct bpf_iarray {
638 	int cnt;
639 	u32 items[];
640 };
641 
642 struct bpf_insn_aux_data {
643 	union {
644 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
645 		struct bpf_map_ptr_state map_ptr_state;
646 		s32 call_imm;			/* saved imm field of call insn */
647 		u32 alu_limit;			/* limit for add/sub register with pointer */
648 		struct {
649 			u32 map_index;		/* index into used_maps[] */
650 			u32 map_off;		/* offset from value base address */
651 		};
652 		struct {
653 			enum bpf_reg_type reg_type;	/* type of pseudo_btf_id */
654 			union {
655 				struct {
656 					struct btf *btf;
657 					u32 btf_id;	/* btf_id for struct typed var */
658 				};
659 				u32 mem_size;	/* mem_size for non-struct typed var */
660 			};
661 		} btf_var;
662 		/* if instruction is a call to bpf_loop this field tracks
663 		 * the state of the relevant registers to make decision about inlining
664 		 */
665 		struct bpf_loop_inline_state loop_inline_state;
666 	};
667 	union {
668 		/* remember the size of type passed to bpf_obj_new to rewrite R1 */
669 		u64 obj_new_size;
670 		/* remember the offset of node field within type to rewrite */
671 		u64 insert_off;
672 	};
673 	struct bpf_iarray *jt;	/* jump table for gotox or bpf_tailcall call instruction */
674 	struct btf_struct_meta *kptr_struct_meta;
675 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
676 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
677 	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
678 	bool nospec; /* do not execute this instruction speculatively */
679 	bool nospec_result; /* result is unsafe under speculation, nospec must follow */
680 	bool zext_dst; /* this insn zero extends dst reg */
681 	bool needs_zext; /* alu op needs to clear upper bits */
682 	bool non_sleepable; /* helper/kfunc may be called from non-sleepable context */
683 	bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */
684 	bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */
685 	u8 alu_state; /* used in combination with alu_limit */
686 	/* true if STX or LDX instruction is a part of a spill/fill
687 	 * pattern for a bpf_fastcall call.
688 	 */
689 	u8 fastcall_pattern:1;
690 	/* for CALL instructions, a number of spill/fill pairs in the
691 	 * bpf_fastcall pattern.
692 	 */
693 	u8 fastcall_spills_num:3;
694 	u8 arg_prog:4;
695 
696 	/* below fields are initialized once */
697 	unsigned int orig_idx; /* original instruction index */
698 	u32 jmp_point:1;
699 	u32 prune_point:1;
700 	/* ensure we check state equivalence and save state checkpoint and
701 	 * this instruction, regardless of any heuristics
702 	 */
703 	u32 force_checkpoint:1;
704 	/* true if instruction is a call to a helper function that
705 	 * accepts callback function as a parameter.
706 	 */
707 	u32 calls_callback:1;
708 	u32 indirect_target:1; /* if it is an indirect jump target */
709 	/*
710 	 * CFG strongly connected component this instruction belongs to,
711 	 * zero if it is a singleton SCC.
712 	 */
713 	u32 scc;
714 	/* registers alive before this instruction. */
715 	u16 live_regs_before;
716 	/*
717 	 * Bitmask of R0-R9 that hold known values at this instruction.
718 	 * const_reg_mask: scalar constants that fit in 32 bits.
719 	 * const_reg_map_mask: map pointers, val is map_index into used_maps[].
720 	 * const_reg_subprog_mask: subprog pointers, val is subprog number.
721 	 * const_reg_vals[i] holds the 32-bit value for register i.
722 	 * Populated by compute_const_regs() pre-pass.
723 	 */
724 	u16 const_reg_mask;
725 	u16 const_reg_map_mask;
726 	u16 const_reg_subprog_mask;
727 	u32 const_reg_vals[10];
728 };
729 
730 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
731 #define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */
732 
733 #define BPF_VERIFIER_TMP_LOG_SIZE	1024
734 
735 struct bpf_verifier_log {
736 	/* Logical start and end positions of a "log window" of the verifier log.
737 	 * start_pos == 0 means we haven't truncated anything.
738 	 * Once truncation starts to happen, start_pos + len_total == end_pos,
739 	 * except during log reset situations, in which (end_pos - start_pos)
740 	 * might get smaller than len_total (see bpf_vlog_reset()).
741 	 * Generally, (end_pos - start_pos) gives number of useful data in
742 	 * user log buffer.
743 	 */
744 	u64 start_pos;
745 	u64 end_pos;
746 	char __user *ubuf;
747 	u32 level;
748 	u32 len_total;
749 	u32 len_max;
750 	char kbuf[BPF_VERIFIER_TMP_LOG_SIZE];
751 };
752 
753 #define BPF_LOG_LEVEL1	1
754 #define BPF_LOG_LEVEL2	2
755 #define BPF_LOG_STATS	4
756 #define BPF_LOG_FIXED	8
757 #define BPF_LOG_LEVEL	(BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2)
758 #define BPF_LOG_MASK	(BPF_LOG_LEVEL | BPF_LOG_STATS | BPF_LOG_FIXED)
759 #define BPF_LOG_KERNEL	(BPF_LOG_MASK + 1) /* kernel internal flag */
760 #define BPF_LOG_MIN_ALIGNMENT 8U
761 #define BPF_LOG_ALIGNMENT 40U
762 
bpf_verifier_log_needed(const struct bpf_verifier_log * log)763 static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log)
764 {
765 	return log && log->level;
766 }
767 
768 struct bpf_log_attr {
769 	char __user *ubuf;
770 	u32 size;
771 	u32 level;
772 	u32 offsetof_true_size;
773 	bpfptr_t uattr;
774 };
775 
776 int bpf_log_attr_init(struct bpf_log_attr *log, u64 log_buf, u32 log_size, u32 log_level,
777 		      u32 offsetof_log_true_size, bpfptr_t uattr, struct bpf_common_attr *common,
778 		      bpfptr_t uattr_common, u32 size_common);
779 struct bpf_verifier_log *bpf_log_attr_create_vlog(struct bpf_log_attr *attr_log,
780 						  struct bpf_common_attr *common, bpfptr_t uattr,
781 						  u32 size);
782 int bpf_log_attr_finalize(struct bpf_log_attr *attr, struct bpf_verifier_log *log);
783 
784 #define BPF_MAX_SUBPROGS 256
785 
786 struct bpf_subprog_arg_info {
787 	enum bpf_arg_type arg_type;
788 	union {
789 		u32 mem_size;
790 		u32 btf_id;
791 	};
792 };
793 
794 enum priv_stack_mode {
795 	PRIV_STACK_UNKNOWN,
796 	NO_PRIV_STACK,
797 	PRIV_STACK_ADAPTIVE,
798 };
799 
800 struct bpf_subprog_info {
801 	const char *name; /* name extracted from BTF */
802 	u32 start; /* insn idx of function entry point */
803 	u32 linfo_idx; /* The idx to the main_prog->aux->linfo */
804 	u32 postorder_start; /* The idx to the env->cfg.insn_postorder */
805 	u32 exit_idx; /* Index of one of the BPF_EXIT instructions in this subprogram */
806 	u16 stack_depth; /* max. stack depth used by this function */
807 	u16 stack_extra;
808 	u32 insns_total;
809 	u32 insns_self;
810 	/* offsets in range [stack_depth .. fastcall_stack_off)
811 	 * are used for bpf_fastcall spills and fills.
812 	 */
813 	s16 fastcall_stack_off;
814 	bool has_tail_call: 1;
815 	bool might_throw: 1;
816 	bool tail_call_reachable: 1;
817 	bool has_ld_abs: 1;
818 	bool is_cb: 1;
819 	bool is_async_cb: 1;
820 	bool is_exception_cb: 1;
821 	bool args_cached: 1;
822 	/* true if bpf_fastcall stack region is used by functions that can't be inlined */
823 	bool keep_fastcall_stack: 1;
824 	bool changes_pkt_data: 1;
825 	bool might_sleep: 1;
826 	u8 arg_cnt:4;
827 
828 	enum priv_stack_mode priv_stack_mode;
829 	struct bpf_subprog_arg_info args[MAX_BPF_FUNC_ARGS];
830 	u16 stack_arg_cnt; /* incoming + max outgoing */
831 	u16 max_out_stack_arg_cnt;
832 };
833 
bpf_in_stack_arg_cnt(const struct bpf_subprog_info * sub)834 static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub)
835 {
836 	if (sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS)
837 		return sub->arg_cnt - MAX_BPF_FUNC_REG_ARGS;
838 	return 0;
839 }
840 
841 struct bpf_diag;
842 struct bpf_verifier_env;
843 
844 struct backtrack_state {
845 	struct bpf_verifier_env *env;
846 	u32 frame;
847 	u32 reg_masks[MAX_CALL_FRAMES];
848 	u64 stack_masks[MAX_CALL_FRAMES];
849 	u8 stack_arg_masks[MAX_CALL_FRAMES];
850 };
851 
852 struct bpf_id_pair {
853 	u32 old;
854 	u32 cur;
855 };
856 
857 struct bpf_idmap {
858 	u32 tmp_id_gen;
859 	u32 cnt;
860 	struct bpf_id_pair map[BPF_ID_MAP_SIZE];
861 };
862 
863 struct bpf_idset {
864 	u32 num_ids;
865 	struct {
866 		u32 id;
867 		u32 cnt;
868 	} entries[BPF_ID_MAP_SIZE];
869 };
870 
871 /* see verifier.c:compute_scc_callchain() */
872 struct bpf_scc_callchain {
873 	/* call sites from bpf_verifier_state->frame[*]->callsite leading to this SCC */
874 	u32 callsites[MAX_CALL_FRAMES - 1];
875 	/* last frame in a chain is identified by SCC id */
876 	u32 scc;
877 };
878 
879 /* verifier state waiting for propagate_backedges() */
880 struct bpf_scc_backedge {
881 	struct bpf_scc_backedge *next;
882 	struct bpf_verifier_state state;
883 };
884 
885 struct bpf_scc_visit {
886 	struct bpf_scc_callchain callchain;
887 	/* first state in current verification path that entered SCC
888 	 * identified by the callchain
889 	 */
890 	struct bpf_verifier_state *entry_state;
891 	struct bpf_scc_backedge *backedges; /* list of backedges */
892 	u32 num_backedges;
893 };
894 
895 /* An array of bpf_scc_visit structs sharing tht same bpf_scc_callchain->scc
896  * but having different bpf_scc_callchain->callsites.
897  */
898 struct bpf_scc_info {
899 	u32 num_visits;
900 	struct bpf_scc_visit visits[];
901 };
902 
903 struct bpf_liveness;
904 
905 struct bpf_fd_array {
906 	union {
907 		struct bpf_map *map;
908 		struct btf *btf;
909 		unsigned long val;
910 	};
911 };
912 
913 /* single container for all structs
914  * one verifier_env per bpf_check() call
915  */
916 struct bpf_verifier_env {
917 	u32 insn_idx;
918 	u32 prev_insn_idx;
919 	struct bpf_prog *prog;		/* eBPF program being verified */
920 	const struct bpf_verifier_ops *ops;
921 	struct module *attach_btf_mod;	/* The owner module of prog->aux->attach_btf */
922 	struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */
923 	int stack_size;			/* number of states to be processed */
924 	bool strict_alignment;		/* perform strict pointer alignment checks */
925 	bool test_state_freq;		/* test verifier with different pruning frequency */
926 	bool test_reg_invariants;	/* fail verification on register invariants violations */
927 	struct bpf_verifier_state *cur_state; /* current verifier state */
928 	/* Search pruning optimization, array of list_heads for
929 	 * lists of struct bpf_verifier_state_list.
930 	 */
931 	struct list_head *explored_states;
932 	struct list_head free_list;	/* list of struct bpf_verifier_state_list */
933 	struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
934 	struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */
935 	struct bpf_map *insn_array_maps[MAX_USED_MAPS]; /* array of INSN_ARRAY map's to be relocated */
936 	u32 used_map_cnt;		/* number of used maps */
937 	u32 used_btf_cnt;		/* number of used BTF objects */
938 	u32 insn_array_map_cnt;		/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
939 	u32 id_gen;			/* used to generate unique reg IDs */
940 	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
941 	int exception_callback_subprog;
942 	bool explore_alu_limits;
943 	bool allow_ptr_leaks;
944 	/* Allow access to uninitialized stack memory. Writes with fixed offset are
945 	 * always allowed, so this refers to reads (with fixed or variable offset),
946 	 * to writes with variable offset and to indirect (helper) accesses.
947 	 */
948 	bool allow_uninit_stack;
949 	bool bpf_capable;
950 	bool bypass_spec_v1;
951 	bool bypass_spec_v4;
952 	bool seen_direct_write;
953 	bool seen_exception;
954 	bool signature;
955 	u32 insn_aux_data_len;
956 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
957 	const struct bpf_line_info *prev_linfo;
958 	struct bpf_verifier_log log;
959 	struct bpf_diag *diag;
960 	struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
961 	/* subprog indices sorted in topological order: leaves first, callers last */
962 	int subprog_topo_order[BPF_MAX_SUBPROGS + 2];
963 	union {
964 		struct bpf_idmap idmap_scratch;
965 		struct bpf_idset idset_scratch;
966 	};
967 	struct {
968 		int *insn_state;
969 		int *insn_stack;
970 		/*
971 		 * vector of instruction indexes sorted in post-order, grouped by subprogram,
972 		 * see bpf_subprog_info->postorder_start.
973 		 */
974 		int *insn_postorder;
975 		int cur_stack;
976 		/* current position in the insn_postorder vector */
977 		int cur_postorder;
978 	} cfg;
979 	struct backtrack_state bt;
980 	struct bpf_jmp_history_entry *cur_hist_ent;
981 	/* Per-callsite copy of parent's converged at_stack_in for cross-frame fills. */
982 	struct arg_track **callsite_at_stack;
983 	u32 pass_cnt; /* number of times do_check() was called */
984 	u32 subprog_cnt;
985 	/* number of instructions analyzed by the verifier */
986 	u32 prev_insn_processed, insn_processed;
987 	/* number of jmps, calls, exits analyzed so far */
988 	u32 prev_jmps_processed, jmps_processed;
989 	/* maximum combined stack depth */
990 	u32 max_stack_depth;
991 	/* total verification time */
992 	u64 verification_time;
993 	/* maximum number of verifier states kept in 'branching' instructions */
994 	u32 max_states_per_insn;
995 	/* total number of allocated verifier states */
996 	u32 total_states;
997 	/* some states are freed during program analysis.
998 	 * this is peak number of states. this number dominates kernel
999 	 * memory consumption during verification
1000 	 */
1001 	u32 peak_states;
1002 	/* longest register parentage chain walked for liveness marking */
1003 	u32 longest_mark_read_walk;
1004 	u32 free_list_size;
1005 	u32 explored_states_size;
1006 	u32 num_backedges;
1007 	/*
1008 	 * The program's fd_array comes in two shapes, told apart by whether
1009 	 * the caller passed fd_array_cnt. They are mutually exclusive:
1010 	 *  - continuous (fd_array_cnt given): ->fd_array holds every entry
1011 	 *    resolved to its object up front, indexed by fd_array position,
1012 	 *    with ->fd_array_cnt slots; ->fd_array_raw is unused.
1013 	 *  - sparse (no fd_array_cnt): ->fd_array is NULL, and entries are
1014 	 *    read from ->fd_array_raw (the caller's fd_array) and resolved
1015 	 *    on the spot at each reference.
1016 	 */
1017 	struct bpf_fd_array *fd_array;
1018 	u32 fd_array_cnt;
1019 	bpfptr_t fd_array_raw;
1020 
1021 	/* bit mask to keep track of whether a register has been accessed
1022 	 * since the last time the function state was printed
1023 	 */
1024 	u32 scratched_regs;
1025 	/* Same as scratched_regs but for stack slots */
1026 	u64 scratched_stack_slots;
1027 	u64 prev_log_pos, prev_insn_print_pos;
1028 	/* buffer used to temporary hold constants as scalar registers */
1029 	struct bpf_reg_state fake_reg[1];
1030 	/* buffers used to save updated reg states while simulating branches */
1031 	struct bpf_reg_state true_reg1, true_reg2, false_reg1, false_reg2;
1032 	/* buffer used to generate temporary string representations,
1033 	 * e.g., in reg_type_str() to generate reg_type string
1034 	 */
1035 	char tmp_str_buf[TMP_STR_BUF_LEN];
1036 	char tmp_arg_name[32];
1037 	struct bpf_insn insn_buf[INSN_BUF_SIZE];
1038 	struct bpf_insn epilogue_buf[INSN_BUF_SIZE];
1039 	struct bpf_scc_callchain callchain_buf;
1040 	struct bpf_liveness *liveness;
1041 	/* array of pointers to bpf_scc_info indexed by SCC id */
1042 	struct bpf_scc_info **scc_info;
1043 	u32 scc_cnt;
1044 	struct bpf_iarray *succ;
1045 	struct bpf_iarray *gotox_tmp_buf;
1046 };
1047 
subprog_aux(struct bpf_verifier_env * env,int subprog)1048 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
1049 {
1050 	return &env->prog->aux->func_info_aux[subprog];
1051 }
1052 
subprog_info(struct bpf_verifier_env * env,int subprog)1053 static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env, int subprog)
1054 {
1055 	return &env->subprog_info[subprog];
1056 }
1057 
1058 struct bpf_call_summary {
1059 	u8 num_params;
1060 	bool is_void;
1061 	bool fastcall;
1062 };
1063 
bpf_helper_call(const struct bpf_insn * insn)1064 static inline bool bpf_helper_call(const struct bpf_insn *insn)
1065 {
1066 	return insn->code == (BPF_JMP | BPF_CALL) &&
1067 	       insn->src_reg == 0;
1068 }
1069 
bpf_pseudo_call(const struct bpf_insn * insn)1070 static inline bool bpf_pseudo_call(const struct bpf_insn *insn)
1071 {
1072 	return insn->code == (BPF_JMP | BPF_CALL) &&
1073 	       insn->src_reg == BPF_PSEUDO_CALL;
1074 }
1075 
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)1076 static inline bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
1077 {
1078 	return insn->code == (BPF_JMP | BPF_CALL) &&
1079 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
1080 }
1081 
1082 __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,
1083 				      const char *fmt, va_list args);
1084 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
1085 					   const char *fmt, ...);
1086 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
1087 			    const char *fmt, ...);
1088 int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level,
1089 		  char __user *log_buf, u32 log_size);
1090 void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos);
1091 int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual);
1092 
1093 __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
1094 				  u32 insn_off,
1095 				  const char *prefix_fmt, ...);
1096 
1097 #define verifier_bug_if(cond, env, fmt, args...)						\
1098 	({											\
1099 		bool __cond = (cond);								\
1100 		if (unlikely(__cond))								\
1101 			verifier_bug(env, fmt " (" #cond ")", ##args);				\
1102 		(__cond);									\
1103 	})
1104 #define verifier_bug(env, fmt, args...)								\
1105 	({											\
1106 		BPF_WARN_ONCE(1, "verifier bug: " fmt "\n", ##args);				\
1107 		bpf_log(&env->log, "verifier bug: " fmt "\n", ##args);				\
1108 	})
1109 
mark_prune_point(struct bpf_verifier_env * env,int idx)1110 static inline void mark_prune_point(struct bpf_verifier_env *env, int idx)
1111 {
1112 	env->insn_aux_data[idx].prune_point = true;
1113 }
1114 
bpf_is_prune_point(struct bpf_verifier_env * env,int insn_idx)1115 static inline bool bpf_is_prune_point(struct bpf_verifier_env *env, int insn_idx)
1116 {
1117 	return env->insn_aux_data[insn_idx].prune_point;
1118 }
1119 
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)1120 static inline void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
1121 {
1122 	env->insn_aux_data[idx].force_checkpoint = true;
1123 }
1124 
bpf_is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)1125 static inline bool bpf_is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
1126 {
1127 	return env->insn_aux_data[insn_idx].force_checkpoint;
1128 }
1129 
mark_calls_callback(struct bpf_verifier_env * env,int idx)1130 static inline void mark_calls_callback(struct bpf_verifier_env *env, int idx)
1131 {
1132 	env->insn_aux_data[idx].calls_callback = true;
1133 }
1134 
bpf_calls_callback(struct bpf_verifier_env * env,int insn_idx)1135 static inline bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
1136 {
1137 	return env->insn_aux_data[insn_idx].calls_callback;
1138 }
1139 
mark_jmp_point(struct bpf_verifier_env * env,int idx)1140 static inline void mark_jmp_point(struct bpf_verifier_env *env, int idx)
1141 {
1142 	env->insn_aux_data[idx].jmp_point = true;
1143 }
1144 
cur_func(struct bpf_verifier_env * env)1145 static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env)
1146 {
1147 	struct bpf_verifier_state *cur = env->cur_state;
1148 
1149 	return cur->frame[cur->curframe];
1150 }
1151 
cur_regs(struct bpf_verifier_env * env)1152 static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env)
1153 {
1154 	return cur_func(env)->regs;
1155 }
1156 
1157 int bpf_prog_offload_verifier_prep(struct bpf_prog *prog);
1158 int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env,
1159 				 int insn_idx, int prev_insn_idx);
1160 int bpf_prog_offload_finalize(struct bpf_verifier_env *env);
1161 void
1162 bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off,
1163 			      struct bpf_insn *insn);
1164 void
1165 bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt);
1166 
1167 /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */
bpf_trampoline_compute_key(const struct bpf_prog * tgt_prog,struct btf * btf,u32 btf_id)1168 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
1169 					     struct btf *btf, u32 btf_id)
1170 {
1171 	if (tgt_prog)
1172 		return ((u64)tgt_prog->aux->id << 32) | btf_id;
1173 	else
1174 		return ((u64)btf_obj_id(btf) << 32) | 0x80000000 | btf_id;
1175 }
1176 
1177 /* unpack the IDs from the key as constructed above */
bpf_trampoline_unpack_key(u64 key,u32 * obj_id,u32 * btf_id)1178 static inline void bpf_trampoline_unpack_key(u64 key, u32 *obj_id, u32 *btf_id)
1179 {
1180 	if (obj_id)
1181 		*obj_id = key >> 32;
1182 	if (btf_id)
1183 		*btf_id = key & 0x7FFFFFFF;
1184 }
1185 
1186 int bpf_prepare_btf_info(struct bpf_verifier_env *env,
1187 			 const union bpf_attr *attr, bpfptr_t uattr);
1188 int bpf_check_btf_info(struct bpf_verifier_env *env,
1189 		       const union bpf_attr *attr, bpfptr_t uattr);
1190 
1191 int bpf_check_attach_target(struct bpf_verifier_log *log,
1192 			    const struct bpf_prog *prog,
1193 			    const struct bpf_prog *tgt_prog,
1194 			    u32 btf_id,
1195 			    struct bpf_attach_target_info *tgt_info);
1196 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
1197 
1198 int mark_chain_precision(struct bpf_verifier_env *env, int regno);
1199 
1200 int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx);
1201 int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
1202 
1203 void bpf_clear_jmp_history(struct bpf_verifier_state *state);
1204 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1205 			    const struct bpf_verifier_state *src);
1206 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx);
1207 void bpf_free_verifier_state(struct bpf_verifier_state *state, bool free_self);
1208 void bpf_free_backedges(struct bpf_scc_visit *visit);
1209 int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
1210 			 int insn_flags, int spi, int frame, u64 linked_regs);
1211 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist);
1212 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
1213 			   struct bpf_reg_state *reg);
1214 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg);
1215 void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env,
1216 				  struct bpf_verifier_state *st);
1217 void bpf_clear_singular_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
1218 int bpf_mark_chain_precision(struct bpf_verifier_env *env,
1219 			     struct bpf_verifier_state *starting_state,
1220 			     int regno, bool *changed);
1221 
bpf_get_spi(s32 off)1222 static inline int bpf_get_spi(s32 off)
1223 {
1224 	return (-off - 1) / BPF_REG_SIZE;
1225 }
1226 
bpf_func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)1227 static inline struct bpf_func_state *bpf_func(struct bpf_verifier_env *env,
1228 					      const struct bpf_reg_state *reg)
1229 {
1230 	struct bpf_verifier_state *cur = env->cur_state;
1231 
1232 	return cur->frame[reg->frameno];
1233 }
1234 
1235 /* Return IP for a given frame in a call stack */
bpf_frame_insn_idx(struct bpf_verifier_state * st,u32 frame)1236 static inline u32 bpf_frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1237 {
1238 	return frame == st->curframe
1239 	       ? st->insn_idx
1240 	       : st->frame[frame + 1]->callsite;
1241 }
1242 
bpf_is_jmp_point(struct bpf_verifier_env * env,int insn_idx)1243 static inline bool bpf_is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
1244 {
1245 	return env->insn_aux_data[insn_idx].jmp_point;
1246 }
1247 
bpf_is_spilled_reg(const struct bpf_stack_state * stack)1248 static inline bool bpf_is_spilled_reg(const struct bpf_stack_state *stack)
1249 {
1250 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1251 }
1252 
bpf_is_spilled_scalar_reg(const struct bpf_stack_state * stack)1253 static inline bool bpf_is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1254 {
1255 	return bpf_is_spilled_reg(stack) && stack->spilled_ptr.type == SCALAR_VALUE;
1256 }
1257 
bpf_register_is_null(struct bpf_reg_state * reg)1258 static inline bool bpf_register_is_null(struct bpf_reg_state *reg)
1259 {
1260 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1261 }
1262 
bpf_bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)1263 static inline void bpf_bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
1264 {
1265 	bt->reg_masks[frame] |= 1 << reg;
1266 }
1267 
bpf_bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)1268 static inline void bpf_bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
1269 {
1270 	bt->stack_masks[frame] |= 1ull << slot;
1271 }
1272 
bpf_bt_set_frame_slot_mask(struct backtrack_state * bt,u32 frame,u64 mask)1273 static inline void bpf_bt_set_frame_slot_mask(struct backtrack_state *bt, u32 frame, u64 mask)
1274 {
1275 	bt->stack_masks[frame] |= mask;
1276 }
1277 
bt_set_frame_stack_arg_slot(struct backtrack_state * bt,u32 frame,u32 slot)1278 static inline void bt_set_frame_stack_arg_slot(struct backtrack_state *bt, u32 frame, u32 slot)
1279 {
1280 	bt->stack_arg_masks[frame] |= 1 << slot;
1281 }
1282 
bt_is_frame_reg_set(struct backtrack_state * bt,u32 frame,u32 reg)1283 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
1284 {
1285 	return bt->reg_masks[frame] & (1 << reg);
1286 }
1287 
bt_is_frame_slot_set(struct backtrack_state * bt,u32 frame,u32 slot)1288 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
1289 {
1290 	return bt->stack_masks[frame] & (1ull << slot);
1291 }
1292 
1293 bool bpf_map_is_rdonly(const struct bpf_map *map);
1294 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
1295 			bool is_ldsx);
1296 
1297 #define BPF_BASE_TYPE_MASK	GENMASK(BPF_BASE_TYPE_BITS - 1, 0)
1298 
1299 /* extract base type from bpf_{arg, return, reg}_type. */
base_type(u32 type)1300 static inline u32 base_type(u32 type)
1301 {
1302 	return type & BPF_BASE_TYPE_MASK;
1303 }
1304 
1305 /* extract flags from an extended type. See bpf_type_flag in bpf.h. */
type_flag(u32 type)1306 static inline u32 type_flag(u32 type)
1307 {
1308 	return type & ~BPF_BASE_TYPE_MASK;
1309 }
1310 
bpf_is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)1311 static inline bool bpf_is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
1312 {
1313 	switch (base_type(type)) {
1314 	case PTR_TO_MEM:
1315 	case PTR_TO_BTF_ID:
1316 		return true;
1317 	default:
1318 		return false;
1319 	}
1320 }
1321 
bpf_may_fault_on_deref(enum bpf_reg_type type)1322 static inline bool bpf_may_fault_on_deref(enum bpf_reg_type type)
1323 {
1324 	/*
1325 	 * The pointer types which must not be dereferenced without fault
1326 	 * protection, that is, the ones bpf_convert_ctx_accesses() has to
1327 	 * turn a BPF_LDX into a BPF_PROBE_MEM one for.
1328 	 */
1329 	return type == PTR_TO_BTF_ID || (type_flag(type) & PTR_UNTRUSTED);
1330 }
1331 
bpf_prog_has_arena_ctx_arg(const struct bpf_prog * prog)1332 static inline bool bpf_prog_has_arena_ctx_arg(const struct bpf_prog *prog)
1333 {
1334 	int i;
1335 
1336 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++)
1337 		if (base_type(prog->aux->ctx_arg_info[i].reg_type) == PTR_TO_ARENA)
1338 			return true;
1339 	return false;
1340 }
1341 
resolve_prog_type(const struct bpf_prog * prog)1342 static inline enum bpf_prog_type resolve_prog_type(const struct bpf_prog *prog)
1343 {
1344 	return (prog->type == BPF_PROG_TYPE_EXT && prog->aux->saved_dst_prog_type) ?
1345 		prog->aux->saved_dst_prog_type : prog->type;
1346 }
1347 
bpf_prog_check_recur(const struct bpf_prog * prog)1348 static inline bool bpf_prog_check_recur(const struct bpf_prog *prog)
1349 {
1350 	switch (resolve_prog_type(prog)) {
1351 	case BPF_PROG_TYPE_TRACING:
1352 		return prog->expected_attach_type != BPF_TRACE_ITER;
1353 	case BPF_PROG_TYPE_STRUCT_OPS:
1354 		return prog->aux->jits_use_priv_stack;
1355 	case BPF_PROG_TYPE_LSM:
1356 	case BPF_PROG_TYPE_SYSCALL:
1357 		return false;
1358 	default:
1359 		return true;
1360 	}
1361 }
1362 
1363 #define BPF_REG_TRUSTED_MODIFIERS (MEM_ALLOC | PTR_TRUSTED | NON_OWN_REF)
1364 
bpf_type_has_unsafe_modifiers(u32 type)1365 static inline bool bpf_type_has_unsafe_modifiers(u32 type)
1366 {
1367 	return type_flag(type) & ~BPF_REG_TRUSTED_MODIFIERS;
1368 }
1369 
type_is_ptr_alloc_obj(u32 type)1370 static inline bool type_is_ptr_alloc_obj(u32 type)
1371 {
1372 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
1373 }
1374 
type_is_non_owning_ref(u32 type)1375 static inline bool type_is_non_owning_ref(u32 type)
1376 {
1377 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
1378 }
1379 
type_is_map_ptr(enum bpf_reg_type type)1380 static inline bool type_is_map_ptr(enum bpf_reg_type type)
1381 {
1382 	switch (base_type(type)) {
1383 	case CONST_PTR_TO_MAP:
1384 	case PTR_TO_MAP_KEY:
1385 	case PTR_TO_MAP_VALUE:
1386 		return true;
1387 	default:
1388 		return false;
1389 	}
1390 }
1391 
type_is_pkt_pointer(enum bpf_reg_type type)1392 static inline bool type_is_pkt_pointer(enum bpf_reg_type type)
1393 {
1394 	type = base_type(type);
1395 	return type == PTR_TO_PACKET ||
1396 	       type == PTR_TO_PACKET_META;
1397 }
1398 
type_is_sk_pointer(enum bpf_reg_type type)1399 static inline bool type_is_sk_pointer(enum bpf_reg_type type)
1400 {
1401 	return type == PTR_TO_SOCKET ||
1402 		type == PTR_TO_SOCK_COMMON ||
1403 		type == PTR_TO_TCP_SOCK ||
1404 		type == PTR_TO_XDP_SOCK;
1405 }
1406 
type_may_be_null(u32 type)1407 static inline bool type_may_be_null(u32 type)
1408 {
1409 	return type & PTR_MAYBE_NULL;
1410 }
1411 
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)1412 static inline void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
1413 {
1414 	env->scratched_regs |= 1U << regno;
1415 }
1416 
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)1417 static inline void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
1418 {
1419 	env->scratched_stack_slots |= 1ULL << spi;
1420 }
1421 
reg_scratched(const struct bpf_verifier_env * env,u32 regno)1422 static inline bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
1423 {
1424 	return (env->scratched_regs >> regno) & 1;
1425 }
1426 
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)1427 static inline bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
1428 {
1429 	return (env->scratched_stack_slots >> regno) & 1;
1430 }
1431 
verifier_state_scratched(const struct bpf_verifier_env * env)1432 static inline bool verifier_state_scratched(const struct bpf_verifier_env *env)
1433 {
1434 	return env->scratched_regs || env->scratched_stack_slots;
1435 }
1436 
mark_verifier_state_clean(struct bpf_verifier_env * env)1437 static inline void mark_verifier_state_clean(struct bpf_verifier_env *env)
1438 {
1439 	env->scratched_regs = 0U;
1440 	env->scratched_stack_slots = 0ULL;
1441 }
1442 
1443 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)1444 static inline void mark_verifier_state_scratched(struct bpf_verifier_env *env)
1445 {
1446 	env->scratched_regs = ~0U;
1447 	env->scratched_stack_slots = ~0ULL;
1448 }
1449 
bpf_stack_narrow_access_ok(int off,int fill_size,int spill_size)1450 static inline bool bpf_stack_narrow_access_ok(int off, int fill_size, int spill_size)
1451 {
1452 #ifdef __BIG_ENDIAN
1453 	off -= spill_size - fill_size;
1454 #endif
1455 
1456 	return !(off % BPF_REG_SIZE);
1457 }
1458 
insn_is_gotox(struct bpf_insn * insn)1459 static inline bool insn_is_gotox(struct bpf_insn *insn)
1460 {
1461 	return BPF_CLASS(insn->code) == BPF_JMP &&
1462 	       BPF_OP(insn->code) == BPF_JA &&
1463 	       BPF_SRC(insn->code) == BPF_X;
1464 }
1465 
1466 const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type);
1467 const char *dynptr_type_str(enum bpf_dynptr_type type);
1468 const char *iter_type_str(const struct btf *btf, u32 btf_id);
1469 const char *iter_state_str(enum bpf_iter_state state);
1470 
1471 void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate,
1472 			  u32 frameno, bool print_all);
1473 void print_insn_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate,
1474 		      u32 frameno);
1475 u32 bpf_vlog_alignment(u32 pos);
1476 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn);
1477 
1478 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off);
1479 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog);
1480 int bpf_jmp_offset(struct bpf_insn *insn);
1481 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
1482 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask);
1483 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
1484 
1485 int bpf_find_subprog(struct bpf_verifier_env *env, int off);
1486 bool bpf_is_throw_kfunc(struct bpf_insn *insn);
1487 int bpf_compute_const_regs(struct bpf_verifier_env *env);
1488 int bpf_prune_dead_branches(struct bpf_verifier_env *env);
1489 int bpf_check_cfg(struct bpf_verifier_env *env);
1490 int bpf_compute_postorder(struct bpf_verifier_env *env);
1491 int bpf_compute_scc(struct bpf_verifier_env *env);
1492 
1493 struct bpf_map_desc {
1494 	struct bpf_map *ptr;
1495 	int uid;
1496 };
1497 
1498 /* The last initialized dynptr; Populated by process_dynptr_func() */
1499 struct bpf_dynptr_desc {
1500 	enum bpf_dynptr_type type;
1501 	u32 id;
1502 	u32 parent_id;
1503 };
1504 
1505 /*
1506  * The last seen rereferenced object; Updated by update_ref_obj() when a register refers to a
1507  * referenced object. Used when the helper or kfunc is casting a referenced object, returning
1508  * allocated memory derived from referenced object or creating a dynptr with a referenced
1509  * object as parent.
1510  */
1511 struct ref_obj_desc {
1512 	u32 id;
1513 	u32 parent_id;
1514 	u8 cnt;
1515 };
1516 
1517 /*
1518  * A memory argument a call fills in. The verifier allows the stack to be uninitialized if
1519  * the range is a known constant. Stack slots are marked as STACK_MISC by check_mem_access().
1520  */
1521 struct arg_raw_mem_desc {
1522 	u8 regno;
1523 	int size;
1524 };
1525 
1526 /* Size of PTR_TO_MEM returned, taken from a constant allocation-size argument */
1527 struct ret_mem_desc {
1528 	u32 size;
1529 	bool found;
1530 };
1531 
1532 /* A constant scalar argument; Populated by process_const_arg() */
1533 struct arg_constant_desc {
1534 	u64 value;
1535 	bool found;
1536 };
1537 
1538 struct bpf_call_arg_meta {
1539 	/* Common */
1540 	struct btf *btf;
1541 	u32 func_id;
1542 	const struct bpf_func_proto *fn;
1543 	u8 release_regno;
1544 	u32 ret_btf_id;
1545 	u32 subprogno;
1546 	struct bpf_map_desc map;
1547 	struct bpf_dynptr_desc dynptr;
1548 	struct ref_obj_desc ref_obj;
1549 	struct ret_mem_desc ret_mem;
1550 
1551 	/* Only set by kfunc */
1552 	bool r0_rdonly;
1553 	u32 kfunc_flags;
1554 	const struct btf_type *func_proto;
1555 	const char *func_name;
1556 	struct arg_constant_desc arg_constant;
1557 
1558 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
1559 	 * generally to pass info about user-defined local kptr types to later
1560 	 * verification logic
1561 	 *   bpf_obj_drop/bpf_percpu_obj_drop
1562 	 *     Record the local kptr type to be drop'd
1563 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
1564 	 *     Record the local kptr type to be refcount_incr'd and use
1565 	 *     arg_owning_ref to determine whether refcount_acquire should be
1566 	 *     fallible
1567 	 */
1568 	struct btf *arg_btf;
1569 	u32 arg_btf_id;
1570 	bool arg_owning_ref;
1571 	bool arg_prog;
1572 
1573 	struct {
1574 		struct btf_field *field;
1575 	} arg_list_head;
1576 	struct {
1577 		struct btf_field *field;
1578 	} arg_rbtree_root;
1579 	struct {
1580 		u8 spi;
1581 		u8 frameno;
1582 	} iter;
1583 
1584 	/* Only set by helper */
1585 	u64 msize_max_value;
1586 	s64 const_map_key;
1587 	struct btf *ret_btf;
1588 	struct btf_field *kptr_field;
1589 	struct arg_raw_mem_desc arg_raw_mem;
1590 };
1591 
1592 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
1593 			 const struct bpf_func_proto **ptr);
1594 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, s32 func_id,
1595 			     s16 offset, struct bpf_call_arg_meta *meta);
1596 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn);
1597 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn);
bpf_is_iter_next_kfunc(struct bpf_call_arg_meta * meta)1598 static inline bool bpf_is_iter_next_kfunc(struct bpf_call_arg_meta *meta)
1599 {
1600 	return meta->kfunc_flags & KF_ITER_NEXT;
1601 }
1602 
bpf_is_kfunc_sleepable(struct bpf_call_arg_meta * meta)1603 static inline bool bpf_is_kfunc_sleepable(struct bpf_call_arg_meta *meta)
1604 {
1605 	return meta->kfunc_flags & KF_SLEEPABLE;
1606 }
1607 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta);
1608 struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem);
1609 int bpf_copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off);
1610 bool bpf_insn_is_cond_jump(u8 code);
1611 bool bpf_is_may_goto_insn(struct bpf_insn *insn);
1612 
1613 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);
1614 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
1615 			  struct bpf_call_summary *cs);
1616 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env,
1617 				  struct bpf_insn *insn, int arg,
1618 				  int insn_idx);
1619 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env,
1620 				 struct bpf_insn *insn, int arg,
1621 				 int insn_idx);
1622 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env);
1623 
1624 int bpf_stack_liveness_init(struct bpf_verifier_env *env);
1625 void bpf_stack_liveness_free(struct bpf_verifier_env *env);
1626 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
1627 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
1628 int bpf_compute_live_registers(struct bpf_verifier_env *env);
1629 
1630 #define BPF_MAP_KEY_POISON	(1ULL << 63)
1631 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
1632 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)1633 static inline bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
1634 {
1635 	return aux->map_ptr_state.poison;
1636 }
1637 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)1638 static inline bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
1639 {
1640 	return aux->map_ptr_state.unpriv;
1641 }
1642 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)1643 static inline bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
1644 {
1645 	return aux->map_key_state & BPF_MAP_KEY_POISON;
1646 }
1647 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)1648 static inline bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
1649 {
1650 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
1651 }
1652 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)1653 static inline u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
1654 {
1655 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
1656 }
1657 
1658 #define MAX_PACKET_OFF 0xffff
1659 #define CALLER_SAVED_REGS 6
1660 
1661 enum bpf_reg_arg_type {
1662 	SRC_OP,		/* register is used as source operand */
1663 	DST_OP,		/* register is used as destination operand */
1664 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1665 };
1666 
1667 #define MAX_KFUNC_DESCS 256
1668 
1669 struct bpf_kfunc_desc {
1670 	struct btf_func_model func_model;
1671 	struct bpf_func_proto proto;
1672 	u32 func_id;
1673 	s32 imm;
1674 	u16 offset;
1675 	unsigned long addr;
1676 };
1677 
1678 struct bpf_kfunc_desc_tab {
1679 	u32 nr_descs;
1680 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
1681 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
1682 	 * available, therefore at the end of verification do_misc_fixups()
1683 	 * sorts this by imm and offset.
1684 	 *
1685 	 * Grown one entry at a time by bpf_add_kfunc_call().
1686 	 */
1687 	struct bpf_kfunc_desc descs[];
1688 };
1689 
1690 /* Functions exported from verifier.c, used by fixups.c */
1691 void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len);
1692 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog);
1693 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env);
1694 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm);
1695 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset);
1696 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
1697 			 struct bpf_insn *insn_buf, int insn_idx, int *cnt);
1698 
1699 /* Functions exported from verifier.c, used by trampoline.c */
1700 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
1701 				  struct bpf_attach_target_info *tgt_info);
1702 
1703 /* Functions in fixups.c, called from bpf_check() */
1704 int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env);
1705 int bpf_optimize_bpf_loop(struct bpf_verifier_env *env);
1706 void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env);
1707 int bpf_opt_remove_dead_code(struct bpf_verifier_env *env);
1708 int bpf_opt_remove_nops(struct bpf_verifier_env *env);
1709 int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union bpf_attr *attr);
1710 int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);
1711 int bpf_jit_subprogs(struct bpf_verifier_env *env);
1712 int bpf_fixup_call_args(struct bpf_verifier_env *env);
1713 int bpf_do_misc_fixups(struct bpf_verifier_env *env);
1714 int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
1715 
1716 #endif /* _LINUX_BPF_VERIFIER_H */
1717