xref: /linux/kernel/bpf/states.c (revision a8471eb0747f083ae5bde949e667d3d799d65cf7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
3 #include <linux/bpf.h>
4 #include <linux/bpf_verifier.h>
5 #include <linux/cnum.h>
6 #include <linux/filter.h>
7 
8 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
9 
10 #define BPF_COMPLEXITY_LIMIT_STATES	64
11 
12 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
13 {
14 	return bpf_is_may_goto_insn(&env->prog->insnsi[insn_idx]);
15 }
16 
17 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
18 {
19 	return env->insn_aux_data[insn_idx].is_iter_next;
20 }
21 
22 static void update_peak_states(struct bpf_verifier_env *env)
23 {
24 	u32 cur_states;
25 
26 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
27 	env->peak_states = max(env->peak_states, cur_states);
28 }
29 
30 /* struct bpf_verifier_state->parent refers to states
31  * that are in either of env->{expored_states,free_list}.
32  * In both cases the state is contained in struct bpf_verifier_state_list.
33  */
34 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
35 {
36 	if (st->parent)
37 		return container_of(st->parent, struct bpf_verifier_state_list, state);
38 	return NULL;
39 }
40 
41 static bool incomplete_read_marks(struct bpf_verifier_env *env,
42 				  struct bpf_verifier_state *st);
43 
44 /* A state can be freed if it is no longer referenced:
45  * - is in the env->free_list;
46  * - has no children states;
47  */
48 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
49 				      struct bpf_verifier_state_list *sl)
50 {
51 	if (!sl->in_free_list
52 	    || sl->state.branches != 0
53 	    || incomplete_read_marks(env, &sl->state))
54 		return;
55 	list_del(&sl->node);
56 	bpf_free_verifier_state(&sl->state, false);
57 	kfree(sl);
58 	env->free_list_size--;
59 }
60 
61 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
62  * if such frame exists form a corresponding @callchain as an array of
63  * call sites leading to this frame and SCC id.
64  * E.g.:
65  *
66  *    void foo()  { A: loop {... SCC#1 ...}; }
67  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
68  *                  D: loop { E: foo(); ... SCC#3 ... } }
69  *    void main() { F: bar(); }
70  *
71  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
72  * on @st frame call sites being (F,C,A) or (F,E,A).
73  */
74 static bool compute_scc_callchain(struct bpf_verifier_env *env,
75 				  struct bpf_verifier_state *st,
76 				  struct bpf_scc_callchain *callchain)
77 {
78 	u32 i, scc, insn_idx;
79 
80 	memset(callchain, 0, sizeof(*callchain));
81 	for (i = 0; i <= st->curframe; i++) {
82 		insn_idx = bpf_frame_insn_idx(st, i);
83 		scc = env->insn_aux_data[insn_idx].scc;
84 		if (scc) {
85 			callchain->scc = scc;
86 			break;
87 		} else if (i < st->curframe) {
88 			callchain->callsites[i] = insn_idx;
89 		} else {
90 			return false;
91 		}
92 	}
93 	return true;
94 }
95 
96 /* Check if bpf_scc_visit instance for @callchain exists. */
97 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
98 					      struct bpf_scc_callchain *callchain)
99 {
100 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
101 	struct bpf_scc_visit *visits = info->visits;
102 	u32 i;
103 
104 	if (!info)
105 		return NULL;
106 	for (i = 0; i < info->num_visits; i++)
107 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
108 			return &visits[i];
109 	return NULL;
110 }
111 
112 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
113  * Allocated instances are alive for a duration of the do_check_common()
114  * call and are freed by free_states().
115  */
116 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
117 					     struct bpf_scc_callchain *callchain)
118 {
119 	struct bpf_scc_visit *visit;
120 	struct bpf_scc_info *info;
121 	u32 scc, num_visits;
122 	u64 new_sz;
123 
124 	scc = callchain->scc;
125 	info = env->scc_info[scc];
126 	num_visits = info ? info->num_visits : 0;
127 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
128 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
129 	if (!info)
130 		return NULL;
131 	env->scc_info[scc] = info;
132 	info->num_visits = num_visits + 1;
133 	visit = &info->visits[num_visits];
134 	memset(visit, 0, sizeof(*visit));
135 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
136 	return visit;
137 }
138 
139 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
140 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
141 {
142 	char *buf = env->tmp_str_buf;
143 	int i, delta = 0;
144 
145 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
146 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
147 		if (!callchain->callsites[i])
148 			break;
149 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
150 				  callchain->callsites[i]);
151 	}
152 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
153 	return env->tmp_str_buf;
154 }
155 
156 /* If callchain for @st exists (@st is in some SCC), ensure that
157  * bpf_scc_visit instance for this callchain exists.
158  * If instance does not exist or is empty, assign visit->entry_state to @st.
159  */
160 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
161 {
162 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
163 	struct bpf_scc_visit *visit;
164 
165 	if (!compute_scc_callchain(env, st, callchain))
166 		return 0;
167 	visit = scc_visit_lookup(env, callchain);
168 	visit = visit ?: scc_visit_alloc(env, callchain);
169 	if (!visit)
170 		return -ENOMEM;
171 	if (!visit->entry_state) {
172 		visit->entry_state = st;
173 		if (env->log.level & BPF_LOG_LEVEL2)
174 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
175 	}
176 	return 0;
177 }
178 
179 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
180 
181 /* If callchain for @st exists (@st is in some SCC), make it empty:
182  * - set visit->entry_state to NULL;
183  * - flush accumulated backedges.
184  */
185 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
186 {
187 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
188 	struct bpf_scc_visit *visit;
189 
190 	if (!compute_scc_callchain(env, st, callchain))
191 		return 0;
192 	visit = scc_visit_lookup(env, callchain);
193 	if (!visit) {
194 		/*
195 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
196 		 * must exist for non-speculative paths. For non-speculative paths
197 		 * traversal stops when:
198 		 * a. Verification error is found, maybe_exit_scc() is not called.
199 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
200 		 *    of any SCC.
201 		 * c. A checkpoint is reached and matched. Checkpoints are created by
202 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
203 		 *    bpf_scc_visit instances for checkpoints within SCCs.
204 		 * (c) is the only case that can reach this point.
205 		 */
206 		if (!st->speculative) {
207 			verifier_bug(env, "scc exit: no visit info for call chain %s",
208 				     format_callchain(env, callchain));
209 			return -EFAULT;
210 		}
211 		return 0;
212 	}
213 	if (visit->entry_state != st)
214 		return 0;
215 	if (env->log.level & BPF_LOG_LEVEL2)
216 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
217 	visit->entry_state = NULL;
218 	env->num_backedges -= visit->num_backedges;
219 	visit->num_backedges = 0;
220 	update_peak_states(env);
221 	return propagate_backedges(env, visit);
222 }
223 
224 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
225  * and add @backedge to visit->backedges. @st callchain must exist.
226  */
227 static int add_scc_backedge(struct bpf_verifier_env *env,
228 			    struct bpf_verifier_state *st,
229 			    struct bpf_scc_backedge *backedge)
230 {
231 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
232 	struct bpf_scc_visit *visit;
233 
234 	if (!compute_scc_callchain(env, st, callchain)) {
235 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
236 			     st->insn_idx);
237 		return -EFAULT;
238 	}
239 	visit = scc_visit_lookup(env, callchain);
240 	if (!visit) {
241 		verifier_bug(env, "add backedge: no visit info for call chain %s",
242 			     format_callchain(env, callchain));
243 		return -EFAULT;
244 	}
245 	if (env->log.level & BPF_LOG_LEVEL2)
246 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
247 	backedge->next = visit->backedges;
248 	visit->backedges = backedge;
249 	visit->num_backedges++;
250 	env->num_backedges++;
251 	update_peak_states(env);
252 	return 0;
253 }
254 
255 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
256  * if state @st is in some SCC and not all execution paths starting at this
257  * SCC are fully explored.
258  */
259 static bool incomplete_read_marks(struct bpf_verifier_env *env,
260 				  struct bpf_verifier_state *st)
261 {
262 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
263 	struct bpf_scc_visit *visit;
264 
265 	if (!compute_scc_callchain(env, st, callchain))
266 		return false;
267 	visit = scc_visit_lookup(env, callchain);
268 	if (!visit)
269 		return false;
270 	return !!visit->backedges;
271 }
272 
273 int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
274 {
275 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
276 	struct bpf_verifier_state *parent;
277 	int err;
278 
279 	while (st) {
280 		u32 br = --st->branches;
281 
282 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
283 		 * but see comment in push_stack(), hence:
284 		 */
285 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
286 		if (br)
287 			break;
288 		err = maybe_exit_scc(env, st);
289 		if (err)
290 			return err;
291 		parent = st->parent;
292 		parent_sl = state_parent_as_list(st);
293 		if (sl)
294 			maybe_free_verifier_state(env, sl);
295 		st = parent;
296 		sl = parent_sl;
297 	}
298 	return 0;
299 }
300 
301 /* check %cur's range satisfies %old's */
302 static bool range_within(const struct bpf_reg_state *old,
303 			 const struct bpf_reg_state *cur)
304 {
305 	if (!cnum64_is_subset(old->r64, cur->r64) ||
306 	    !cnum32_is_subset(old->r32, cur->r32))
307 		return false;
308 
309 	if (old->step <= 1)
310 		return true;
311 
312 	if (cnum64_is_const(cur->r64))
313 		return imod((s64)cnum64_smin(cur->r64), old->step) == old->base;
314 
315 	/*
316 	 * Both `old` and `cur` define some sets of points.
317 	 * Return true, if points defined by `cur` are a subset of points defined by `old`:
318 	 * - bounds for `cur` should be within bounds for `old`;
319 	 * - cur->step should be dividable by old->step;
320 	 * - cur->base should start at integer number of old->step
321 	 *   steps from old->base.
322 	 *
323 	 * E.g. the following ranges are compatible:
324 	 * - old [0, 10] step 2
325 	 * - new [2, 10] step 4
326 	 */
327 	return cur->step % old->step == 0 &&
328 	       (cur->base - old->base) % old->step == 0;
329 }
330 
331 /* If in the old state two registers had the same id, then they need to have
332  * the same id in the new state as well.  But that id could be different from
333  * the old state, so we need to track the mapping from old to new ids.
334  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
335  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
336  * regs with a different old id could still have new id 9, we don't care about
337  * that.
338  * So we look through our idmap to see if this old id has been seen before.  If
339  * so, we require the new id to match; otherwise, we add the id pair to the map.
340  */
341 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
342 {
343 	struct bpf_id_pair *map = idmap->map;
344 	unsigned int i;
345 
346 	/* either both IDs should be set or both should be zero */
347 	if (!!old_id != !!cur_id)
348 		return false;
349 
350 	if (old_id == 0) /* cur_id == 0 as well */
351 		return true;
352 
353 	for (i = 0; i < idmap->cnt; i++) {
354 		if (map[i].old == old_id)
355 			return map[i].cur == cur_id;
356 		if (map[i].cur == cur_id)
357 			return false;
358 	}
359 
360 	/* Reached the end of known mappings; haven't seen this id before */
361 	if (idmap->cnt < BPF_ID_MAP_SIZE) {
362 		map[idmap->cnt].old = old_id;
363 		map[idmap->cnt].cur = cur_id;
364 		idmap->cnt++;
365 		return true;
366 	}
367 
368 	/*
369 	 * idmap slots are bounded by the number of registers and stack slots.
370 	 * Since referenced dynptrs acquire intermediate references that do
371 	 * not live in either, so the map can be exhausted. Since it is unlikely,
372 	 * fail the verification by treating the states as not equivalent.
373 	 */
374 	return false;
375 }
376 
377 /*
378  * Compare scalar register IDs for state equivalence.
379  *
380  * When old_id == 0, the old register is independent - not linked to any
381  * other register. Any linking in the current state only adds constraints,
382  * making it more restrictive. Since the old state didn't rely on any ID
383  * relationships for this register, it's always safe to accept cur regardless
384  * of its ID. Hence, return true immediately.
385  *
386  * When old_id != 0 but cur_id == 0, we need to ensure that different
387  * independent registers in cur don't incorrectly satisfy the ID matching
388  * requirements of linked registers in old.
389  *
390  * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0
391  * and r7.id=0 (both independent), without temp IDs both would map old_id=X
392  * to cur_id=0 and pass. With temp IDs: r6 maps X->temp1, r7 tries to map
393  * X->temp2, but X is already mapped to temp1, so the check fails correctly.
394  *
395  * When old_id has BPF_ADD_CONST set, the compound id (base | flag) and the
396  * base id (flag stripped) must both map consistently. Example: old has
397  * r2.id=A, r3.id=A|flag (r3 = r2 + delta), cur has r2.id=B, r3.id=C|flag
398  * (r3 derived from unrelated r4). Without the base check, idmap gets two
399  * independent entries A->B and A|flag->C|flag, missing that A->C conflicts
400  * with A->B. The base ID cross-check catches this.
401  */
402 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
403 {
404 	if (!old_id)
405 		return true;
406 
407 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
408 
409 	if (!check_ids(old_id, cur_id, idmap))
410 		return false;
411 	if (old_id & BPF_ADD_CONST) {
412 		old_id &= ~BPF_ADD_CONST;
413 		cur_id &= ~BPF_ADD_CONST;
414 		if (!check_ids(old_id, cur_id, idmap))
415 			return false;
416 	}
417 	return true;
418 }
419 
420 static void __clean_func_state(struct bpf_verifier_env *env,
421 			       struct bpf_func_state *st,
422 			       u16 live_regs, int frame)
423 {
424 	int i, j;
425 
426 	for (i = 0; i < BPF_REG_FP; i++) {
427 		/* liveness must not touch this register anymore */
428 		if (!(live_regs & BIT(i)))
429 			/* since the register is unused, clear its state
430 			 * to make further comparison simpler
431 			 */
432 			bpf_mark_reg_not_init(env, &st->regs[i]);
433 	}
434 
435 	/*
436 	 * Clean dead 4-byte halves within each SPI independently.
437 	 * half_spi 2*i   → lower half: slot_type[0..3] (closer to FP)
438 	 * half_spi 2*i+1 → upper half: slot_type[4..7] (farther from FP)
439 	 */
440 	for (i = 0; i < bpf_stack_nr_slots(st); i++) {
441 		bool lo_live = bpf_stack_slot_alive(env, frame, i * 2);
442 		bool hi_live = bpf_stack_slot_alive(env, frame, i * 2 + 1);
443 
444 		if (!hi_live || !lo_live) {
445 			int start = !lo_live ? 0 : BPF_REG_SIZE / 2;
446 			int end = !hi_live ? BPF_REG_SIZE : BPF_REG_SIZE / 2;
447 			u8 stype = bpf_stack_slot(st, i)->slot_type[7];
448 
449 			/*
450 			 * Don't clear special slots.
451 			 * destroy_if_dynptr_stack_slot() needs STACK_DYNPTR to
452 			 * detect overwrites and invalidate associated data slices.
453 			 * is_iter_reg_valid_uninit() and is_irq_flag_reg_valid_uninit()
454 			 * check for their respective slot types to detect double-create.
455 			 */
456 			if (stype == STACK_DYNPTR || stype == STACK_ITER ||
457 			    stype == STACK_IRQ_FLAG)
458 				continue;
459 
460 			/*
461 			 * Only scalar spills can be degraded to raw stack bytes
462 			 * when their high half is dead. Pointer spills need the
463 			 * saved spilled_ptr metadata so partial fills keep
464 			 * rejecting as non-scalar register fills.
465 			 */
466 			if (!hi_live) {
467 				struct bpf_reg_state *spill = &bpf_stack_slot(st, i)->spilled_ptr;
468 
469 				if (lo_live && stype == STACK_SPILL) {
470 					if (spill->type != SCALAR_VALUE)
471 						continue;
472 					/*
473 					 * Can't replace with STACK_ZERO, because
474 					 * that requires bpf_mark_chain_precision().
475 					 */
476 					if (bpf_register_is_null(spill))
477 						continue;
478 					for (j = 0; j < 4; j++) {
479 						u8 *t = &bpf_stack_slot(st, i)->slot_type[j];
480 
481 						if (*t == STACK_SPILL)
482 							*t = STACK_MISC;
483 					}
484 				}
485 				bpf_mark_reg_not_init(env, spill);
486 			}
487 			for (j = start; j < end; j++)
488 				bpf_stack_slot(st, i)->slot_type[j] = STACK_POISON;
489 		}
490 	}
491 }
492 
493 static int clean_verifier_state(struct bpf_verifier_env *env,
494 				 struct bpf_verifier_state *st)
495 {
496 	int i, err;
497 
498 	err = bpf_live_stack_query_init(env, st);
499 	if (err)
500 		return err;
501 	for (i = 0; i <= st->curframe; i++) {
502 		u32 ip = bpf_frame_insn_idx(st, i);
503 		u16 live_regs = env->insn_aux_data[ip].live_regs_before;
504 
505 		__clean_func_state(env, st->frame[i], live_regs, i);
506 	}
507 	return 0;
508 }
509 
510 static bool regs_exact(const struct bpf_reg_state *rold,
511 		       const struct bpf_reg_state *rcur,
512 		       struct bpf_idmap *idmap)
513 {
514 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
515 	       check_ids(rold->id, rcur->id, idmap) &&
516 	       check_ids(rold->parent_id, rcur->parent_id, idmap) &&
517 	       check_ids(rold->map_uid, rcur->map_uid, idmap);
518 }
519 
520 enum exact_level {
521 	NOT_EXACT,
522 	EXACT,
523 	RANGE_WITHIN
524 };
525 
526 /* Returns true if (rold safe implies rcur safe) */
527 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
528 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
529 		    enum exact_level exact)
530 {
531 	if (exact == EXACT)
532 		return regs_exact(rold, rcur, idmap);
533 
534 	if (rold->type == NOT_INIT)
535 		/* explored state can't have used this */
536 		return true;
537 
538 	/* Enforce that register types have to match exactly, including their
539 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
540 	 * rule.
541 	 *
542 	 * One can make a point that using a pointer register as unbounded
543 	 * SCALAR would be technically acceptable, but this could lead to
544 	 * pointer leaks because scalars are allowed to leak while pointers
545 	 * are not. We could make this safe in special cases if root is
546 	 * calling us, but it's probably not worth the hassle.
547 	 *
548 	 * Also, register types that are *not* MAYBE_NULL could technically be
549 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
550 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
551 	 * to the same map).
552 	 * However, if the old MAYBE_NULL register then got NULL checked,
553 	 * doing so could have affected others with the same id, and we can't
554 	 * check for that because we lost the id when we converted to
555 	 * a non-MAYBE_NULL variant.
556 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
557 	 * non-MAYBE_NULL registers as well.
558 	 */
559 	if (rold->type != rcur->type)
560 		return false;
561 
562 	switch (base_type(rold->type)) {
563 	case SCALAR_VALUE:
564 		if (env->explore_alu_limits) {
565 			/* explore_alu_limits disables tnum_in() and range_within()
566 			 * logic and requires everything to be strict
567 			 */
568 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
569 			       check_scalar_ids(rold->id, rcur->id, idmap);
570 		}
571 		if (!rold->precise && exact == NOT_EXACT)
572 			return true;
573 		/*
574 		 * Linked register tracking uses rold->id to detect relationships.
575 		 * When rold->id == 0, the register is independent and any linking
576 		 * in rcur only adds constraints. When rold->id != 0, we must verify
577 		 * id mapping and (for BPF_ADD_CONST) offset consistency.
578 		 *
579 		 * +------------------+-----------+------------------+---------------+
580 		 * |                  | rold->id  | rold + ADD_CONST | rold->id == 0 |
581 		 * |------------------+-----------+------------------+---------------|
582 		 * | rcur->id         | range,ids | false            | range         |
583 		 * | rcur + ADD_CONST | false     | range,ids,off    | range         |
584 		 * | rcur->id == 0    | range,ids | false            | range         |
585 		 * +------------------+-----------+------------------+---------------+
586 		 *
587 		 * Why check_ids() for scalar registers?
588 		 *
589 		 * Consider the following BPF code:
590 		 *   1: r6 = ... unbound scalar, ID=a ...
591 		 *   2: r7 = ... unbound scalar, ID=b ...
592 		 *   3: if (r6 > r7) goto +1
593 		 *   4: r6 = r7
594 		 *   5: if (r6 > X) goto ...
595 		 *   6: ... memory operation using r7 ...
596 		 *
597 		 * First verification path is [1-6]:
598 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
599 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
600 		 *   r7 <= X, because r6 and r7 share same id.
601 		 * Next verification path is [1-4, 6].
602 		 *
603 		 * Instruction (6) would be reached in two states:
604 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
605 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
606 		 *
607 		 * Use check_ids() to distinguish these states.
608 		 * ---
609 		 * Also verify that new value satisfies old value range knowledge.
610 		 */
611 
612 		/*
613 		 * ADD_CONST flags must match exactly: BPF_ADD_CONST32 and
614 		 * BPF_ADD_CONST64 have different linking semantics in
615 		 * sync_linked_regs() (alu32 zero-extends, alu64 does not),
616 		 * so pruning across different flag types is unsafe.
617 		 */
618 		if (rold->id &&
619 		    (rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
620 			return false;
621 
622 		/* Both have offset linkage: offsets must match */
623 		if ((rold->id & BPF_ADD_CONST) && rold->delta != rcur->delta)
624 			return false;
625 
626 		if (!check_scalar_ids(rold->id, rcur->id, idmap))
627 			return false;
628 
629 		return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off);
630 	case PTR_TO_MAP_KEY:
631 	case PTR_TO_MAP_VALUE:
632 	case PTR_TO_MEM:
633 	case PTR_TO_BUF:
634 	case PTR_TO_TP_BUFFER:
635 	case PTR_TO_STACK:
636 	case PTR_TO_BTF_ID:
637 		/* If the new min/max/var_off satisfy the old ones and
638 		 * everything else matches, we are OK.
639 		 */
640 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
641 		       range_within(rold, rcur) &&
642 		       tnum_in(rold->var_off, rcur->var_off) &&
643 		       check_ids(rold->id, rcur->id, idmap) &&
644 		       check_ids(rold->parent_id, rcur->parent_id, idmap) &&
645 		       check_ids(rold->map_uid, rcur->map_uid, idmap);
646 	case PTR_TO_PACKET_META:
647 	case PTR_TO_PACKET:
648 		/* We must have at least as much range as the old ptr
649 		 * did, so that any accesses which were safe before are
650 		 * still safe.  This is true even if old range < old off,
651 		 * since someone could have accessed through (ptr - k), or
652 		 * even done ptr -= k in a register, to get a safe access.
653 		 */
654 		if (rold->range < 0 || rcur->range < 0) {
655 			/* special case for [BEYOND|AT]_PKT_END */
656 			if (rold->range != rcur->range)
657 				return false;
658 		} else if (rold->range > rcur->range) {
659 			return false;
660 		}
661 		/* id relations must be preserved */
662 		if (!check_ids(rold->id, rcur->id, idmap))
663 			return false;
664 		/* Preserve displacements between pointers sharing an ID. */
665 		if (rold->id && rold->r64.base != rcur->r64.base)
666 			return false;
667 		/* new val must satisfy old val knowledge */
668 		return range_within(rold, rcur) &&
669 		       tnum_in(rold->var_off, rcur->var_off);
670 	case PTR_TO_ARENA:
671 		return true;
672 	case PTR_TO_INSN:
673 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
674 		       range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off);
675 	default:
676 		return regs_exact(rold, rcur, idmap);
677 	}
678 }
679 
680 static struct bpf_reg_state unbound_reg;
681 
682 static __init int unbound_reg_init(void)
683 {
684 	bpf_mark_reg_unknown_imprecise(&unbound_reg);
685 	return 0;
686 }
687 late_initcall(unbound_reg_init);
688 
689 static bool is_spilled_scalar_after(const struct bpf_stack_state *stack, int im)
690 {
691 	return stack->slot_type[im] == STACK_SPILL &&
692 	       stack->spilled_ptr.type == SCALAR_VALUE;
693 }
694 
695 static bool is_stack_misc_after(struct bpf_verifier_env *env,
696 				struct bpf_stack_state *stack, int im)
697 {
698 	u32 i;
699 
700 	for (i = im; i < ARRAY_SIZE(stack->slot_type); ++i) {
701 		if ((stack->slot_type[i] == STACK_MISC) ||
702 		    ((stack->slot_type[i] == STACK_INVALID || stack->slot_type[i] == STACK_POISON) &&
703 		     env->allow_uninit_stack))
704 			continue;
705 		return false;
706 	}
707 
708 	return true;
709 }
710 
711 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
712 						  struct bpf_stack_state *stack, int im)
713 {
714 	if (is_spilled_scalar_after(stack, im))
715 		return &stack->spilled_ptr;
716 
717 	if (is_stack_misc_after(env, stack, im))
718 		return &unbound_reg;
719 
720 	return NULL;
721 }
722 
723 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
724 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
725 		      enum exact_level exact)
726 {
727 	int i, spi;
728 
729 	/* walk slots of the explored stack and ignore any additional
730 	 * slots in the current stack, since explored(safe) state
731 	 * didn't use them
732 	 */
733 	for (i = 0; i < old->allocated_stack; i++) {
734 		struct bpf_stack_state *old_slot, *cur_slot;
735 		struct bpf_reg_state *old_reg, *cur_reg;
736 		int im = i % BPF_REG_SIZE;
737 		u8 old_type;
738 
739 		spi = i / BPF_REG_SIZE;
740 		old_slot = bpf_stack_slot(old, spi);
741 		old_type = old_slot->slot_type[im];
742 		cur_slot = i < cur->allocated_stack ? bpf_stack_slot(cur, spi) : NULL;
743 
744 		if (exact == EXACT) {
745 			u8 cur_type = cur_slot ? cur_slot->slot_type[im] : STACK_INVALID;
746 
747 			/* STACK_INVALID and STACK_POISON are equivalent for pruning */
748 			if (old_type == STACK_POISON)
749 				old_type = STACK_INVALID;
750 			if (cur_type == STACK_POISON)
751 				cur_type = STACK_INVALID;
752 			if (!cur_slot || old_type != cur_type)
753 				return false;
754 		}
755 
756 		if (old_type == STACK_INVALID || old_type == STACK_POISON)
757 			continue;
758 
759 		if (env->allow_uninit_stack && old_type == STACK_MISC)
760 			continue;
761 
762 		/* explored stack has more populated slots than current stack
763 		 * and these slots were used
764 		 */
765 		if (!cur_slot)
766 			return false;
767 
768 		/*
769 		 * 64 and 32-bit scalar spills vs MISC/INVALID slots and vice versa.
770 		 * Load from MISC/INVALID slots produces unbound scalar.
771 		 * Construct a fake register for such stack and call
772 		 * regsafe() to ensure scalar ids are compared.
773 		 */
774 		if (im == 0 || im == 4) {
775 			old_reg = scalar_reg_for_stack(env, old_slot, im);
776 			cur_reg = scalar_reg_for_stack(env, cur_slot, im);
777 			if (old_reg && cur_reg) {
778 				if (!regsafe(env, old_reg, cur_reg, idmap, exact))
779 					return false;
780 				i += (im == 0 ? BPF_REG_SIZE - 1 : 3);
781 				continue;
782 			}
783 		}
784 
785 		/* if old state was safe with misc data in the stack
786 		 * it will be safe with zero-initialized stack.
787 		 * The opposite is not true
788 		 */
789 		if (old_type == STACK_MISC && cur_slot->slot_type[im] == STACK_ZERO)
790 			continue;
791 		if (old_type != cur_slot->slot_type[im])
792 			/* Ex: old explored (safe) state has STACK_SPILL in
793 			 * this stack slot, but current has STACK_MISC ->
794 			 * this verifier states are not equivalent,
795 			 * return false to continue verification of this path
796 			 */
797 			return false;
798 		if (im != BPF_REG_SIZE - 1)
799 			continue;
800 		/* Both old and cur are having same slot_type */
801 		switch (old_type) {
802 		case STACK_SPILL:
803 			/* when explored and current stack slot are both storing
804 			 * spilled registers, check that stored pointers types
805 			 * are the same as well.
806 			 * Ex: explored safe path could have stored
807 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
808 			 * but current path has stored:
809 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
810 			 * such verifier states are not equivalent.
811 			 * return false to continue verification of this path
812 			 */
813 			if (!regsafe(env, &old_slot->spilled_ptr, &cur_slot->spilled_ptr,
814 				     idmap, exact))
815 				return false;
816 			break;
817 		case STACK_DYNPTR:
818 			old_reg = &old_slot->spilled_ptr;
819 			cur_reg = &cur_slot->spilled_ptr;
820 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
821 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
822 			    !check_ids(old_reg->id, cur_reg->id, idmap) ||
823 			    !check_ids(old_reg->parent_id, cur_reg->parent_id, idmap))
824 				return false;
825 			break;
826 		case STACK_ITER:
827 			old_reg = &old_slot->spilled_ptr;
828 			cur_reg = &cur_slot->spilled_ptr;
829 			/* iter.depth is not compared between states as it
830 			 * doesn't matter for correctness and would otherwise
831 			 * prevent convergence; we maintain it only to prevent
832 			 * infinite loop check triggering, see
833 			 * iter_active_depths_differ()
834 			 */
835 			if (old_reg->type != cur_reg->type ||
836 			    old_reg->iter.btf != cur_reg->iter.btf ||
837 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
838 			    old_reg->iter.state != cur_reg->iter.state ||
839 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
840 			    !check_ids(old_reg->id, cur_reg->id, idmap))
841 				return false;
842 			break;
843 		case STACK_IRQ_FLAG:
844 			old_reg = &old_slot->spilled_ptr;
845 			cur_reg = &cur_slot->spilled_ptr;
846 			if (!check_ids(old_reg->id, cur_reg->id, idmap) ||
847 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
848 				return false;
849 			break;
850 		case STACK_MISC:
851 		case STACK_ZERO:
852 		case STACK_INVALID:
853 		case STACK_POISON:
854 			continue;
855 		/* Ensure that new unhandled slot types return false by default */
856 		default:
857 			return false;
858 		}
859 	}
860 	return true;
861 }
862 
863 /*
864  * Compare stack arg slots between old and current states.
865  * Outgoing stack args are path-local state and must agree for pruning.
866  */
867 static bool stack_arg_safe(struct bpf_verifier_env *env, struct bpf_func_state *old,
868 			   struct bpf_func_state *cur, struct bpf_idmap *idmap,
869 			   enum exact_level exact)
870 {
871 	int i, nslots;
872 
873 	nslots = max(old->out_stack_arg_cnt, cur->out_stack_arg_cnt);
874 	for (i = 0; i < nslots; i++) {
875 		struct bpf_reg_state *old_arg, *cur_arg;
876 		struct bpf_reg_state not_init = { .type = NOT_INIT };
877 
878 		old_arg = i < old->out_stack_arg_cnt ?
879 			  &old->stack_arg_regs[i] : &not_init;
880 		cur_arg = i < cur->out_stack_arg_cnt ?
881 			  &cur->stack_arg_regs[i] : &not_init;
882 		if (!regsafe(env, old_arg, cur_arg, idmap, exact))
883 			return false;
884 	}
885 
886 	return true;
887 }
888 
889 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
890 		    struct bpf_idmap *idmap)
891 {
892 	int i;
893 
894 	if (old->acquired_refs != cur->acquired_refs)
895 		return false;
896 
897 	if (old->active_locks != cur->active_locks)
898 		return false;
899 
900 	if (old->active_preempt_locks != cur->active_preempt_locks)
901 		return false;
902 
903 	if (old->active_rcu_locks != cur->active_rcu_locks)
904 		return false;
905 
906 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
907 		return false;
908 
909 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
910 	    old->active_lock_ptr != cur->active_lock_ptr)
911 		return false;
912 
913 	for (i = 0; i < old->acquired_refs; i++) {
914 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
915 		    old->refs[i].type != cur->refs[i].type)
916 			return false;
917 		switch (old->refs[i].type) {
918 		case REF_TYPE_PTR:
919 			if (!check_ids(old->refs[i].parent_id, cur->refs[i].parent_id, idmap))
920 				return false;
921 			break;
922 		case REF_TYPE_IRQ:
923 			break;
924 		case REF_TYPE_LOCK:
925 		case REF_TYPE_RES_LOCK:
926 		case REF_TYPE_RES_LOCK_IRQ:
927 			if (old->refs[i].ptr != cur->refs[i].ptr)
928 				return false;
929 			break;
930 		default:
931 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
932 			return false;
933 		}
934 	}
935 
936 	return true;
937 }
938 
939 static bool loop_stack_safe(struct bpf_verifier_env *env, struct bpf_func_state *old,
940 			    struct bpf_func_state *cur)
941 {
942 	struct loop_stack_entry *old_stack = old->loop_stack;
943 	struct loop_stack_entry *cur_stack = cur->loop_stack;
944 	u32 i;
945 
946 	if (old->loop_stack_cnt != cur->loop_stack_cnt)
947 		return false;
948 
949 	for (i = 0; i < old->loop_stack_cnt; i++) {
950 		if (old_stack[i].loop_id == cur_stack[i].loop_id &&
951 		    old_stack[i].max_header_count == cur_stack[i].max_header_count &&
952 		    old_stack[i].terminates == cur_stack[i].terminates)
953 			continue;
954 		return false;
955 	}
956 
957 	return true;
958 }
959 
960 /* compare two verifier states
961  *
962  * all states stored in state_list are known to be valid, since
963  * verifier reached 'bpf_exit' instruction through them
964  *
965  * this function is called when verifier exploring different branches of
966  * execution popped from the state stack. If it sees an old state that has
967  * more strict register state and more strict stack state then this execution
968  * branch doesn't need to be explored further, since verifier already
969  * concluded that more strict state leads to valid finish.
970  *
971  * Therefore two states are equivalent if register state is more conservative
972  * and explored stack state is more conservative than the current one.
973  * Example:
974  *       explored                   current
975  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
976  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
977  *
978  * In other words if current stack state (one being explored) has more
979  * valid slots than old one that already passed validation, it means
980  * the verifier can stop exploring and conclude that current state is valid too
981  *
982  * Similarly with registers. If explored state has register type as invalid
983  * whereas register type in current state is meaningful, it means that
984  * the current state will reach 'bpf_exit' instruction safely
985  */
986 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
987 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
988 {
989 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
990 	u16 i;
991 
992 	if (old->callback_depth > cur->callback_depth)
993 		return false;
994 
995 	if (!old->no_stack_arg_load && cur->no_stack_arg_load)
996 		return false;
997 
998 	if (old->in_rcu_callback_fn != cur->in_rcu_callback_fn)
999 		return false;
1000 
1001 	for (i = 0; i < MAX_BPF_REG; i++)
1002 		if (((1 << i) & live_regs) &&
1003 		    !regsafe(env, &old->regs[i], &cur->regs[i],
1004 			     &env->idmap_scratch, exact))
1005 			return false;
1006 
1007 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
1008 		return false;
1009 
1010 	if (!stack_arg_safe(env, old, cur, &env->idmap_scratch, exact))
1011 		return false;
1012 
1013 	if (!loop_stack_safe(env, old, cur))
1014 		return false;
1015 
1016 	return true;
1017 }
1018 
1019 static void reset_idmap_scratch(struct bpf_verifier_env *env)
1020 {
1021 	struct bpf_idmap *idmap = &env->idmap_scratch;
1022 
1023 	idmap->tmp_id_gen = env->id_gen;
1024 	idmap->cnt = 0;
1025 }
1026 
1027 static bool states_equal(struct bpf_verifier_env *env,
1028 			 struct bpf_verifier_state *old,
1029 			 struct bpf_verifier_state *cur,
1030 			 enum exact_level exact)
1031 {
1032 	u32 insn_idx;
1033 	int i;
1034 
1035 	if (old->curframe != cur->curframe)
1036 		return false;
1037 
1038 	reset_idmap_scratch(env);
1039 
1040 	/* Verification state from speculative execution simulation
1041 	 * must never prune a non-speculative execution one.
1042 	 */
1043 	if (old->speculative && !cur->speculative)
1044 		return false;
1045 
1046 	if (old->in_sleepable != cur->in_sleepable)
1047 		return false;
1048 
1049 	if (!refsafe(old, cur, &env->idmap_scratch))
1050 		return false;
1051 
1052 	/* for states to be equal callsites have to be the same
1053 	 * and all frame states need to be equivalent
1054 	 */
1055 	for (i = 0; i <= old->curframe; i++) {
1056 		insn_idx = bpf_frame_insn_idx(old, i);
1057 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
1058 			return false;
1059 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
1060 			return false;
1061 	}
1062 
1063 	return true;
1064 }
1065 
1066 /* find precise scalars in the previous equivalent state and
1067  * propagate them into the current state
1068  */
1069 static int propagate_precision(struct bpf_verifier_env *env,
1070 			       const struct bpf_verifier_state *old,
1071 			       struct bpf_verifier_state *cur,
1072 			       bool *changed)
1073 {
1074 	struct bpf_reg_state *state_reg;
1075 	struct bpf_func_state *state;
1076 	int i, err = 0, fr;
1077 	bool first;
1078 
1079 	for (fr = old->curframe; fr >= 0; fr--) {
1080 		state = old->frame[fr];
1081 		state_reg = state->regs;
1082 		first = true;
1083 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
1084 			if (state_reg->type != SCALAR_VALUE ||
1085 			    !state_reg->precise)
1086 				continue;
1087 			if (env->log.level & BPF_LOG_LEVEL2) {
1088 				if (first)
1089 					verbose(env, "frame %d: propagating r%d", fr, i);
1090 				else
1091 					verbose(env, ",r%d", i);
1092 			}
1093 			bpf_bt_set_frame_reg(&env->bt, fr, i);
1094 			first = false;
1095 		}
1096 
1097 		for (i = 0; i < bpf_stack_nr_slots(state); i++) {
1098 			struct bpf_stack_state *ss = bpf_stack_slot(state, i);
1099 
1100 			if (!bpf_is_spilled_reg(ss))
1101 				continue;
1102 			state_reg = &ss->spilled_ptr;
1103 			if (state_reg->type != SCALAR_VALUE ||
1104 			    !state_reg->precise)
1105 				continue;
1106 			if (env->log.level & BPF_LOG_LEVEL2) {
1107 				if (first)
1108 					verbose(env, "frame %d: propagating fp%d",
1109 						fr, (-i - 1) * BPF_REG_SIZE);
1110 				else
1111 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
1112 			}
1113 			bpf_bt_set_frame_slot(&env->bt, fr, i);
1114 			first = false;
1115 		}
1116 		if (!first && (env->log.level & BPF_LOG_LEVEL2))
1117 			verbose(env, "\n");
1118 	}
1119 
1120 	err = bpf_mark_chain_precision(env, cur, -1, changed);
1121 	if (err < 0)
1122 		return err;
1123 
1124 	return 0;
1125 }
1126 
1127 #define MAX_BACKEDGE_ITERS 64
1128 
1129 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
1130  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
1131  * then free visit->backedges.
1132  * After execution of this function incomplete_read_marks() will return false
1133  * for all states corresponding to @visit->callchain.
1134  */
1135 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
1136 {
1137 	struct bpf_scc_backedge *backedge;
1138 	struct bpf_verifier_state *st;
1139 	bool changed;
1140 	int i, err;
1141 
1142 	i = 0;
1143 	do {
1144 		if (i++ > MAX_BACKEDGE_ITERS) {
1145 			if (env->log.level & BPF_LOG_LEVEL2)
1146 				verbose(env, "%s: too many iterations\n", __func__);
1147 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
1148 				bpf_mark_all_scalars_precise(env, &backedge->state);
1149 			break;
1150 		}
1151 		changed = false;
1152 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
1153 			st = &backedge->state;
1154 			err = propagate_precision(env, st->equal_state, st, &changed);
1155 			if (err)
1156 				return err;
1157 		}
1158 	} while (changed);
1159 
1160 	bpf_free_backedges(visit);
1161 	return 0;
1162 }
1163 
1164 static bool states_maybe_looping(struct bpf_verifier_state *old,
1165 				 struct bpf_verifier_state *cur)
1166 {
1167 	struct bpf_func_state *fold, *fcur;
1168 	int i, fr = cur->curframe;
1169 
1170 	if (old->curframe != fr)
1171 		return false;
1172 
1173 	fold = old->frame[fr];
1174 	fcur = cur->frame[fr];
1175 	for (i = 0; i < MAX_BPF_REG; i++)
1176 		if (memcmp(&fold->regs[i], &fcur->regs[i],
1177 			   offsetofend(struct bpf_reg_state, step)))
1178 			return false;
1179 	return true;
1180 }
1181 
1182 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
1183  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
1184  * states to match, which otherwise would look like an infinite loop. So while
1185  * iter_next() calls are taken care of, we still need to be careful and
1186  * prevent erroneous and too eager declaration of "infinite loop", when
1187  * iterators are involved.
1188  *
1189  * Here's a situation in pseudo-BPF assembly form:
1190  *
1191  *   0: again:                          ; set up iter_next() call args
1192  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
1193  *   2:   call bpf_iter_num_next        ; this is iter_next() call
1194  *   3:   if r0 == 0 goto done
1195  *   4:   ... something useful here ...
1196  *   5:   goto again                    ; another iteration
1197  *   6: done:
1198  *   7:   r1 = &it
1199  *   8:   call bpf_iter_num_destroy     ; clean up iter state
1200  *   9:   exit
1201  *
1202  * This is a typical loop. Let's assume that we have a prune point at 1:,
1203  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
1204  * again`, assuming other heuristics don't get in a way).
1205  *
1206  * When we first time come to 1:, let's say we have some state X. We proceed
1207  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
1208  * Now we come back to validate that forked ACTIVE state. We proceed through
1209  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
1210  * are converging. But the problem is that we don't know that yet, as this
1211  * convergence has to happen at iter_next() call site only. So if nothing is
1212  * done, at 1: verifier will use bounded loop logic and declare infinite
1213  * looping (and would be *technically* correct, if not for iterator's
1214  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
1215  * don't want that. So what we do in process_iter_next_call() when we go on
1216  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
1217  * a different iteration. So when we suspect an infinite loop, we additionally
1218  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
1219  * pretend we are not looping and wait for next iter_next() call.
1220  *
1221  * This only applies to ACTIVE state. In DRAINED state we don't expect to
1222  * loop, because that would actually mean infinite loop, as DRAINED state is
1223  * "sticky", and so we'll keep returning into the same instruction with the
1224  * same state (at least in one of possible code paths).
1225  *
1226  * This approach allows to keep infinite loop heuristic even in the face of
1227  * active iterator. E.g., C snippet below is and will be detected as
1228  * infinitely looping:
1229  *
1230  *   struct bpf_iter_num it;
1231  *   int *p, x;
1232  *
1233  *   bpf_iter_num_new(&it, 0, 10);
1234  *   while ((p = bpf_iter_num_next(&t))) {
1235  *       x = p;
1236  *       while (x--) {} // <<-- infinite loop here
1237  *   }
1238  *
1239  */
1240 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
1241 {
1242 	struct bpf_reg_state *slot, *cur_slot;
1243 	struct bpf_func_state *state;
1244 	int i, fr;
1245 
1246 	for (fr = old->curframe; fr >= 0; fr--) {
1247 		state = old->frame[fr];
1248 		for (i = 0; i < bpf_stack_nr_slots(state); i++) {
1249 			struct bpf_stack_state *ss = bpf_stack_slot(state, i);
1250 
1251 			if (ss->slot_type[0] != STACK_ITER)
1252 				continue;
1253 
1254 			slot = &ss->spilled_ptr;
1255 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
1256 				continue;
1257 
1258 			cur_slot = &bpf_stack_slot(cur->frame[fr], i)->spilled_ptr;
1259 			if (cur_slot->iter.depth != slot->iter.depth)
1260 				return true;
1261 		}
1262 	}
1263 	return false;
1264 }
1265 
1266 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1267 {
1268 	struct bpf_func_state *func;
1269 	struct bpf_reg_state *reg;
1270 	int i, j;
1271 
1272 	for (i = 0; i <= st->curframe; i++) {
1273 		func = st->frame[i];
1274 		for (j = 0; j < BPF_REG_FP; j++) {
1275 			reg = &func->regs[j];
1276 			if (reg->type != SCALAR_VALUE)
1277 				continue;
1278 			reg->precise = false;
1279 		}
1280 		for (j = 0; j < bpf_stack_nr_slots(func); j++) {
1281 			struct bpf_stack_state *ss = bpf_stack_slot(func, j);
1282 
1283 			if (!bpf_is_spilled_reg(ss))
1284 				continue;
1285 			reg = &ss->spilled_ptr;
1286 			if (reg->type != SCALAR_VALUE)
1287 				continue;
1288 			reg->precise = false;
1289 		}
1290 	}
1291 }
1292 
1293 int bpf_split_cur_state(struct bpf_verifier_env *env)
1294 {
1295 	struct bpf_verifier_state *cur = env->cur_state, *new;
1296 	struct bpf_verifier_state_list *new_sl;
1297 	struct list_head *head;
1298 	int insn_idx = cur->insn_idx;
1299 	int err;
1300 
1301 	head = bpf_explored_state(env, insn_idx);
1302 	new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);
1303 	if (!new_sl)
1304 		return -ENOMEM;
1305 	env->total_states++;
1306 	env->explored_states_size++;
1307 	update_peak_states(env);
1308 	env->prev_jmps_processed = env->jmps_processed;
1309 	env->prev_insn_processed = env->insn_processed;
1310 
1311 	/* forget precise markings we inherited, see __mark_chain_precision */
1312 	if (env->bpf_capable)
1313 		mark_all_scalars_imprecise(env, cur);
1314 
1315 	bpf_clear_singular_ids(env, cur);
1316 
1317 	/* add new state to the head of linked list */
1318 	new = &new_sl->state;
1319 	err = bpf_copy_verifier_state(new, cur);
1320 	if (err) {
1321 		bpf_free_verifier_state(new, false);
1322 		kfree(new_sl);
1323 		return err;
1324 	}
1325 	new->insn_idx = insn_idx;
1326 	verifier_bug_if(new->branches != 1, env,
1327 			"%s:branches_to_explore=%d insn %d",
1328 			__func__, new->branches, insn_idx);
1329 	err = maybe_enter_scc(env, new);
1330 	if (err) {
1331 		bpf_free_verifier_state(new, false);
1332 		kfree(new_sl);
1333 		return err;
1334 	}
1335 
1336 	cur->parent = new;
1337 	cur->last_insn_idx = -1;
1338 	cur->first_insn_idx = insn_idx;
1339 	cur->dfs_depth = new->dfs_depth + 1;
1340 	bpf_clear_jmp_history(cur);
1341 	list_add(&new_sl->node, head);
1342 	return 0;
1343 }
1344 
1345 /* Force a checkpoint upon reaching a loop header for a terminating loop. */
1346 static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx)
1347 {
1348 	struct bpf_verifier_state *cur = env->cur_state;
1349 	struct bpf_func_state *frame = cur->frame[cur->curframe];
1350 	struct loop_stack_entry *top;
1351 
1352 	if (bpf_loop_at_index(env, insn_idx) != insn_idx || !frame->loop_stack_cnt)
1353 		return false;
1354 	top = &frame->loop_stack[frame->loop_stack_cnt - 1];
1355 	return top->loop_id == insn_idx && top->terminates;
1356 }
1357 
1358 static struct loop_stack_entry *current_loop(struct bpf_verifier_state *st)
1359 {
1360 	struct bpf_func_state *frame = st->frame[st->curframe];
1361 
1362 	if (frame->loop_stack_cnt == 0)
1363 		return NULL;
1364 	return &frame->loop_stack[frame->loop_stack_cnt - 1];
1365 }
1366 
1367 int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
1368 {
1369 	struct loop_stack_entry *old_loop, *cur_loop;
1370 	struct bpf_verifier_state_list *sl;
1371 	struct bpf_verifier_state *cur = env->cur_state;
1372 	bool force_new_state, add_new_state, loop, loop_checkpoint;
1373 	int n, err, states_cnt = 0;
1374 	struct list_head *pos, *tmp, *head;
1375 
1376 	loop_checkpoint = need_loop_checkpoint(env, insn_idx);
1377 	force_new_state = env->test_state_freq || bpf_is_force_checkpoint(env, insn_idx) ||
1378 			  loop_checkpoint ||
1379 			  /* Avoid accumulating infinitely long jmp history */
1380 			  cur->jmp_history_cnt > 40;
1381 
1382 	/* bpf progs typically have pruning point every 4 instructions
1383 	 * http://vger.kernel.org/bpfconf2019.html#session-1
1384 	 * Do not add new state for future pruning if the verifier hasn't seen
1385 	 * at least 2 jumps and at least 8 instructions.
1386 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
1387 	 * In tests that amounts to up to 50% reduction into total verifier
1388 	 * memory consumption and 20% verifier time speedup.
1389 	 */
1390 	add_new_state = force_new_state;
1391 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
1392 	    env->insn_processed - env->prev_insn_processed >= 8)
1393 		add_new_state = true;
1394 
1395 	/* keep cleaning the current state as registers/stack become dead */
1396 	err = clean_verifier_state(env, cur);
1397 	if (err)
1398 		return err;
1399 
1400 	loop = false;
1401 	head = bpf_explored_state(env, insn_idx);
1402 	list_for_each_safe(pos, tmp, head) {
1403 		sl = container_of(pos, struct bpf_verifier_state_list, node);
1404 		states_cnt++;
1405 		if (sl->state.insn_idx != insn_idx)
1406 			continue;
1407 
1408 		if (sl->state.branches) {
1409 			struct bpf_func_state *old_top_frame = sl->state.frame[0];
1410 
1411 			if (old_top_frame->in_async_callback_fn &&
1412 			    old_top_frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) {
1413 				/* Different async_entry_cnt means that the verifier is
1414 				 * processing another entry into async callback.
1415 				 * Seeing the same state is not an indication of infinite
1416 				 * loop or infinite recursion.
1417 				 * But finding the same state doesn't mean that it's safe
1418 				 * to stop processing the current state. The previous state
1419 				 * hasn't yet reached bpf_exit, since state.branches > 0.
1420 				 * Checking in_async_callback_fn alone is not enough either.
1421 				 * Since the verifier still needs to catch infinite loops
1422 				 * inside async callbacks.
1423 				 */
1424 				goto skip_inf_loop_check;
1425 			}
1426 			/* BPF open-coded iterators loop detection is special.
1427 			 * states_maybe_looping() logic is too simplistic in detecting
1428 			 * states that *might* be equivalent, because it doesn't know
1429 			 * about ID remapping, so don't even perform it.
1430 			 * See process_iter_next_call() and iter_active_depths_differ()
1431 			 * for overview of the logic. When current and one of parent
1432 			 * states are detected as equivalent, it's a good thing: we prove
1433 			 * convergence and can stop simulating further iterations.
1434 			 * It's safe to assume that iterator loop will finish, taking into
1435 			 * account iter_next() contract of eventually returning
1436 			 * sticky NULL result.
1437 			 *
1438 			 * Note, that states have to be compared exactly in this case because
1439 			 * read and precision marks might not be finalized inside the loop.
1440 			 * E.g. as in the program below:
1441 			 *
1442 			 *     1. r7 = -16
1443 			 *     2. r6 = bpf_get_prandom_u32()
1444 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
1445 			 *     4.   if (r6 != 42) {
1446 			 *     5.     r7 = -32
1447 			 *     6.     r6 = bpf_get_prandom_u32()
1448 			 *     7.     continue
1449 			 *     8.   }
1450 			 *     9.   r0 = r10
1451 			 *    10.   r0 += r7
1452 			 *    11.   r8 = *(u64 *)(r0 + 0)
1453 			 *    12.   r6 = bpf_get_prandom_u32()
1454 			 *    13. }
1455 			 *
1456 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
1457 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
1458 			 * not have read or precision mark for r7 yet, thus inexact states
1459 			 * comparison would discard current state with r7=-32
1460 			 * => unsafe memory access at 11 would not be caught.
1461 			 */
1462 			if (is_iter_next_insn(env, insn_idx)) {
1463 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
1464 					struct bpf_func_state *cur_frame, *iter_frame, *old_frame;
1465 					struct bpf_reg_state *iter_state, *iter_reg;
1466 					struct bpf_reg_state *old_iter;
1467 					int spi;
1468 
1469 					cur_frame = cur->frame[cur->curframe];
1470 					/* btf_check_iter_kfuncs() enforces that
1471 					 * iter state pointer is always the first arg
1472 					 */
1473 					iter_reg = &cur_frame->regs[BPF_REG_1];
1474 					/* current state is valid due to states_equal(),
1475 					 * so we can assume valid iter and reg state,
1476 					 * no need for extra (re-)validations
1477 					 */
1478 					spi = bpf_get_spi(iter_reg->var_off.value);
1479 					iter_frame = bpf_func(env, iter_reg);
1480 					iter_state = &bpf_stack_slot(iter_frame, spi)->spilled_ptr;
1481 					old_frame = sl->state.frame[iter_reg->frameno];
1482 					old_iter = &bpf_stack_slot(old_frame, spi)->spilled_ptr;
1483 					/*
1484 					 * states_equal() matches ids through idmap.
1485 					 * The loop converged only if it's the same
1486 					 * iterator. The one that was destroyed and
1487 					 * created again starts from the beginning.
1488 					 */
1489 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE &&
1490 					    iter_state->id == old_iter->id) {
1491 						loop = true;
1492 						goto hit;
1493 					}
1494 				}
1495 				goto skip_inf_loop_check;
1496 			}
1497 			if (is_may_goto_insn_at(env, insn_idx)) {
1498 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
1499 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
1500 					loop = true;
1501 					goto hit;
1502 				}
1503 			}
1504 			if (bpf_calls_callback(env, insn_idx)) {
1505 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
1506 					loop = true;
1507 					goto hit;
1508 				}
1509 				goto skip_inf_loop_check;
1510 			}
1511 			/*
1512 			 * If old state belongs to a control flow loop that we know terminates,
1513 			 * it should be safe to prune current state. However, account for the
1514 			 * following situation:
1515 			 *
1516 			 *   for (;;) {
1517 			 *     for (i = 0; i < 10; i++)
1518 			 *       ...
1519 			 *   }
1520 			 *
1521 			 * Here a backedge to a non-terminating outer loop is dominated by an exit
1522 			 * from the inner loop. Pruning at a re-entry to the inner loop therefore
1523 			 * would hide the fact that outer loop is non-terminating.
1524 			 * Hence, only allow pruning states within the same entry state.
1525 			 */
1526 			old_loop = current_loop(&sl->state);
1527 			cur_loop = current_loop(cur);
1528 			if (old_loop && cur_loop &&
1529 			    old_loop->terminates && cur_loop->terminates &&
1530 			    old_loop->entry_state == cur_loop->entry_state) {
1531 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
1532 					loop = true;
1533 					goto hit;
1534 				}
1535 				goto skip_inf_loop_check;
1536 			}
1537 
1538 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
1539 			if (states_maybe_looping(&sl->state, cur) &&
1540 			    states_equal(env, &sl->state, cur, EXACT) &&
1541 			    !iter_active_depths_differ(&sl->state, cur) &&
1542 			    sl->state.may_goto_depth == cur->may_goto_depth &&
1543 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
1544 				verbose_linfo(env, insn_idx, "; ");
1545 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
1546 				verbose(env, "cur state:");
1547 				print_verifier_state(env, cur, cur->curframe, true);
1548 				verbose(env, "old state:");
1549 				print_verifier_state(env, &sl->state, cur->curframe, true);
1550 				return -EINVAL;
1551 			}
1552 			/* if the verifier is processing a loop, avoid adding new state
1553 			 * too often, since different loop iterations have distinct
1554 			 * states and may not help future pruning.
1555 			 * This threshold shouldn't be too low to make sure that
1556 			 * a loop with large bound will be rejected quickly.
1557 			 * The most abusive loop will be:
1558 			 * r1 += 1
1559 			 * if r1 < 1000000 goto pc-2
1560 			 * 1M insn_procssed limit / 100 == 10k peak states.
1561 			 * This threshold shouldn't be too high either, since states
1562 			 * at the end of the loop are likely to be useful in pruning.
1563 			 */
1564 skip_inf_loop_check:
1565 			if (!force_new_state &&
1566 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
1567 			    env->insn_processed - env->prev_insn_processed < 100)
1568 				add_new_state = false;
1569 			goto miss;
1570 		}
1571 		/* See comments for mark_all_regs_read_and_precise() */
1572 		loop = incomplete_read_marks(env, &sl->state);
1573 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
1574 hit:
1575 			sl->hit_cnt++;
1576 
1577 			/* if previous state reached the exit with precision and
1578 			 * current state is equivalent to it (except precision marks)
1579 			 * the precision needs to be propagated back in
1580 			 * the current state.
1581 			 */
1582 			err = 0;
1583 			if (bpf_is_jmp_point(env, env->insn_idx))
1584 				err = bpf_push_jmp_history(env, cur, 0, 0, 0, NULL, 0);
1585 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
1586 			if (err)
1587 				return err;
1588 			/* When processing iterator based loops above propagate_liveness and
1589 			 * propagate_precision calls are not sufficient to transfer all relevant
1590 			 * read and precision marks. E.g. consider the following case:
1591 			 *
1592 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
1593 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
1594 			 *  |   v   v  At this point, state C is not processed yet, so state A
1595 			 *  '-- B   C  has not received any read or precision marks from C.
1596 			 *             Thus, marks propagated from A to B are incomplete.
1597 			 *
1598 			 * The verifier mitigates this by performing the following steps:
1599 			 *
1600 			 * - Prior to the main verification pass, strongly connected components
1601 			 *   (SCCs) are computed over the program's control flow graph,
1602 			 *   intraprocedurally.
1603 			 *
1604 			 * - During the main verification pass, `maybe_enter_scc()` checks
1605 			 *   whether the current verifier state is entering an SCC. If so, an
1606 			 *   instance of a `bpf_scc_visit` object is created, and the state
1607 			 *   entering the SCC is recorded as the entry state.
1608 			 *
1609 			 * - This instance is associated not with the SCC itself, but with a
1610 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
1611 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
1612 			 *
1613 			 * - When a verification path encounters a `states_equal(...,
1614 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
1615 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
1616 			 *   of the current state is created and added to
1617 			 *   `bpf_scc_visit->backedges`.
1618 			 *
1619 			 * - When a verification path terminates, `maybe_exit_scc()` is called
1620 			 *   from `bpf_update_branch_counts()`. For states with `branches == 0`, it
1621 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
1622 			 *   instance. If it is, this indicates that all paths originating from
1623 			 *   this SCC visit have been explored. `propagate_backedges()` is then
1624 			 *   called, which propagates read and precision marks through the
1625 			 *   backedges until a fixed point is reached.
1626 			 *   (In the earlier example, this would propagate marks from A to B,
1627 			 *    from C to A, and then again from A to B.)
1628 			 *
1629 			 * A note on callchains
1630 			 * --------------------
1631 			 *
1632 			 * Consider the following example:
1633 			 *
1634 			 *     void foo() { loop { ... SCC#1 ... } }
1635 			 *     void main() {
1636 			 *       A: foo();
1637 			 *       B: ...
1638 			 *       C: foo();
1639 			 *     }
1640 			 *
1641 			 * Here, there are two distinct callchains leading to SCC#1:
1642 			 * - (A, SCC#1)
1643 			 * - (C, SCC#1)
1644 			 *
1645 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
1646 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
1647 			 * functions traverse the parent state of each backedge state, which
1648 			 * means these parent states must remain valid (i.e., not freed) while
1649 			 * the corresponding `bpf_scc_visit` instance exists.
1650 			 *
1651 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
1652 			 * callchains would break this invariant:
1653 			 * - States explored during `C: foo()` would contribute backedges to
1654 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
1655 			 *   `A: foo()` completes.
1656 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
1657 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
1658 			 *   links for states from `C: foo()` to become invalid.
1659 			 */
1660 			if (loop) {
1661 				struct bpf_scc_backedge *backedge;
1662 
1663 				backedge = kzalloc_obj(*backedge,
1664 						       GFP_KERNEL_ACCOUNT);
1665 				if (!backedge)
1666 					return -ENOMEM;
1667 				err = bpf_copy_verifier_state(&backedge->state, cur);
1668 				backedge->state.equal_state = &sl->state;
1669 				backedge->state.insn_idx = insn_idx;
1670 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
1671 				if (err) {
1672 					bpf_free_verifier_state(&backedge->state, false);
1673 					kfree(backedge);
1674 					return err;
1675 				}
1676 			}
1677 			return 1;
1678 		}
1679 miss:
1680 		/* when new state is not going to be added do not increase miss count.
1681 		 * Otherwise several loop iterations will remove the state
1682 		 * recorded earlier. The goal of these heuristics is to have
1683 		 * states from some iterations of the loop (some in the beginning
1684 		 * and some at the end) to help pruning.
1685 		 */
1686 		if (add_new_state)
1687 			sl->miss_cnt++;
1688 		/* heuristic to determine whether this state is beneficial
1689 		 * to keep checking from state equivalence point of view.
1690 		 * Higher numbers increase max_states_per_insn and verification time,
1691 		 * but do not meaningfully decrease insn_processed.
1692 		 * 'n' controls how many times state could miss before eviction.
1693 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
1694 		 * too early would hinder iterator convergence.
1695 		 */
1696 		n = (bpf_is_force_checkpoint(env, insn_idx) || loop_checkpoint) &&
1697 		    sl->state.branches > 0 ? 64 : 3;
1698 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
1699 			/* the state is unlikely to be useful. Remove it to
1700 			 * speed up verification
1701 			 */
1702 			sl->in_free_list = true;
1703 			list_del(&sl->node);
1704 			list_add(&sl->node, &env->free_list);
1705 			env->free_list_size++;
1706 			env->explored_states_size--;
1707 			maybe_free_verifier_state(env, sl);
1708 		}
1709 	}
1710 
1711 	if (env->max_states_per_insn < states_cnt)
1712 		env->max_states_per_insn = states_cnt;
1713 
1714 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
1715 		return 0;
1716 
1717 	if (!add_new_state)
1718 		return 0;
1719 
1720 	/* There were no equivalent states, remember the current one.
1721 	 * Technically the current state is not proven to be safe yet,
1722 	 * but it will either reach outer most bpf_exit (which means it's safe)
1723 	 * or it will be rejected. When there are no loops the verifier won't be
1724 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
1725 	 * again on the way to bpf_exit.
1726 	 * When looping the sl->state.branches will be > 0 and this state
1727 	 * will not be considered for equivalence until branches == 0.
1728 	 */
1729 	return bpf_split_cur_state(env);
1730 }
1731