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/android_kabi.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_CONST_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 /* Liveness marks, used for registers and spilled-regs (in stack slots).
31 * Read marks propagate upwards until they find a write mark; they record that
32 * "one of this state's descendants read this reg" (and therefore the reg is
33 * relevant for states_equal() checks).
34 * Write marks collect downwards and do not propagate; they record that "the
35 * straight-line code that reached this state (from its parent) wrote this reg"
36 * (and therefore that reads propagated from this state or its descendants
37 * should not propagate to its parent).
38 * A state with a write mark can receive read marks; it just won't propagate
39 * them to its parent, since the write mark is a property, not of the state,
40 * but of the link between it and its parent. See mark_reg_read() and
41 * mark_stack_slot_read() in kernel/bpf/verifier.c.
42 */
43 enum bpf_reg_liveness {
44 REG_LIVE_NONE = 0, /* reg hasn't been read or written this branch */
45 REG_LIVE_READ32 = 0x1, /* reg was read, so we're sensitive to initial value */
46 REG_LIVE_READ64 = 0x2, /* likewise, but full 64-bit content matters */
47 REG_LIVE_READ = REG_LIVE_READ32 | REG_LIVE_READ64,
48 REG_LIVE_WRITTEN = 0x4, /* reg was written first, screening off later reads */
49 REG_LIVE_DONE = 0x8, /* liveness won't be updating this register anymore */
50 };
51
52 /* For every reg representing a map value or allocated object pointer,
53 * we consider the tuple of (ptr, id) for them to be unique in verifier
54 * context and conside them to not alias each other for the purposes of
55 * tracking lock state.
56 */
57 struct bpf_active_lock {
58 /* This can either be reg->map_ptr or reg->btf. If ptr is NULL,
59 * there's no active lock held, and other fields have no
60 * meaning. If non-NULL, it indicates that a lock is held and
61 * id member has the reg->id of the register which can be >= 0.
62 */
63 void *ptr;
64 /* This will be reg->id */
65 u32 id;
66 };
67
68 #define ITER_PREFIX "bpf_iter_"
69
70 enum bpf_iter_state {
71 BPF_ITER_STATE_INVALID, /* for non-first slot */
72 BPF_ITER_STATE_ACTIVE,
73 BPF_ITER_STATE_DRAINED,
74 };
75
76 struct bpf_reg_state {
77 /* Ordering of fields matters. See states_equal() */
78 enum bpf_reg_type type;
79 /*
80 * Fixed part of pointer offset, pointer types only.
81 * Or constant delta between "linked" scalars with the same ID.
82 */
83 s32 off;
84 union {
85 /* valid when type == PTR_TO_PACKET */
86 int range;
87
88 /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
89 * PTR_TO_MAP_VALUE_OR_NULL
90 */
91 struct {
92 struct bpf_map *map_ptr;
93 /* To distinguish map lookups from outer map
94 * the map_uid is non-zero for registers
95 * pointing to inner maps.
96 */
97 u32 map_uid;
98 };
99
100 /* for PTR_TO_BTF_ID */
101 struct {
102 struct btf *btf;
103 u32 btf_id;
104 };
105
106 struct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */
107 u32 mem_size;
108 u32 dynptr_id; /* for dynptr slices */
109 };
110
111 /* For dynptr stack slots */
112 struct {
113 enum bpf_dynptr_type type;
114 /* A dynptr is 16 bytes so it takes up 2 stack slots.
115 * We need to track which slot is the first slot
116 * to protect against cases where the user may try to
117 * pass in an address starting at the second slot of the
118 * dynptr.
119 */
120 bool first_slot;
121 } dynptr;
122
123 /* For bpf_iter stack slots */
124 struct {
125 /* BTF container and BTF type ID describing
126 * struct bpf_iter_<type> of an iterator state
127 */
128 struct btf *btf;
129 u32 btf_id;
130 /* packing following two fields to fit iter state into 16 bytes */
131 enum bpf_iter_state state:2;
132 int depth:30;
133 } iter;
134
135 /* Max size from any of the above. */
136 struct {
137 unsigned long raw1;
138 unsigned long raw2;
139 } raw;
140
141 u32 subprogno; /* for PTR_TO_FUNC */
142 };
143 /* For scalar types (SCALAR_VALUE), this represents our knowledge of
144 * the actual value.
145 * For pointer types, this represents the variable part of the offset
146 * from the pointed-to object, and is shared with all bpf_reg_states
147 * with the same id as us.
148 */
149 struct tnum var_off;
150 /* Used to determine if any memory access using this register will
151 * result in a bad access.
152 * These refer to the same value as var_off, not necessarily the actual
153 * contents of the register.
154 */
155 s64 smin_value; /* minimum possible (s64)value */
156 s64 smax_value; /* maximum possible (s64)value */
157 u64 umin_value; /* minimum possible (u64)value */
158 u64 umax_value; /* maximum possible (u64)value */
159 s32 s32_min_value; /* minimum possible (s32)value */
160 s32 s32_max_value; /* maximum possible (s32)value */
161 u32 u32_min_value; /* minimum possible (u32)value */
162 u32 u32_max_value; /* maximum possible (u32)value */
163 /* For PTR_TO_PACKET, used to find other pointers with the same variable
164 * offset, so they can share range knowledge.
165 * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we
166 * came from, when one is tested for != NULL.
167 * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation
168 * for the purpose of tracking that it's freed.
169 * For PTR_TO_SOCKET this is used to share which pointers retain the
170 * same reference to the socket, to determine proper reference freeing.
171 * For stack slots that are dynptrs, this is used to track references to
172 * the dynptr to determine proper reference freeing.
173 * Similarly to dynptrs, we use ID to track "belonging" of a reference
174 * to a specific instance of bpf_iter.
175 */
176 /*
177 * Upper bit of ID is used to remember relationship between "linked"
178 * registers. Example:
179 * r1 = r2; both will have r1->id == r2->id == N
180 * r1 += 10; r1->id == N | BPF_ADD_CONST and r1->off == 10
181 */
182 #define BPF_ADD_CONST (1U << 31)
183 u32 id;
184 /* PTR_TO_SOCKET and PTR_TO_TCP_SOCK could be a ptr returned
185 * from a pointer-cast helper, bpf_sk_fullsock() and
186 * bpf_tcp_sock().
187 *
188 * Consider the following where "sk" is a reference counted
189 * pointer returned from "sk = bpf_sk_lookup_tcp();":
190 *
191 * 1: sk = bpf_sk_lookup_tcp();
192 * 2: if (!sk) { return 0; }
193 * 3: fullsock = bpf_sk_fullsock(sk);
194 * 4: if (!fullsock) { bpf_sk_release(sk); return 0; }
195 * 5: tp = bpf_tcp_sock(fullsock);
196 * 6: if (!tp) { bpf_sk_release(sk); return 0; }
197 * 7: bpf_sk_release(sk);
198 * 8: snd_cwnd = tp->snd_cwnd; // verifier will complain
199 *
200 * After bpf_sk_release(sk) at line 7, both "fullsock" ptr and
201 * "tp" ptr should be invalidated also. In order to do that,
202 * the reg holding "fullsock" and "sk" need to remember
203 * the original refcounted ptr id (i.e. sk_reg->id) in ref_obj_id
204 * such that the verifier can reset all regs which have
205 * ref_obj_id matching the sk_reg->id.
206 *
207 * sk_reg->ref_obj_id is set to sk_reg->id at line 1.
208 * sk_reg->id will stay as NULL-marking purpose only.
209 * After NULL-marking is done, sk_reg->id can be reset to 0.
210 *
211 * After "fullsock = bpf_sk_fullsock(sk);" at line 3,
212 * fullsock_reg->ref_obj_id is set to sk_reg->ref_obj_id.
213 *
214 * After "tp = bpf_tcp_sock(fullsock);" at line 5,
215 * tp_reg->ref_obj_id is set to fullsock_reg->ref_obj_id
216 * which is the same as sk_reg->ref_obj_id.
217 *
218 * From the verifier perspective, if sk, fullsock and tp
219 * are not NULL, they are the same ptr with different
220 * reg->type. In particular, bpf_sk_release(tp) is also
221 * allowed and has the same effect as bpf_sk_release(sk).
222 */
223 u32 ref_obj_id;
224 /* parentage chain for liveness checking */
225 struct bpf_reg_state *parent;
226 /* Inside the callee two registers can be both PTR_TO_STACK like
227 * R1=fp-8 and R2=fp-8, but one of them points to this function stack
228 * while another to the caller's stack. To differentiate them 'frameno'
229 * is used which is an index in bpf_verifier_state->frame[] array
230 * pointing to bpf_func_state.
231 */
232 u32 frameno;
233 /* Tracks subreg definition. The stored value is the insn_idx of the
234 * writing insn. This is safe because subreg_def is used before any insn
235 * patching which only happens after main verification finished.
236 */
237 s32 subreg_def;
238 enum bpf_reg_liveness live;
239 /* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
240 bool precise;
241 };
242
243 enum bpf_stack_slot_type {
244 STACK_INVALID, /* nothing was stored in this stack slot */
245 STACK_SPILL, /* register spilled into stack */
246 STACK_MISC, /* BPF program wrote some data into this slot */
247 STACK_ZERO, /* BPF program wrote constant zero */
248 /* A dynptr is stored in this stack slot. The type of dynptr
249 * is stored in bpf_stack_state->spilled_ptr.dynptr.type
250 */
251 STACK_DYNPTR,
252 STACK_ITER,
253 };
254
255 #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
256
257 #define BPF_REGMASK_ARGS ((1 << BPF_REG_1) | (1 << BPF_REG_2) | \
258 (1 << BPF_REG_3) | (1 << BPF_REG_4) | \
259 (1 << BPF_REG_5))
260
261 #define BPF_DYNPTR_SIZE sizeof(struct bpf_dynptr_kern)
262 #define BPF_DYNPTR_NR_SLOTS (BPF_DYNPTR_SIZE / BPF_REG_SIZE)
263
264 struct bpf_stack_state {
265 struct bpf_reg_state spilled_ptr;
266 u8 slot_type[BPF_REG_SIZE];
267 };
268
269 struct bpf_reference_state {
270 /* Track each reference created with a unique id, even if the same
271 * instruction creates the reference multiple times (eg, via CALL).
272 */
273 int id;
274 /* Instruction where the allocation of this reference occurred. This
275 * is used purely to inform the user of a reference leak.
276 */
277 int insn_idx;
278 /* There can be a case like:
279 * main (frame 0)
280 * cb (frame 1)
281 * func (frame 3)
282 * cb (frame 4)
283 * Hence for frame 4, if callback_ref just stored boolean, it would be
284 * impossible to distinguish nested callback refs. Hence store the
285 * frameno and compare that to callback_ref in check_reference_leak when
286 * exiting a callback function.
287 */
288 int callback_ref;
289 };
290
291 struct bpf_retval_range {
292 s32 minval;
293 s32 maxval;
294 };
295
296 /* state of the program:
297 * type of all registers and stack info
298 */
299 struct bpf_func_state {
300 struct bpf_reg_state regs[MAX_BPF_REG];
301 /* index of call instruction that called into this func */
302 int callsite;
303 /* stack frame number of this function state from pov of
304 * enclosing bpf_verifier_state.
305 * 0 = main function, 1 = first callee.
306 */
307 u32 frameno;
308 /* subprog number == index within subprog_info
309 * zero == main subprog
310 */
311 u32 subprogno;
312 /* Every bpf_timer_start will increment async_entry_cnt.
313 * It's used to distinguish:
314 * void foo(void) { for(;;); }
315 * void foo(void) { bpf_timer_set_callback(,foo); }
316 */
317 u32 async_entry_cnt;
318 struct bpf_retval_range callback_ret_range;
319 bool in_callback_fn;
320 bool in_async_callback_fn;
321 bool in_exception_callback_fn;
322 /* For callback calling functions that limit number of possible
323 * callback executions (e.g. bpf_loop) keeps track of current
324 * simulated iteration number.
325 * Value in frame N refers to number of times callback with frame
326 * N+1 was simulated, e.g. for the following call:
327 *
328 * bpf_loop(..., fn, ...); | suppose current frame is N
329 * | fn would be simulated in frame N+1
330 * | number of simulations is tracked in frame N
331 */
332 u32 callback_depth;
333
334 /* The following fields should be last. See copy_func_state() */
335 int acquired_refs;
336 struct bpf_reference_state *refs;
337 /* The state of the stack. Each element of the array describes BPF_REG_SIZE
338 * (i.e. 8) bytes worth of stack memory.
339 * stack[0] represents bytes [*(r10-8)..*(r10-1)]
340 * stack[1] represents bytes [*(r10-16)..*(r10-9)]
341 * ...
342 * stack[allocated_stack/8 - 1] represents [*(r10-allocated_stack)..*(r10-allocated_stack+7)]
343 */
344 struct bpf_stack_state *stack;
345 /* Size of the current stack, in bytes. The stack state is tracked below, in
346 * `stack`. allocated_stack is always a multiple of BPF_REG_SIZE.
347 */
348 int allocated_stack;
349 };
350
351 #define MAX_CALL_FRAMES 8
352
353 /* instruction history flags, used in bpf_jmp_history_entry.flags field */
354 enum {
355 /* instruction references stack slot through PTR_TO_STACK register;
356 * we also store stack's frame number in lower 3 bits (MAX_CALL_FRAMES is 8)
357 * and accessed stack slot's index in next 6 bits (MAX_BPF_STACK is 512,
358 * 8 bytes per slot, so slot index (spi) is [0, 63])
359 */
360 INSN_F_FRAMENO_MASK = 0x7, /* 3 bits */
361
362 INSN_F_SPI_MASK = 0x3f, /* 6 bits */
363 INSN_F_SPI_SHIFT = 3, /* shifted 3 bits to the left */
364
365 INSN_F_STACK_ACCESS = BIT(9), /* we need 10 bits total */
366 };
367
368 static_assert(INSN_F_FRAMENO_MASK + 1 >= MAX_CALL_FRAMES);
369 static_assert(INSN_F_SPI_MASK + 1 >= MAX_BPF_STACK / 8);
370
371 struct bpf_jmp_history_entry {
372 u32 idx;
373 /* insn idx can't be bigger than 1 million */
374 u32 prev_idx : 22;
375 /* special flags, e.g., whether insn is doing register stack spill/load */
376 u32 flags : 10;
377 /* additional registers that need precision tracking when this
378 * jump is backtracked, vector of six 10-bit records
379 */
380 u64 linked_regs;
381 };
382
383 /* Maximum number of register states that can exist at once */
384 #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) * MAX_CALL_FRAMES)
385 struct bpf_verifier_state {
386 /* call stack tracking */
387 struct bpf_func_state *frame[MAX_CALL_FRAMES];
388 struct bpf_verifier_state *parent;
389 /*
390 * 'branches' field is the number of branches left to explore:
391 * 0 - all possible paths from this state reached bpf_exit or
392 * were safely pruned
393 * 1 - at least one path is being explored.
394 * This state hasn't reached bpf_exit
395 * 2 - at least two paths are being explored.
396 * This state is an immediate parent of two children.
397 * One is fallthrough branch with branches==1 and another
398 * state is pushed into stack (to be explored later) also with
399 * branches==1. The parent of this state has branches==1.
400 * The verifier state tree connected via 'parent' pointer looks like:
401 * 1
402 * 1
403 * 2 -> 1 (first 'if' pushed into stack)
404 * 1
405 * 2 -> 1 (second 'if' pushed into stack)
406 * 1
407 * 1
408 * 1 bpf_exit.
409 *
410 * Once do_check() reaches bpf_exit, it calls update_branch_counts()
411 * and the verifier state tree will look:
412 * 1
413 * 1
414 * 2 -> 1 (first 'if' pushed into stack)
415 * 1
416 * 1 -> 1 (second 'if' pushed into stack)
417 * 0
418 * 0
419 * 0 bpf_exit.
420 * After pop_stack() the do_check() will resume at second 'if'.
421 *
422 * If is_state_visited() sees a state with branches > 0 it means
423 * there is a loop. If such state is exactly equal to the current state
424 * it's an infinite loop. Note states_equal() checks for states
425 * equivalency, so two states being 'states_equal' does not mean
426 * infinite loop. The exact comparison is provided by
427 * states_maybe_looping() function. It's a stronger pre-check and
428 * much faster than states_equal().
429 *
430 * This algorithm may not find all possible infinite loops or
431 * loop iteration count may be too high.
432 * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in.
433 */
434 u32 branches;
435 u32 insn_idx;
436 u32 curframe;
437
438 struct bpf_active_lock active_lock;
439 bool speculative;
440 bool active_rcu_lock;
441 u32 active_preempt_lock;
442 /* If this state was ever pointed-to by other state's loop_entry field
443 * this flag would be set to true. Used to avoid freeing such states
444 * while they are still in use.
445 */
446 bool used_as_loop_entry;
447 bool in_sleepable;
448
449 /* first and last insn idx of this verifier state */
450 u32 first_insn_idx;
451 u32 last_insn_idx;
452 /* If this state is a part of states loop this field points to some
453 * parent of this state such that:
454 * - it is also a member of the same states loop;
455 * - DFS states traversal starting from initial state visits loop_entry
456 * state before this state.
457 * Used to compute topmost loop entry for state loops.
458 * State loops might appear because of open coded iterators logic.
459 * See get_loop_entry() for more information.
460 */
461 struct bpf_verifier_state *loop_entry;
462 /* jmp history recorded from first to last.
463 * backtracking is using it to go from last to first.
464 * For most states jmp_history_cnt is [0-3].
465 * For loops can go up to ~40.
466 */
467 struct bpf_jmp_history_entry *jmp_history;
468 u32 jmp_history_cnt;
469 u32 dfs_depth;
470 u32 callback_unroll_depth;
471 u32 may_goto_depth;
472 };
473
474 #define bpf_get_spilled_reg(slot, frame, mask) \
475 (((slot < frame->allocated_stack / BPF_REG_SIZE) && \
476 ((1 << frame->stack[slot].slot_type[BPF_REG_SIZE - 1]) & (mask))) \
477 ? &frame->stack[slot].spilled_ptr : NULL)
478
479 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */
480 #define bpf_for_each_spilled_reg(iter, frame, reg, mask) \
481 for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask); \
482 iter < frame->allocated_stack / BPF_REG_SIZE; \
483 iter++, reg = bpf_get_spilled_reg(iter, frame, mask))
484
485 #define bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, __mask, __expr) \
486 ({ \
487 struct bpf_verifier_state *___vstate = __vst; \
488 int ___i, ___j; \
489 for (___i = 0; ___i <= ___vstate->curframe; ___i++) { \
490 struct bpf_reg_state *___regs; \
491 __state = ___vstate->frame[___i]; \
492 ___regs = __state->regs; \
493 for (___j = 0; ___j < MAX_BPF_REG; ___j++) { \
494 __reg = &___regs[___j]; \
495 (void)(__expr); \
496 } \
497 bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \
498 if (!__reg) \
499 continue; \
500 (void)(__expr); \
501 } \
502 } \
503 })
504
505 /* Invoke __expr over regsiters in __vst, setting __state and __reg */
506 #define bpf_for_each_reg_in_vstate(__vst, __state, __reg, __expr) \
507 bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, 1 << STACK_SPILL, __expr)
508
509 /* linked list of verifier states used to prune search */
510 struct bpf_verifier_state_list {
511 struct bpf_verifier_state state;
512 struct bpf_verifier_state_list *next;
513 int miss_cnt, hit_cnt;
514 };
515
516 struct bpf_loop_inline_state {
517 unsigned int initialized:1; /* set to true upon first entry */
518 unsigned int fit_for_inline:1; /* true if callback function is the same
519 * at each call and flags are always zero
520 */
521 u32 callback_subprogno; /* valid when fit_for_inline is true */
522 };
523
524 /* pointer and state for maps */
525 struct bpf_map_ptr_state {
526 struct bpf_map *map_ptr;
527 bool poison;
528 bool unpriv;
529 };
530
531 /* Possible states for alu_state member. */
532 #define BPF_ALU_SANITIZE_SRC (1U << 0)
533 #define BPF_ALU_SANITIZE_DST (1U << 1)
534 #define BPF_ALU_NEG_VALUE (1U << 2)
535 #define BPF_ALU_NON_POINTER (1U << 3)
536 #define BPF_ALU_IMMEDIATE (1U << 4)
537 #define BPF_ALU_SANITIZE (BPF_ALU_SANITIZE_SRC | \
538 BPF_ALU_SANITIZE_DST)
539
540 struct bpf_insn_aux_data {
541 union {
542 enum bpf_reg_type ptr_type; /* pointer type for load/store insns */
543 struct bpf_map_ptr_state map_ptr_state;
544 s32 call_imm; /* saved imm field of call insn */
545 u32 alu_limit; /* limit for add/sub register with pointer */
546 struct {
547 u32 map_index; /* index into used_maps[] */
548 u32 map_off; /* offset from value base address */
549 };
550 struct {
551 enum bpf_reg_type reg_type; /* type of pseudo_btf_id */
552 union {
553 struct {
554 struct btf *btf;
555 u32 btf_id; /* btf_id for struct typed var */
556 };
557 u32 mem_size; /* mem_size for non-struct typed var */
558 };
559 } btf_var;
560 /* if instruction is a call to bpf_loop this field tracks
561 * the state of the relevant registers to make decision about inlining
562 */
563 struct bpf_loop_inline_state loop_inline_state;
564 };
565 union {
566 /* remember the size of type passed to bpf_obj_new to rewrite R1 */
567 u64 obj_new_size;
568 /* remember the offset of node field within type to rewrite */
569 u64 insert_off;
570 };
571 struct btf_struct_meta *kptr_struct_meta;
572 u64 map_key_state; /* constant (32 bit) key tracking for maps */
573 int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
574 u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
575 bool sanitize_stack_spill; /* subject to Spectre v4 sanitation */
576 bool zext_dst; /* this insn zero extends dst reg */
577 bool needs_zext; /* alu op needs to clear upper bits */
578 bool storage_get_func_atomic; /* bpf_*_storage_get() with atomic memory alloc */
579 bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */
580 bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */
581 u8 alu_state; /* used in combination with alu_limit */
582 /* true if STX or LDX instruction is a part of a spill/fill
583 * pattern for a bpf_fastcall call.
584 */
585 u8 fastcall_pattern:1;
586 /* for CALL instructions, a number of spill/fill pairs in the
587 * bpf_fastcall pattern.
588 */
589 u8 fastcall_spills_num:3;
590
591 /* below fields are initialized once */
592 unsigned int orig_idx; /* original instruction index */
593 bool jmp_point;
594 bool prune_point;
595 /* ensure we check state equivalence and save state checkpoint and
596 * this instruction, regardless of any heuristics
597 */
598 bool force_checkpoint;
599 /* true if instruction is a call to a helper function that
600 * accepts callback function as a parameter.
601 */
602 bool calls_callback;
603 };
604
605 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
606 #define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */
607
608 #define BPF_VERIFIER_TMP_LOG_SIZE 1024
609
610 struct bpf_verifier_log {
611 /* Logical start and end positions of a "log window" of the verifier log.
612 * start_pos == 0 means we haven't truncated anything.
613 * Once truncation starts to happen, start_pos + len_total == end_pos,
614 * except during log reset situations, in which (end_pos - start_pos)
615 * might get smaller than len_total (see bpf_vlog_reset()).
616 * Generally, (end_pos - start_pos) gives number of useful data in
617 * user log buffer.
618 */
619 u64 start_pos;
620 u64 end_pos;
621 char __user *ubuf;
622 u32 level;
623 u32 len_total;
624 u32 len_max;
625 char kbuf[BPF_VERIFIER_TMP_LOG_SIZE];
626 };
627
628 #define BPF_LOG_LEVEL1 1
629 #define BPF_LOG_LEVEL2 2
630 #define BPF_LOG_STATS 4
631 #define BPF_LOG_FIXED 8
632 #define BPF_LOG_LEVEL (BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2)
633 #define BPF_LOG_MASK (BPF_LOG_LEVEL | BPF_LOG_STATS | BPF_LOG_FIXED)
634 #define BPF_LOG_KERNEL (BPF_LOG_MASK + 1) /* kernel internal flag */
635 #define BPF_LOG_MIN_ALIGNMENT 8U
636 #define BPF_LOG_ALIGNMENT 40U
637
bpf_verifier_log_needed(const struct bpf_verifier_log * log)638 static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log)
639 {
640 return log && log->level;
641 }
642
643 #define BPF_MAX_SUBPROGS 256
644
645 struct bpf_subprog_arg_info {
646 enum bpf_arg_type arg_type;
647 union {
648 u32 mem_size;
649 u32 btf_id;
650 };
651 };
652
653 struct bpf_subprog_info {
654 /* 'start' has to be the first field otherwise find_subprog() won't work */
655 u32 start; /* insn idx of function entry point */
656 u32 linfo_idx; /* The idx to the main_prog->aux->linfo */
657 u16 stack_depth; /* max. stack depth used by this function */
658 u16 stack_extra;
659 /* offsets in range [stack_depth .. fastcall_stack_off)
660 * are used for bpf_fastcall spills and fills.
661 */
662 s16 fastcall_stack_off;
663 bool has_tail_call: 1;
664 bool tail_call_reachable: 1;
665 bool has_ld_abs: 1;
666 bool is_cb: 1;
667 bool is_async_cb: 1;
668 bool is_exception_cb: 1;
669 bool args_cached: 1;
670 /* true if bpf_fastcall stack region is used by functions that can't be inlined */
671 bool keep_fastcall_stack: 1;
672
673 u8 arg_cnt;
674 struct bpf_subprog_arg_info args[MAX_BPF_FUNC_REG_ARGS];
675
676 ANDROID_KABI_RESERVE(1);
677 };
678
679 struct bpf_verifier_env;
680
681 struct backtrack_state {
682 struct bpf_verifier_env *env;
683 u32 frame;
684 u32 reg_masks[MAX_CALL_FRAMES];
685 u64 stack_masks[MAX_CALL_FRAMES];
686 };
687
688 struct bpf_id_pair {
689 u32 old;
690 u32 cur;
691 };
692
693 struct bpf_idmap {
694 u32 tmp_id_gen;
695 struct bpf_id_pair map[BPF_ID_MAP_SIZE];
696 };
697
698 struct bpf_idset {
699 u32 count;
700 u32 ids[BPF_ID_MAP_SIZE];
701 };
702
703 /* single container for all structs
704 * one verifier_env per bpf_check() call
705 */
706 struct bpf_verifier_env {
707 u32 insn_idx;
708 u32 prev_insn_idx;
709 struct bpf_prog *prog; /* eBPF program being verified */
710 const struct bpf_verifier_ops *ops;
711 struct module *attach_btf_mod; /* The owner module of prog->aux->attach_btf */
712 struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */
713 int stack_size; /* number of states to be processed */
714 bool strict_alignment; /* perform strict pointer alignment checks */
715 bool test_state_freq; /* test verifier with different pruning frequency */
716 bool test_reg_invariants; /* fail verification on register invariants violations */
717 struct bpf_verifier_state *cur_state; /* current verifier state */
718 struct bpf_verifier_state_list **explored_states; /* search pruning optimization */
719 struct bpf_verifier_state_list *free_list;
720 struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
721 struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */
722 u32 used_map_cnt; /* number of used maps */
723 u32 used_btf_cnt; /* number of used BTF objects */
724 u32 id_gen; /* used to generate unique reg IDs */
725 u32 hidden_subprog_cnt; /* number of hidden subprogs */
726 int exception_callback_subprog;
727 bool explore_alu_limits;
728 bool allow_ptr_leaks;
729 /* Allow access to uninitialized stack memory. Writes with fixed offset are
730 * always allowed, so this refers to reads (with fixed or variable offset),
731 * to writes with variable offset and to indirect (helper) accesses.
732 */
733 bool allow_uninit_stack;
734 bool bpf_capable;
735 bool bypass_spec_v1;
736 bool bypass_spec_v4;
737 bool seen_direct_write;
738 bool seen_exception;
739 struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
740 const struct bpf_line_info *prev_linfo;
741 struct bpf_verifier_log log;
742 struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
743 union {
744 struct bpf_idmap idmap_scratch;
745 struct bpf_idset idset_scratch;
746 };
747 struct {
748 int *insn_state;
749 int *insn_stack;
750 int cur_stack;
751 } cfg;
752 struct backtrack_state bt;
753 struct bpf_jmp_history_entry *cur_hist_ent;
754 u32 pass_cnt; /* number of times do_check() was called */
755 u32 subprog_cnt;
756 /* number of instructions analyzed by the verifier */
757 u32 prev_insn_processed, insn_processed;
758 /* number of jmps, calls, exits analyzed so far */
759 u32 prev_jmps_processed, jmps_processed;
760 /* total verification time */
761 u64 verification_time;
762 /* maximum number of verifier states kept in 'branching' instructions */
763 u32 max_states_per_insn;
764 /* total number of allocated verifier states */
765 u32 total_states;
766 /* some states are freed during program analysis.
767 * this is peak number of states. this number dominates kernel
768 * memory consumption during verification
769 */
770 u32 peak_states;
771 /* longest register parentage chain walked for liveness marking */
772 u32 longest_mark_read_walk;
773 bpfptr_t fd_array;
774
775 /* bit mask to keep track of whether a register has been accessed
776 * since the last time the function state was printed
777 */
778 u32 scratched_regs;
779 /* Same as scratched_regs but for stack slots */
780 u64 scratched_stack_slots;
781 u64 prev_log_pos, prev_insn_print_pos;
782 /* buffer used to temporary hold constants as scalar registers */
783 struct bpf_reg_state fake_reg[2];
784 /* buffer used to generate temporary string representations,
785 * e.g., in reg_type_str() to generate reg_type string
786 */
787 char tmp_str_buf[TMP_STR_BUF_LEN];
788 struct bpf_insn insn_buf[INSN_BUF_SIZE];
789 struct bpf_insn epilogue_buf[INSN_BUF_SIZE];
790
791 ANDROID_KABI_RESERVE(1);
792 ANDROID_KABI_RESERVE(2);
793 };
794
subprog_aux(struct bpf_verifier_env * env,int subprog)795 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
796 {
797 return &env->prog->aux->func_info_aux[subprog];
798 }
799
subprog_info(struct bpf_verifier_env * env,int subprog)800 static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env, int subprog)
801 {
802 return &env->subprog_info[subprog];
803 }
804
805 __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,
806 const char *fmt, va_list args);
807 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
808 const char *fmt, ...);
809 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
810 const char *fmt, ...);
811 int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level,
812 char __user *log_buf, u32 log_size);
813 void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos);
814 int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual);
815
816 __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
817 u32 insn_off,
818 const char *prefix_fmt, ...);
819
cur_func(struct bpf_verifier_env * env)820 static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env)
821 {
822 struct bpf_verifier_state *cur = env->cur_state;
823
824 return cur->frame[cur->curframe];
825 }
826
cur_regs(struct bpf_verifier_env * env)827 static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env)
828 {
829 return cur_func(env)->regs;
830 }
831
832 int bpf_prog_offload_verifier_prep(struct bpf_prog *prog);
833 int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env,
834 int insn_idx, int prev_insn_idx);
835 int bpf_prog_offload_finalize(struct bpf_verifier_env *env);
836 void
837 bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off,
838 struct bpf_insn *insn);
839 void
840 bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt);
841
842 /* 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)843 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
844 struct btf *btf, u32 btf_id)
845 {
846 if (tgt_prog)
847 return ((u64)tgt_prog->aux->id << 32) | btf_id;
848 else
849 return ((u64)btf_obj_id(btf) << 32) | 0x80000000 | btf_id;
850 }
851
852 /* unpack the IDs from the key as constructed above */
bpf_trampoline_unpack_key(u64 key,u32 * obj_id,u32 * btf_id)853 static inline void bpf_trampoline_unpack_key(u64 key, u32 *obj_id, u32 *btf_id)
854 {
855 if (obj_id)
856 *obj_id = key >> 32;
857 if (btf_id)
858 *btf_id = key & 0x7FFFFFFF;
859 }
860
861 int bpf_check_attach_target(struct bpf_verifier_log *log,
862 const struct bpf_prog *prog,
863 const struct bpf_prog *tgt_prog,
864 u32 btf_id,
865 struct bpf_attach_target_info *tgt_info);
866 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
867
868 int mark_chain_precision(struct bpf_verifier_env *env, int regno);
869
870 #define BPF_BASE_TYPE_MASK GENMASK(BPF_BASE_TYPE_BITS - 1, 0)
871
872 /* extract base type from bpf_{arg, return, reg}_type. */
base_type(u32 type)873 static inline u32 base_type(u32 type)
874 {
875 return type & BPF_BASE_TYPE_MASK;
876 }
877
878 /* extract flags from an extended type. See bpf_type_flag in bpf.h. */
type_flag(u32 type)879 static inline u32 type_flag(u32 type)
880 {
881 return type & ~BPF_BASE_TYPE_MASK;
882 }
883
884 /* only use after check_attach_btf_id() */
resolve_prog_type(const struct bpf_prog * prog)885 static inline enum bpf_prog_type resolve_prog_type(const struct bpf_prog *prog)
886 {
887 return (prog->type == BPF_PROG_TYPE_EXT && prog->aux->saved_dst_prog_type) ?
888 prog->aux->saved_dst_prog_type : prog->type;
889 }
890
bpf_prog_check_recur(const struct bpf_prog * prog)891 static inline bool bpf_prog_check_recur(const struct bpf_prog *prog)
892 {
893 switch (resolve_prog_type(prog)) {
894 case BPF_PROG_TYPE_TRACING:
895 return prog->expected_attach_type != BPF_TRACE_ITER;
896 case BPF_PROG_TYPE_STRUCT_OPS:
897 case BPF_PROG_TYPE_LSM:
898 return false;
899 default:
900 return true;
901 }
902 }
903
904 #define BPF_REG_TRUSTED_MODIFIERS (MEM_ALLOC | PTR_TRUSTED | NON_OWN_REF)
905
bpf_type_has_unsafe_modifiers(u32 type)906 static inline bool bpf_type_has_unsafe_modifiers(u32 type)
907 {
908 return type_flag(type) & ~BPF_REG_TRUSTED_MODIFIERS;
909 }
910
type_is_ptr_alloc_obj(u32 type)911 static inline bool type_is_ptr_alloc_obj(u32 type)
912 {
913 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
914 }
915
type_is_non_owning_ref(u32 type)916 static inline bool type_is_non_owning_ref(u32 type)
917 {
918 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
919 }
920
type_is_pkt_pointer(enum bpf_reg_type type)921 static inline bool type_is_pkt_pointer(enum bpf_reg_type type)
922 {
923 type = base_type(type);
924 return type == PTR_TO_PACKET ||
925 type == PTR_TO_PACKET_META;
926 }
927
type_is_sk_pointer(enum bpf_reg_type type)928 static inline bool type_is_sk_pointer(enum bpf_reg_type type)
929 {
930 return type == PTR_TO_SOCKET ||
931 type == PTR_TO_SOCK_COMMON ||
932 type == PTR_TO_TCP_SOCK ||
933 type == PTR_TO_XDP_SOCK;
934 }
935
type_may_be_null(u32 type)936 static inline bool type_may_be_null(u32 type)
937 {
938 return type & PTR_MAYBE_NULL;
939 }
940
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)941 static inline void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
942 {
943 env->scratched_regs |= 1U << regno;
944 }
945
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)946 static inline void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
947 {
948 env->scratched_stack_slots |= 1ULL << spi;
949 }
950
reg_scratched(const struct bpf_verifier_env * env,u32 regno)951 static inline bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
952 {
953 return (env->scratched_regs >> regno) & 1;
954 }
955
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)956 static inline bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
957 {
958 return (env->scratched_stack_slots >> regno) & 1;
959 }
960
verifier_state_scratched(const struct bpf_verifier_env * env)961 static inline bool verifier_state_scratched(const struct bpf_verifier_env *env)
962 {
963 return env->scratched_regs || env->scratched_stack_slots;
964 }
965
mark_verifier_state_clean(struct bpf_verifier_env * env)966 static inline void mark_verifier_state_clean(struct bpf_verifier_env *env)
967 {
968 env->scratched_regs = 0U;
969 env->scratched_stack_slots = 0ULL;
970 }
971
972 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)973 static inline void mark_verifier_state_scratched(struct bpf_verifier_env *env)
974 {
975 env->scratched_regs = ~0U;
976 env->scratched_stack_slots = ~0ULL;
977 }
978
bpf_stack_narrow_access_ok(int off,int fill_size,int spill_size)979 static inline bool bpf_stack_narrow_access_ok(int off, int fill_size, int spill_size)
980 {
981 #ifdef __BIG_ENDIAN
982 off -= spill_size - fill_size;
983 #endif
984
985 return !(off % BPF_REG_SIZE);
986 }
987
988 const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type);
989 const char *dynptr_type_str(enum bpf_dynptr_type type);
990 const char *iter_type_str(const struct btf *btf, u32 btf_id);
991 const char *iter_state_str(enum bpf_iter_state state);
992
993 void print_verifier_state(struct bpf_verifier_env *env,
994 const struct bpf_func_state *state, bool print_all);
995 void print_insn_state(struct bpf_verifier_env *env, const struct bpf_func_state *state);
996
997 #endif /* _LINUX_BPF_VERIFIER_H */
998