xref: /linux/kernel/bpf/backtrack.c (revision 60b0109ad195c8b131224cfe66cbd6277c8d47b4)
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/filter.h>
6 #include <linux/bitmap.h>
7 
8 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
9 
10 /* for any branch, call, exit record the history of jmps in the given state */
11 int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
12 			 int insn_flags, int spi, int frame, const u16 *linked_regs,
13 			 u8 linked_regs_cnt)
14 {
15 	u32 cnt = cur->jmp_history_cnt;
16 	struct bpf_jmp_history_entry *p;
17 	size_t alloc_size;
18 
19 	/* combine instruction flags if we already recorded this instruction */
20 	if (env->cur_hist_ent) {
21 		/* atomic instructions push insn_flags twice, for READ and
22 		 * WRITE sides, but they should agree on stack slot
23 		 */
24 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
25 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
26 				env, "insn history: insn_idx %d cur flags %x new flags %x",
27 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
28 		env->cur_hist_ent->flags |= insn_flags;
29 		env->cur_hist_ent->spi = spi;
30 		env->cur_hist_ent->frame = frame;
31 		verifier_bug_if(env->cur_hist_ent->linked_regs_cnt != 0, env,
32 				"insn history: insn_idx %d has %u linked regs",
33 				env->insn_idx, env->cur_hist_ent->linked_regs_cnt);
34 		if (linked_regs_cnt)
35 			memcpy(env->cur_hist_ent->linked_regs, linked_regs,
36 			       linked_regs_cnt * sizeof(*linked_regs));
37 		env->cur_hist_ent->linked_regs_cnt = linked_regs_cnt;
38 		return 0;
39 	}
40 
41 	cnt++;
42 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
43 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
44 	if (!p)
45 		return -ENOMEM;
46 	cur->jmp_history = p;
47 
48 	p = &cur->jmp_history[cnt - 1];
49 	p->idx = env->insn_idx;
50 	p->prev_idx = env->prev_insn_idx;
51 	p->flags = insn_flags;
52 	p->spi = spi;
53 	p->frame = frame;
54 	if (linked_regs_cnt)
55 		memcpy(p->linked_regs, linked_regs, linked_regs_cnt * sizeof(*linked_regs));
56 	p->linked_regs_cnt = linked_regs_cnt;
57 	cur->jmp_history_cnt = cnt;
58 	env->cur_hist_ent = p;
59 
60 	return 0;
61 }
62 
63 static bool is_atomic_load_insn(const struct bpf_insn *insn)
64 {
65 	return BPF_CLASS(insn->code) == BPF_STX &&
66 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
67 	       insn->imm == BPF_LOAD_ACQ;
68 }
69 
70 static bool is_atomic_fetch_insn(const struct bpf_insn *insn)
71 {
72 	return BPF_CLASS(insn->code) == BPF_STX &&
73 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
74 	       (insn->imm & BPF_FETCH);
75 }
76 
77 /* Backtrack one insn at a time. If idx is not at the top of recorded
78  * history then previous instruction came from straight line execution.
79  * Return -ENOENT if we exhausted all instructions within given state.
80  *
81  * It's legal to have a bit of a looping with the same starting and ending
82  * insn index within the same state, e.g.: 3->4->5->3, so just because current
83  * instruction index is the same as state's first_idx doesn't mean we are
84  * done. If there is still some jump history left, we should keep going. We
85  * need to take into account that we might have a jump history between given
86  * state's parent and itself, due to checkpointing. In this case, we'll have
87  * history entry recording a jump from last instruction of parent state and
88  * first instruction of given state.
89  */
90 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
91 			     u32 *history)
92 {
93 	u32 cnt = *history;
94 
95 	if (i == st->first_insn_idx) {
96 		if (cnt == 0)
97 			return -ENOENT;
98 		if (cnt == 1 && st->jmp_history[0].idx == i)
99 			return -ENOENT;
100 	}
101 
102 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
103 		i = st->jmp_history[cnt - 1].prev_idx;
104 		(*history)--;
105 	} else {
106 		i--;
107 	}
108 	return i;
109 }
110 
111 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
112 						        u32 hist_end, int insn_idx)
113 {
114 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
115 		return &st->jmp_history[hist_end - 1];
116 	return NULL;
117 }
118 
119 static inline void bt_init(struct backtrack_state *bt, u32 frame)
120 {
121 	bt->frame = frame;
122 }
123 
124 static inline void bt_reset(struct backtrack_state *bt)
125 {
126 	struct bpf_verifier_env *env = bt->env;
127 
128 	memset(bt, 0, sizeof(*bt));
129 	bt->env = env;
130 }
131 
132 static inline bool bt_frame_stack_empty(struct backtrack_state *bt, u32 frame)
133 {
134 	return bitmap_empty(bt->stack_masks[frame], MAX_BPF_STACK_SLOTS);
135 }
136 
137 static inline bool bt_stack_empty(struct backtrack_state *bt)
138 {
139 	return bt_frame_stack_empty(bt, bt->frame);
140 }
141 
142 static inline bool bt_empty(struct backtrack_state *bt)
143 {
144 	u32 mask = 0;
145 	int i;
146 
147 	for (i = 0; i <= bt->frame; i++) {
148 		mask |= bt->reg_masks[i] | bt->stack_arg_masks[i];
149 		if (!bt_frame_stack_empty(bt, i))
150 			return false;
151 	}
152 
153 	return mask == 0;
154 }
155 
156 static inline void bt_clear_frame_stack_arg_slot(struct backtrack_state *bt, u32 frame, u32 slot)
157 {
158 	bt->stack_arg_masks[frame] &= ~(1 << slot);
159 }
160 
161 static inline bool bt_is_frame_stack_arg_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
162 {
163 	return bt->stack_arg_masks[frame] & (1 << slot);
164 }
165 
166 static inline int bt_subprog_enter(struct backtrack_state *bt)
167 {
168 	if (bt->frame == MAX_CALL_FRAMES - 1) {
169 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
170 		return -EFAULT;
171 	}
172 	bt->frame++;
173 	return 0;
174 }
175 
176 static inline int bt_subprog_exit(struct backtrack_state *bt)
177 {
178 	if (bt->frame == 0) {
179 		verifier_bug(bt->env, "subprog exit from frame 0");
180 		return -EFAULT;
181 	}
182 	bt->frame--;
183 	return 0;
184 }
185 
186 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
187 {
188 	bt->reg_masks[frame] &= ~(1 << reg);
189 }
190 
191 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
192 {
193 	bpf_bt_set_frame_reg(bt, bt->frame, reg);
194 }
195 
196 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
197 {
198 	bt_clear_frame_reg(bt, bt->frame, reg);
199 }
200 
201 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
202 {
203 	__clear_bit(slot, bt->stack_masks[frame]);
204 }
205 
206 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
207 {
208 	return bt->reg_masks[frame];
209 }
210 
211 static inline u32 bt_reg_mask(struct backtrack_state *bt)
212 {
213 	return bt->reg_masks[bt->frame];
214 }
215 
216 static inline unsigned long *bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
217 {
218 	return bt->stack_masks[frame];
219 }
220 
221 static inline unsigned long *bt_stack_mask(struct backtrack_state *bt)
222 {
223 	return bt_frame_stack_mask(bt, bt->frame);
224 }
225 
226 static inline u8 bt_stack_arg_mask(struct backtrack_state *bt)
227 {
228 	return bt->stack_arg_masks[bt->frame];
229 }
230 
231 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
232 {
233 	return bt->reg_masks[bt->frame] & (1 << reg);
234 }
235 
236 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
237 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
238 {
239 	DECLARE_BITMAP(mask, 64);
240 	bool first = true;
241 	int i, n;
242 
243 	buf[0] = '\0';
244 
245 	bitmap_from_u64(mask, reg_mask);
246 	for_each_set_bit(i, mask, 32) {
247 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
248 		first = false;
249 		buf += n;
250 		buf_sz -= n;
251 		if (buf_sz < 0)
252 			break;
253 	}
254 }
255 
256 /* format stack slots bitmask, e.g., "-8,-24,-40" for slots 0, 2 and 4 */
257 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, const unsigned long *stack_mask)
258 {
259 	bool first = true;
260 	int i, n;
261 
262 	buf[0] = '\0';
263 
264 	for_each_set_bit(i, stack_mask, MAX_BPF_STACK_SLOTS) {
265 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
266 		first = false;
267 		buf += n;
268 		buf_sz -= n;
269 		if (buf_sz < 0)
270 			break;
271 	}
272 }
273 
274 /* For given verifier state backtrack_insn() is called from the last insn to
275  * the first insn. Its purpose is to compute a bitmask of registers and
276  * stack slots that needs precision in the parent verifier state.
277  *
278  * @idx is an index of the instruction we are currently processing;
279  * @subseq_idx is an index of the subsequent instruction that:
280  *   - *would be* executed next, if jump history is viewed in forward order;
281  *   - *was* processed previously during backtracking.
282  */
283 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
284 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
285 {
286 	struct bpf_insn *insn = env->prog->insnsi + idx;
287 	u8 class = BPF_CLASS(insn->code);
288 	u8 opcode = BPF_OP(insn->code);
289 	u8 mode = BPF_MODE(insn->code);
290 	u32 dreg = insn->dst_reg;
291 	u32 sreg = insn->src_reg;
292 	u32 spi, i, fr;
293 
294 	if (insn->code == 0)
295 		return 0;
296 	if (env->log.level & BPF_LOG_LEVEL2) {
297 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
298 		verbose(env, "mark_precise: frame%d: regs=%s ",
299 			bt->frame, env->tmp_str_buf);
300 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
301 		verbose(env, "stack=%s before ", env->tmp_str_buf);
302 		verbose(env, "%d: ", idx);
303 		bpf_verbose_insn(env, insn);
304 		verbose(env, "\n");
305 	}
306 
307 	/* If there is a history record that some registers gained range at this insn,
308 	 * propagate precision marks to those registers, so that bt_is_reg_set()
309 	 * accounts for these registers.
310 	 */
311 	bpf_bt_sync_linked_regs(bt, hist);
312 
313 	if (class == BPF_ALU || class == BPF_ALU64) {
314 		if (!bt_is_reg_set(bt, dreg))
315 			return 0;
316 		if (opcode == BPF_END || opcode == BPF_NEG) {
317 			/* sreg is reserved and unused
318 			 * dreg still need precision before this insn
319 			 */
320 			return 0;
321 		} else if (opcode == BPF_MOV) {
322 			if (BPF_SRC(insn->code) == BPF_X) {
323 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
324 				 * dreg needs precision after this insn
325 				 * sreg needs precision before this insn
326 				 */
327 				bt_clear_reg(bt, dreg);
328 				if (sreg != BPF_REG_FP)
329 					bt_set_reg(bt, sreg);
330 			} else {
331 				/* dreg = K
332 				 * dreg needs precision after this insn.
333 				 * Corresponding register is already marked
334 				 * as precise=true in this verifier state.
335 				 * No further markings in parent are necessary
336 				 */
337 				bt_clear_reg(bt, dreg);
338 			}
339 		} else {
340 			if (BPF_SRC(insn->code) == BPF_X) {
341 				/* dreg += sreg
342 				 * both dreg and sreg need precision
343 				 * before this insn
344 				 */
345 				if (sreg != BPF_REG_FP)
346 					bt_set_reg(bt, sreg);
347 			} /* else dreg += K
348 			   * dreg still needs precision before this insn
349 			   */
350 		}
351 	} else if (class == BPF_LDX ||
352 		   is_atomic_load_insn(insn) ||
353 		   is_atomic_fetch_insn(insn)) {
354 		u32 load_reg = dreg;
355 
356 		/*
357 		 * Atomic fetch operation writes the old value into
358 		 * a register (sreg or r0) and if it was tracked for
359 		 * precision, propagate to the stack slot like we do
360 		 * in regular ldx.
361 		 */
362 		if (is_atomic_fetch_insn(insn))
363 			load_reg = insn->imm == BPF_CMPXCHG ?
364 				   BPF_REG_0 : sreg;
365 
366 		if (!bt_is_reg_set(bt, load_reg))
367 			return 0;
368 		bt_clear_reg(bt, load_reg);
369 
370 		if (hist && hist->flags & INSN_F_STACK_ARG_ACCESS) {
371 			spi = hist->spi;
372 			/*
373 			 * Stack arg read: callee reads from r11+off, but
374 			 * the data lives in the caller's stack_arg_regs.
375 			 * Set the mask in the caller frame so precision
376 			 * is marked in the caller's slot at the callee
377 			 * entry checkpoint.
378 			 */
379 			bt_set_frame_stack_arg_slot(bt, bt->frame - 1, spi);
380 			return 0;
381 		}
382 
383 		/* scalars can only be spilled into stack w/o losing precision.
384 		 * Load from any other memory can be zero extended.
385 		 * The desire to keep that precision is already indicated
386 		 * by 'precise' mark in corresponding register of this state.
387 		 * No further tracking necessary.
388 		 */
389 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
390 			return 0;
391 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
392 		 * that [fp - off] slot contains scalar that needs to be
393 		 * tracked with precision
394 		 */
395 		spi = hist->spi;
396 		fr = hist->frame;
397 		bpf_bt_set_frame_slot(bt, fr, spi);
398 	} else if (class == BPF_STX || class == BPF_ST) {
399 		if (bt_is_reg_set(bt, dreg))
400 			/* stx & st shouldn't be using _scalar_ dst_reg
401 			 * to access memory. It means backtracking
402 			 * encountered a case of pointer subtraction.
403 			 */
404 			return -ENOTSUPP;
405 
406 		if (hist && hist->flags & INSN_F_STACK_ARG_ACCESS) {
407 			spi = hist->spi;
408 			if (!bt_is_frame_stack_arg_slot_set(bt, bt->frame, spi))
409 				return 0;
410 			bt_clear_frame_stack_arg_slot(bt, bt->frame, spi);
411 			if (class == BPF_STX)
412 				bt_set_reg(bt, sreg);
413 			return 0;
414 		}
415 
416 		/* scalars can only be spilled into stack */
417 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
418 			return 0;
419 		spi = hist->spi;
420 		fr = hist->frame;
421 		if (!bt_is_frame_slot_set(bt, fr, spi))
422 			return 0;
423 		bt_clear_frame_slot(bt, fr, spi);
424 		if (class == BPF_STX)
425 			bt_set_reg(bt, sreg);
426 	} else if (class == BPF_JMP || class == BPF_JMP32) {
427 		if (bpf_pseudo_call(insn) || bpf_is_callx(insn)) {
428 			int subprog_insn_idx, subprog = -1;
429 
430 			if (bpf_pseudo_call(insn)) {
431 				subprog_insn_idx = idx + insn->imm + 1;
432 				subprog = bpf_find_subprog(env, subprog_insn_idx);
433 				if (subprog < 0)
434 					return -EFAULT;
435 			}
436 
437 			/* callx calls static subprogs only */
438 			if (subprog >= 0 && bpf_subprog_is_global(env, subprog)) {
439 				/* check that jump history doesn't have any
440 				 * extra instructions from subprog; the next
441 				 * instruction after call to global subprog
442 				 * should be literally next instruction in
443 				 * caller program
444 				 */
445 				verifier_bug_if(idx + 1 != subseq_idx, env,
446 						"extra insn from subprog");
447 				/* global subprog always sets R0 */
448 				bt_clear_reg(bt, BPF_REG_0);
449 				/* and if it does not set R2, main pass would catch it */
450 				bt_clear_reg(bt, BPF_REG_2);
451 				/* r1-r5 are invalidated after subprog call,
452 				 * so for global func call it shouldn't be set
453 				 * anymore
454 				 */
455 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
456 					verifier_bug(env, "global subprog unexpected regs %x",
457 						     bt_reg_mask(bt));
458 					return -EFAULT;
459 				}
460 				return 0;
461 			} else {
462 				/* static subprog call instruction, which
463 				 * means that we are exiting current subprog,
464 				 * so only r1-r5 could be still requested as
465 				 * precise, r0 and r6-r10 or any stack slot in
466 				 * the current frame should be zero by now
467 				 */
468 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
469 					verifier_bug(env, "static subprog unexpected regs %x",
470 						     bt_reg_mask(bt));
471 					return -EFAULT;
472 				}
473 				/* we are now tracking register spills correctly,
474 				 * so any instance of leftover slots is a bug
475 				 */
476 				if (!bt_stack_empty(bt)) {
477 					bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
478 							   bt_stack_mask(bt));
479 					verifier_bug(env, "static subprog leftover stack slots %s",
480 						     env->tmp_str_buf);
481 					return -EFAULT;
482 				}
483 				/* propagate r1-r5 to the caller */
484 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
485 					if (bt_is_reg_set(bt, i)) {
486 						bt_clear_reg(bt, i);
487 						bpf_bt_set_frame_reg(bt, bt->frame - 1, i);
488 					}
489 				}
490 				if (bt_stack_arg_mask(bt)) {
491 					verifier_bug(env,
492 						     "static subprog leftover stack arg slots %x",
493 						     bt_stack_arg_mask(bt));
494 					return -EFAULT;
495 				}
496 				if (bt_subprog_exit(bt))
497 					return -EFAULT;
498 				return 0;
499 			}
500 		} else if (bpf_is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
501 			/* exit from callback subprog to callback-calling helper or
502 			 * kfunc call. Use idx/subseq_idx check to discern it from
503 			 * straight line code backtracking.
504 			 * Unlike the subprog call handling above, we shouldn't
505 			 * propagate precision of r1-r5 (if any requested), as they are
506 			 * not actually arguments passed directly to callback subprogs
507 			 */
508 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
509 				verifier_bug(env, "callback unexpected regs %x",
510 					     bt_reg_mask(bt));
511 				return -EFAULT;
512 			}
513 			if (!bt_stack_empty(bt)) {
514 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
515 						   bt_stack_mask(bt));
516 				verifier_bug(env, "callback leftover stack slots %s",
517 					     env->tmp_str_buf);
518 				return -EFAULT;
519 			}
520 			/* clear r1-r5 in callback subprog's mask */
521 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
522 				bt_clear_reg(bt, i);
523 			if (bt_subprog_exit(bt))
524 				return -EFAULT;
525 			return 0;
526 		} else if (opcode == BPF_CALL) {
527 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
528 			 * catch this error later. Make backtracking conservative
529 			 * with ENOTSUPP.
530 			 */
531 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
532 				return -ENOTSUPP;
533 			/* regular helper call sets R0 */
534 			bt_clear_reg(bt, BPF_REG_0);
535 			/* kfunc might also set R2 */
536 			bt_clear_reg(bt, BPF_REG_2);
537 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
538 				/* if backtracking was looking for registers R1-R5
539 				 * they should have been found already.
540 				 */
541 				verifier_bug(env, "backtracking call unexpected regs %x",
542 					     bt_reg_mask(bt));
543 				return -EFAULT;
544 			}
545 			if (insn->src_reg == BPF_REG_0 && insn->imm == BPF_FUNC_tail_call
546 			    && subseq_idx - idx != 1) {
547 				if (bt_subprog_enter(bt))
548 					return -EFAULT;
549 			}
550 		} else if (opcode == BPF_EXIT) {
551 			bool from_subprog_call, r0_precise, r2_precise;
552 
553 			/* BPF_EXIT in subprog or callback always returns
554 			 * right after the call instruction, so by checking
555 			 * whether the instruction at subseq_idx-1 is subprog
556 			 * call or not we can distinguish actual exit from
557 			 * *subprog* from exit from *callback*. In the former
558 			 * case, we need to propagate the precision of the
559 			 * return registers, if necessary. In the latter we
560 			 * never do that.
561 			 */
562 			from_subprog_call = subseq_idx - 1 >= 0 &&
563 					    (bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) ||
564 					     bpf_is_callx(&env->prog->insnsi[subseq_idx - 1]));
565 
566 			r0_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_0);
567 			r2_precise = from_subprog_call && bt_is_reg_set(bt, BPF_REG_2);
568 
569 			/* Backtracking to a nested function call, 'idx' is a part of
570 			 * the inner frame 'subseq_idx' is a part of the outer frame.
571 			 * In case of a regular function call, the callee defines the
572 			 * return registers R0 and R2, so clear them before checking
573 			 * that instructions giving precision to registers R1-R5 have
574 			 * been found already. R2 is also an argument register, hence
575 			 * it has to be cleared before that check.
576 			 * In case of a callback from bpf_loop(), R{1,4} in the calling
577 			 * frame would be set as precise and that is correct, and R2
578 			 * might be a precise helper argument as well, so leave it set.
579 			 */
580 			bt_clear_reg(bt, BPF_REG_0);
581 			if (from_subprog_call)
582 				bt_clear_reg(bt, BPF_REG_2);
583 			if (from_subprog_call && (bt_reg_mask(bt) & BPF_REGMASK_ARGS)) {
584 				verifier_bug(env, "backtracking exit unexpected regs %x",
585 					     bt_reg_mask(bt));
586 				return -EFAULT;
587 			}
588 
589 			if (bt_subprog_enter(bt))
590 				return -EFAULT;
591 
592 			if (r0_precise)
593 				bt_set_reg(bt, BPF_REG_0);
594 			if (r2_precise)
595 				bt_set_reg(bt, BPF_REG_2);
596 			/* r6-r9 and stack slots will stay set in caller frame
597 			 * bitmasks until we return back from callee(s)
598 			 */
599 			return 0;
600 		} else if (BPF_SRC(insn->code) == BPF_X) {
601 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
602 				return 0;
603 			/* dreg <cond> sreg
604 			 * Both dreg and sreg need precision before
605 			 * this insn. If only sreg was marked precise
606 			 * before it would be equally necessary to
607 			 * propagate it to dreg.
608 			 */
609 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
610 				bt_set_reg(bt, sreg);
611 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
612 				bt_set_reg(bt, dreg);
613 		} else if (BPF_SRC(insn->code) == BPF_K) {
614 			 /* dreg <cond> K
615 			  * Only dreg still needs precision before
616 			  * this insn, so for the K-based conditional
617 			  * there is nothing new to be marked.
618 			  */
619 		}
620 	} else if (class == BPF_LD) {
621 		/* It's ld_imm64 or ld_abs or ld_ind.
622 		 * For ld_imm64 no further tracking of precision
623 		 * into parent is necessary
624 		 */
625 		if (mode == BPF_IMM) {
626 			bt_clear_reg(bt, dreg);
627 			return 0;
628 		}
629 		/*
630 		 * BPF_{IND,ABS} are modelled as two branches:
631 		 * - fallthrough;
632 		 * - implicit subprogram exit.
633 		 * It is necessary to switch current frame if
634 		 * implicit subprogram exit branch is backtracked.
635 		 */
636 		if (mode == BPF_IND || mode == BPF_ABS) {
637 			if (bt_is_reg_set(bt, dreg))
638 				return -ENOTSUPP;
639 			if (subseq_idx != idx + 1)
640 				if (bt_subprog_enter(bt))
641 					return -EFAULT;
642 			return 0;
643 		}
644 	}
645 	/* Propagate precision marks to linked registers, to account for
646 	 * registers marked as precise in this function.
647 	 */
648 	bpf_bt_sync_linked_regs(bt, hist);
649 	return 0;
650 }
651 
652 /* the scalar precision tracking algorithm:
653  * . at the start all registers have precise=false.
654  * . scalar ranges are tracked as normal through alu and jmp insns.
655  * . once precise value of the scalar register is used in:
656  *   .  ptr + scalar alu
657  *   . if (scalar cond K|scalar)
658  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
659  *   backtrack through the verifier states and mark all registers and
660  *   stack slots with spilled constants that these scalar registers
661  *   should be precise.
662  * . during state pruning two registers (or spilled stack slots)
663  *   are equivalent if both are not precise.
664  *
665  * Note the verifier cannot simply walk register parentage chain,
666  * since many different registers and stack slots could have been
667  * used to compute single precise scalar.
668  *
669  * The approach of starting with precise=true for all registers and then
670  * backtrack to mark a register as not precise when the verifier detects
671  * that program doesn't care about specific value (e.g., when helper
672  * takes register as ARG_ANYTHING parameter) is not safe.
673  *
674  * It's ok to walk single parentage chain of the verifier states.
675  * It's possible that this backtracking will go all the way till 1st insn.
676  * All other branches will be explored for needing precision later.
677  *
678  * The backtracking needs to deal with cases like:
679  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
680  * r9 -= r8
681  * r5 = r9
682  * if r5 > 0x79f goto pc+7
683  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
684  * r5 += 1
685  * ...
686  * call bpf_perf_event_output#25
687  *   where .arg5_type = ARG_MEM_SIZE_OR_ZERO
688  *
689  * and this case:
690  * r6 = 1
691  * call foo // uses callee's r6 inside to compute r0
692  * r0 += r6
693  * if r0 == 0 goto
694  *
695  * to track above reg_mask/stack_mask needs to be independent for each frame.
696  *
697  * Also if parent's curframe > frame where backtracking started,
698  * the verifier need to mark registers in both frames, otherwise callees
699  * may incorrectly prune callers. This is similar to
700  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
701  *
702  * For now backtracking falls back into conservative marking.
703  */
704 void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env,
705 				 struct bpf_verifier_state *st)
706 {
707 	struct bpf_func_state *func;
708 	struct bpf_reg_state *reg;
709 	int i, j;
710 
711 	if (env->log.level & BPF_LOG_LEVEL2) {
712 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
713 			st->curframe);
714 	}
715 
716 	/* big hammer: mark all scalars precise in this path.
717 	 * pop_stack may still get !precise scalars.
718 	 * We also skip current state and go straight to first parent state,
719 	 * because precision markings in current non-checkpointed state are
720 	 * not needed. See why in the comment in __mark_chain_precision below.
721 	 */
722 	for (st = st->parent; st; st = st->parent) {
723 		for (i = 0; i <= st->curframe; i++) {
724 			func = st->frame[i];
725 			for (j = 0; j < BPF_REG_FP; j++) {
726 				reg = &func->regs[j];
727 				if (reg->type != SCALAR_VALUE || reg->precise)
728 					continue;
729 				reg->precise = true;
730 				if (env->log.level & BPF_LOG_LEVEL2) {
731 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
732 						i, j);
733 				}
734 			}
735 			for (j = 0; j < bpf_stack_nr_slots(func); j++) {
736 				struct bpf_stack_state *ss = bpf_stack_slot(func, j);
737 
738 				if (!bpf_is_spilled_reg(ss))
739 					continue;
740 				reg = &ss->spilled_ptr;
741 				if (reg->type != SCALAR_VALUE || reg->precise)
742 					continue;
743 				reg->precise = true;
744 				if (env->log.level & BPF_LOG_LEVEL2) {
745 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
746 						i, -(j + 1) * 8);
747 				}
748 			}
749 		}
750 	}
751 }
752 
753 /*
754  * bpf_mark_chain_precision() backtracks BPF program instruction sequence and
755  * chain of verifier states making sure that register *regno* (if regno >= 0)
756  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
757  * SCALARS, as well as any other registers and slots that contribute to
758  * a tracked state of given registers/stack slots, depending on specific BPF
759  * assembly instructions (see backtrack_insns() for exact instruction handling
760  * logic). This backtracking relies on recorded jmp_history and is able to
761  * traverse entire chain of parent states. This process ends only when all the
762  * necessary registers/slots and their transitive dependencies are marked as
763  * precise.
764  *
765  * One important and subtle aspect is that precise marks *do not matter* in
766  * the currently verified state (current state). It is important to understand
767  * why this is the case.
768  *
769  * First, note that current state is the state that is not yet "checkpointed",
770  * i.e., it is not yet put into env->explored_states, and it has no children
771  * states as well. It's ephemeral, and can end up either a) being discarded if
772  * compatible explored state is found at some point or BPF_EXIT instruction is
773  * reached or b) checkpointed and put into env->explored_states, branching out
774  * into one or more children states.
775  *
776  * In the former case, precise markings in current state are completely
777  * ignored by state comparison code (see regsafe() for details). Only
778  * checkpointed ("old") state precise markings are important, and if old
779  * state's register/slot is precise, regsafe() assumes current state's
780  * register/slot as precise and checks value ranges exactly and precisely. If
781  * states turn out to be compatible, current state's necessary precise
782  * markings and any required parent states' precise markings are enforced
783  * after the fact with propagate_precision() logic, after the fact. But it's
784  * important to realize that in this case, even after marking current state
785  * registers/slots as precise, we immediately discard current state. So what
786  * actually matters is any of the precise markings propagated into current
787  * state's parent states, which are always checkpointed (due to b) case above).
788  * As such, for scenario a) it doesn't matter if current state has precise
789  * markings set or not.
790  *
791  * Now, for the scenario b), checkpointing and forking into child(ren)
792  * state(s). Note that before current state gets to checkpointing step, any
793  * processed instruction always assumes precise SCALAR register/slot
794  * knowledge: if precise value or range is useful to prune jump branch, BPF
795  * verifier takes this opportunity enthusiastically. Similarly, when
796  * register's value is used to calculate offset or memory address, exact
797  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
798  * what we mentioned above about state comparison ignoring precise markings
799  * during state comparison, BPF verifier ignores and also assumes precise
800  * markings *at will* during instruction verification process. But as verifier
801  * assumes precision, it also propagates any precision dependencies across
802  * parent states, which are not yet finalized, so can be further restricted
803  * based on new knowledge gained from restrictions enforced by their children
804  * states. This is so that once those parent states are finalized, i.e., when
805  * they have no more active children state, state comparison logic in
806  * is_state_visited() would enforce strict and precise SCALAR ranges, if
807  * required for correctness.
808  *
809  * To build a bit more intuition, note also that once a state is checkpointed,
810  * the path we took to get to that state is not important. This is crucial
811  * property for state pruning. When state is checkpointed and finalized at
812  * some instruction index, it can be correctly and safely used to "short
813  * circuit" any *compatible* state that reaches exactly the same instruction
814  * index. I.e., if we jumped to that instruction from a completely different
815  * code path than original finalized state was derived from, it doesn't
816  * matter, current state can be discarded because from that instruction
817  * forward having a compatible state will ensure we will safely reach the
818  * exit. States describe preconditions for further exploration, but completely
819  * forget the history of how we got here.
820  *
821  * This also means that even if we needed precise SCALAR range to get to
822  * finalized state, but from that point forward *that same* SCALAR register is
823  * never used in a precise context (i.e., it's precise value is not needed for
824  * correctness), it's correct and safe to mark such register as "imprecise"
825  * (i.e., precise marking set to false). This is what we rely on when we do
826  * not set precise marking in current state. If no child state requires
827  * precision for any given SCALAR register, it's safe to dictate that it can
828  * be imprecise. If any child state does require this register to be precise,
829  * we'll mark it precise later retroactively during precise markings
830  * propagation from child state to parent states.
831  *
832  * Skipping precise marking setting in current state is a mild version of
833  * relying on the above observation. But we can utilize this property even
834  * more aggressively by proactively forgetting any precise marking in the
835  * current state (which we inherited from the parent state), right before we
836  * checkpoint it and branch off into new child state. This is done by
837  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
838  * finalized states which help in short circuiting more future states.
839  */
840 int bpf_mark_chain_precision(struct bpf_verifier_env *env,
841 			    struct bpf_verifier_state *starting_state,
842 			    int regno,
843 			    bool *changed)
844 {
845 	struct bpf_verifier_state *st = starting_state;
846 	struct backtrack_state *bt = &env->bt;
847 	int first_idx = st->first_insn_idx;
848 	int last_idx = starting_state->insn_idx;
849 	int subseq_idx = -1;
850 	struct bpf_func_state *func;
851 	bool tmp, skip_first = true;
852 	struct bpf_stack_state *ss;
853 	struct bpf_reg_state *reg;
854 	int i, fr, err;
855 
856 	if (!env->bpf_capable)
857 		return 0;
858 
859 	changed = changed ?: &tmp;
860 	/* set frame number from which we are starting to backtrack */
861 	bt_init(bt, starting_state->curframe);
862 
863 	/* Do sanity checks against current state of register and/or stack
864 	 * slot, but don't set precise flag in current state, as precision
865 	 * tracking in the current state is unnecessary.
866 	 */
867 	func = st->frame[bt->frame];
868 	if (regno >= 0) {
869 		reg = &func->regs[regno];
870 		if (reg->type != SCALAR_VALUE) {
871 			verifier_bug(env, "backtracking misuse");
872 			return -EFAULT;
873 		}
874 		bt_set_reg(bt, regno);
875 	}
876 
877 	if (bt_empty(bt))
878 		return 0;
879 
880 	for (;;) {
881 		DECLARE_BITMAP(mask, 64);
882 		u32 history = st->jmp_history_cnt;
883 		struct bpf_jmp_history_entry *hist;
884 
885 		if (env->log.level & BPF_LOG_LEVEL2) {
886 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
887 				bt->frame, last_idx, first_idx, subseq_idx);
888 		}
889 
890 		if (last_idx < 0) {
891 			/* Consecutive checkpoints can have no instructions between them. */
892 			if (st->parent)
893 				goto parent;
894 
895 			/* we are at the entry into subprog, which
896 			 * is expected for global funcs, but only if
897 			 * requested precise registers are R1-R5
898 			 * (which are global func's input arguments)
899 			 */
900 			if (st->curframe == 0 &&
901 			    st->frame[0]->subprogno > 0 &&
902 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
903 			    bt_stack_empty(bt) &&
904 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
905 				bitmap_from_u64(mask, bt_reg_mask(bt));
906 				for_each_set_bit(i, mask, 32) {
907 					reg = &st->frame[0]->regs[i];
908 					bt_clear_reg(bt, i);
909 					if (reg->type == SCALAR_VALUE) {
910 						reg->precise = true;
911 						*changed = true;
912 					}
913 				}
914 				return 0;
915 			}
916 
917 			bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
918 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %s",
919 				     st->frame[0]->subprogno, bt_reg_mask(bt), env->tmp_str_buf);
920 			return -EFAULT;
921 		}
922 
923 		for (i = last_idx;;) {
924 			if (skip_first) {
925 				err = 0;
926 				skip_first = false;
927 			} else {
928 				hist = get_jmp_hist_entry(st, history, i);
929 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
930 			}
931 			if (err == -ENOTSUPP) {
932 				bpf_mark_all_scalars_precise(env, starting_state);
933 				bt_reset(bt);
934 				return 0;
935 			} else if (err) {
936 				return err;
937 			}
938 			if (bt_empty(bt))
939 				/* Found assignment(s) into tracked register in this state.
940 				 * Since this state is already marked, just return.
941 				 * Nothing to be tracked further in the parent state.
942 				 */
943 				return 0;
944 			subseq_idx = i;
945 			i = get_prev_insn_idx(st, i, &history);
946 			if (i == -ENOENT)
947 				break;
948 			if (i >= env->prog->len) {
949 				/* This can happen if backtracking reached insn 0
950 				 * and there are still reg_mask or stack_mask
951 				 * to backtrack.
952 				 * It means the backtracking missed the spot where
953 				 * particular register was initialized with a constant.
954 				 */
955 				verifier_bug(env, "backtracking idx %d", i);
956 				return -EFAULT;
957 			}
958 		}
959 parent:
960 		st = st->parent;
961 		if (!st)
962 			break;
963 
964 		for (fr = bt->frame; fr >= 0; fr--) {
965 			func = st->frame[fr];
966 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
967 			for_each_set_bit(i, mask, 32) {
968 				reg = &func->regs[i];
969 				if (reg->type != SCALAR_VALUE) {
970 					bt_clear_frame_reg(bt, fr, i);
971 					continue;
972 				}
973 				if (reg->precise) {
974 					bt_clear_frame_reg(bt, fr, i);
975 				} else {
976 					reg->precise = true;
977 					*changed = true;
978 				}
979 			}
980 
981 			for_each_set_bit(i, bt_frame_stack_mask(bt, fr), MAX_BPF_STACK_SLOTS) {
982 				if (verifier_bug_if(i >= bpf_stack_nr_slots(func),
983 						    env, "stack slot %d, total slots %d",
984 						    i, bpf_stack_nr_slots(func)))
985 					return -EFAULT;
986 
987 				ss = bpf_stack_slot(func, i);
988 				if (!bpf_is_spilled_scalar_reg(ss)) {
989 					bt_clear_frame_slot(bt, fr, i);
990 					continue;
991 				}
992 				reg = &ss->spilled_ptr;
993 				if (reg->precise) {
994 					bt_clear_frame_slot(bt, fr, i);
995 				} else {
996 					reg->precise = true;
997 					*changed = true;
998 				}
999 			}
1000 			for (i = 0; i < func->out_stack_arg_cnt; i++) {
1001 				if (!bt_is_frame_stack_arg_slot_set(bt, fr, i))
1002 					continue;
1003 				reg = &func->stack_arg_regs[i];
1004 				if (reg->type != SCALAR_VALUE || reg->precise) {
1005 					bt_clear_frame_stack_arg_slot(bt, fr, i);
1006 				} else {
1007 					reg->precise = true;
1008 					*changed = true;
1009 				}
1010 			}
1011 			if (env->log.level & BPF_LOG_LEVEL2) {
1012 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
1013 					     bt_frame_reg_mask(bt, fr));
1014 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
1015 					fr, env->tmp_str_buf);
1016 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
1017 					       bt_frame_stack_mask(bt, fr));
1018 				verbose(env, "stack=%s: ", env->tmp_str_buf);
1019 				print_verifier_state(env, st, fr, true);
1020 			}
1021 		}
1022 
1023 		if (bt_empty(bt))
1024 			return 0;
1025 
1026 		subseq_idx = first_idx;
1027 		last_idx = st->last_insn_idx;
1028 		first_idx = st->first_insn_idx;
1029 	}
1030 
1031 	/* if we still have requested precise regs or slots, we missed
1032 	 * something (e.g., stack access through non-r10 register), so
1033 	 * fallback to marking all precise
1034 	 */
1035 	if (!bt_empty(bt)) {
1036 		bpf_mark_all_scalars_precise(env, starting_state);
1037 		bt_reset(bt);
1038 	}
1039 
1040 	return 0;
1041 }
1042