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