xref: /linux/kernel/bpf/diagnostics.c (revision 99a6a288a82bf00ba0b01e72bf85164e848d1d18)
1 // SPDX-License-Identifier: GPL-2.0-only
2 // Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
3 
4 #include <linux/bpf.h>
5 #include <linux/bpf_verifier.h>
6 #include <linux/btf.h>
7 #include <linux/ctype.h>
8 #include <linux/kernel.h>
9 #include <linux/list.h>
10 #include <linux/seq_buf.h>
11 #include <linux/overflow.h>
12 #include <linux/slab.h>
13 #include <linux/stdarg.h>
14 #include <linux/string.h>
15 
16 #include "disasm.h"
17 #include "diagnostics.h"
18 
19 #define REGISTER_TYPE_SAFETY "Register Type Safety"
20 #define MEMORY_SAFETY "Memory Safety"
21 #define RESOURCE_LIFETIME_SAFETY "Resource Lifetime Safety"
22 #define CALL_TYPE_SAFETY "Call Type Safety"
23 #define EXECUTION_CONTEXT_SAFETY "Execution Context Safety"
24 
25 #define BPF_DIAG_TEXT_WIDTH 100
26 #define BPF_DIAG_TEXT_INDENT "  "
27 #define BPF_DIAG_CONTEXT 2
28 #define BPF_DIAG_CONTEXT_CNT (1 + BPF_DIAG_CONTEXT * 2)
29 #define BPF_DIAG_HISTORY_RENDER_MAX 64
30 #define BPF_DIAG_SOURCE_LANE_WIDTH 88
31 #define BPF_DIAG_TAB_WIDTH 8
32 #define BPF_DIAG_FMT_CHUNK_SIZE (PAGE_SIZE - sizeof(struct diag_fmt_chunk))
33 #define BPF_DIAG_FMT_BUF_SIZE 256
34 #define BPF_DIAG_EVENT_LOG_MAX_SIZE (64U << 20)
35 #define DISASM_LINE_LEN 160
36 
37 enum bpf_diag_mod_target_kind {
38 	BPF_DIAG_MOD_TARGET_NONE,
39 	BPF_DIAG_MOD_TARGET_REG,
40 	BPF_DIAG_MOD_TARGET_STACK_ARG,
41 	BPF_DIAG_MOD_TARGET_STACK_SLOT,
42 	BPF_DIAG_MOD_TARGET_STACK_RANGE,
43 };
44 
45 struct bpf_diag_mod_target {
46 	u32 frame_id;
47 	union {
48 		struct {
49 			s16 min_off;
50 			s16 max_off;
51 		} range;
52 		u16 spi;
53 		u8 regno;
54 		u8 stack_arg;
55 	};
56 	u8 frameno;
57 	u8 kind;
58 };
59 
60 static struct bpf_diag_mod_target diag_reg_target(u32 frame_id, u8 frameno, u8 regno)
61 {
62 	return (struct bpf_diag_mod_target){
63 		.frame_id = frame_id,
64 		.frameno = frameno,
65 		.kind = BPF_DIAG_MOD_TARGET_REG,
66 		.regno = regno,
67 	};
68 }
69 
70 static struct bpf_diag_mod_target diag_stack_arg_target(u32 frame_id, u8 frameno, u8 slot)
71 {
72 	return (struct bpf_diag_mod_target){
73 		.frame_id = frame_id,
74 		.frameno = frameno,
75 		.kind = BPF_DIAG_MOD_TARGET_STACK_ARG,
76 		.stack_arg = slot,
77 	};
78 }
79 
80 static struct bpf_diag_mod_target diag_stack_slot_target(u32 frame_id, u8 frameno, u16 spi)
81 {
82 	return (struct bpf_diag_mod_target){
83 		.frame_id = frame_id,
84 		.frameno = frameno,
85 		.kind = BPF_DIAG_MOD_TARGET_STACK_SLOT,
86 		.spi = spi,
87 	};
88 }
89 
90 static struct bpf_diag_mod_target diag_stack_range_target(u32 frame_id, u8 frameno,
91 							  s16 min_off, s16 max_off)
92 {
93 	return (struct bpf_diag_mod_target){
94 		.frame_id = frame_id,
95 		.frameno = frameno,
96 		.kind = BPF_DIAG_MOD_TARGET_STACK_RANGE,
97 		.range.min_off = min_off,
98 		.range.max_off = max_off,
99 	};
100 }
101 
102 struct bpf_diag_reg_snapshot {
103 	u32 type;
104 	u32 btf_id;
105 	const struct bpf_map *map_ptr;
106 	const struct btf *btf;
107 	struct tnum var_off;
108 	struct cnum64 r64;
109 };
110 
111 enum bpf_diag_history_kind {
112 	BPF_DIAG_HISTORY_BRANCH,
113 	BPF_DIAG_HISTORY_MOD,
114 	BPF_DIAG_HISTORY_REF_ACQUIRE,
115 	BPF_DIAG_HISTORY_REF_RELEASE,
116 	BPF_DIAG_HISTORY_CONTEXT,
117 };
118 
119 struct bpf_diag_history_event {
120 	u32 insn_idx : 24;
121 	u32 kind : 8;
122 	u8 in_lineage : 1;
123 	union {
124 		struct {
125 			bool cond_true;
126 		} branch;
127 		struct {
128 			struct bpf_diag_mod_target target;
129 			struct bpf_diag_mod_target origin;
130 			struct bpf_diag_reg_snapshot old, new;
131 			u8 reason;
132 			bool origin_valid;
133 		} mod;
134 		struct {
135 			u32 ref_id;
136 		} ref;
137 		struct {
138 			u32 depth;
139 			u8 kind;
140 			bool enter;
141 		} ctx;
142 	};
143 };
144 
145 enum bpf_diag_history_scope {
146 	BPF_DIAG_HISTORY_SCOPE_REG,
147 	BPF_DIAG_HISTORY_SCOPE_STACK_ARG,
148 	BPF_DIAG_HISTORY_SCOPE_REF,
149 	BPF_DIAG_HISTORY_SCOPE_CONTEXT,
150 };
151 
152 struct bpf_diag_history_opts {
153 	enum bpf_diag_history_scope scope;
154 	u32 frame_id;
155 	u32 frameno;
156 	int regno;
157 	int stack_arg_slot;
158 	u32 ref_id;
159 	enum bpf_diag_context_kind ctx_kind;
160 	u32 ctx_depth;
161 };
162 
163 static void diag_print_history(struct bpf_verifier_env *env,
164 			       const struct bpf_diag_history_opts *opts);
165 static bool diag_target_matches(const struct bpf_diag_mod_target *event_target,
166 				const struct bpf_diag_mod_target *target);
167 static const char *diag_context_name(enum bpf_diag_context_kind kind);
168 struct disasm_line {
169 	char text[DISASM_LINE_LEN];
170 	int idx;
171 	bool valid;
172 };
173 
174 struct disasm_ctx {
175 	struct bpf_verifier_env *env;
176 	struct seq_buf seq;
177 };
178 
179 struct diag_fmt_chunk {
180 	struct list_head node;
181 	struct seq_buf seq;
182 	char data[];
183 };
184 
185 struct diag_fmt_mark {
186 	struct diag_fmt_chunk *chunk;
187 	size_t len;
188 };
189 
190 struct bpf_diag_log {
191 	struct bpf_diag_history_event *events;
192 	/* Sequence number of the oldest retained event on the active path. */
193 	u64 first_seq;
194 	u32 cnt;
195 	u32 cap;
196 	u32 head;
197 	bool growth_failed;
198 };
199 
200 struct bpf_diag_scratch {
201 	struct bpf_linfo_source source_lines[BPF_DIAG_CONTEXT_CNT];
202 	struct disasm_line disasm_lines[BPF_DIAG_CONTEXT_CNT];
203 };
204 
205 struct bpf_diag_mod_scope {
206 	struct bpf_reg_state target_reg_snapshot;
207 	struct bpf_diag_mod_target target;
208 	struct bpf_diag_mod_target origin;
209 	enum bpf_diag_mod_reason reason;
210 	u32 insn_idx;
211 	bool active;
212 	bool origin_valid;
213 };
214 
215 struct bpf_diag {
216 	struct bpf_diag_log log;
217 	struct bpf_diag_scratch scratch;
218 	struct list_head fmt_chunks;
219 	struct bpf_diag_mod_scope mod;
220 	u32 frame_id_gen;
221 };
222 
223 bool bpf_diag_enabled(const struct bpf_verifier_env *env)
224 {
225 	return env->log.level & BPF_LOG_LEVEL;
226 }
227 
228 static void diag_write(struct bpf_verifier_env *env, const char *fmt, ...) __printf(2, 3);
229 
230 int bpf_diag_init(struct bpf_verifier_env *env)
231 {
232 	if (!bpf_diag_enabled(env))
233 		return 0;
234 
235 	env->diag = kzalloc_obj(struct bpf_diag, GFP_KERNEL_ACCOUNT);
236 	if (!env->diag)
237 		return -ENOMEM;
238 
239 	INIT_LIST_HEAD(&env->diag->fmt_chunks);
240 	return 0;
241 }
242 
243 void bpf_diag_init_frame(struct bpf_verifier_env *env, struct bpf_func_state *state)
244 {
245 	if (env->diag)
246 		state->diag_frame_id = ++env->diag->frame_id_gen;
247 }
248 
249 static char *diag_fmt_alloc(struct bpf_verifier_env *env, size_t size)
250 {
251 	struct bpf_diag *diag = env->diag;
252 	struct diag_fmt_chunk *chunk;
253 	size_t capacity, available;
254 	char *buf;
255 
256 	if (!diag || !size || size > INT_MAX)
257 		return NULL;
258 
259 	if (!list_empty(&diag->fmt_chunks)) {
260 		chunk = list_last_entry(&diag->fmt_chunks, struct diag_fmt_chunk, node);
261 		available = seq_buf_get_buf(&chunk->seq, &buf);
262 		if (available >= size)
263 			goto commit;
264 	}
265 
266 	capacity = max_t(size_t, BPF_DIAG_FMT_CHUNK_SIZE, size);
267 	chunk = kmalloc(struct_size(chunk, data, capacity), GFP_KERNEL_ACCOUNT);
268 	if (!chunk)
269 		return NULL;
270 
271 	seq_buf_init(&chunk->seq, chunk->data, capacity);
272 	list_add_tail(&chunk->node, &diag->fmt_chunks);
273 	available = seq_buf_get_buf(&chunk->seq, &buf);
274 	if (WARN_ON_ONCE(available < size))
275 		return NULL;
276 
277 commit:
278 	seq_buf_commit(&chunk->seq, size);
279 	return buf;
280 }
281 
282 char *bpf_diag_fmt_buf(struct bpf_verifier_env *env, size_t size)
283 {
284 	char *buf;
285 
286 	buf = diag_fmt_alloc(env, size);
287 	if (buf)
288 		buf[0] = '\0';
289 	return buf;
290 }
291 
292 const char *bpf_diag_vfmt(struct bpf_verifier_env *env, const char *fmt, va_list args)
293 {
294 	va_list copy;
295 	char *buf;
296 	int len;
297 
298 	va_copy(copy, args);
299 	len = vsnprintf(NULL, 0, fmt, copy);
300 	va_end(copy);
301 	if (len < 0 || len == INT_MAX)
302 		return "";
303 
304 	buf = diag_fmt_alloc(env, len + 1);
305 	if (buf)
306 		vsnprintf(buf, len + 1, fmt, args);
307 	return buf ?: "";
308 }
309 
310 const char *bpf_diag_fmt(struct bpf_verifier_env *env, const char *fmt, ...)
311 {
312 	const char *buf;
313 	va_list args;
314 
315 	va_start(args, fmt);
316 	buf = bpf_diag_vfmt(env, fmt, args);
317 	va_end(args);
318 	return buf;
319 }
320 
321 static struct diag_fmt_mark diag_fmt_save(struct bpf_verifier_env *env)
322 {
323 	struct bpf_diag *diag = env->diag;
324 	struct diag_fmt_mark mark = {};
325 
326 	if (!diag || list_empty(&diag->fmt_chunks))
327 		return mark;
328 
329 	mark.chunk = list_last_entry(&diag->fmt_chunks, struct diag_fmt_chunk, node);
330 	mark.len = mark.chunk->seq.len;
331 	return mark;
332 }
333 
334 static void diag_fmt_restore(struct bpf_verifier_env *env, struct diag_fmt_mark mark)
335 {
336 	struct bpf_diag *diag = env->diag;
337 	struct diag_fmt_chunk *chunk;
338 
339 	if (!diag)
340 		return;
341 
342 	while (!list_empty(&diag->fmt_chunks)) {
343 		chunk = list_last_entry(&diag->fmt_chunks, struct diag_fmt_chunk, node);
344 		if (chunk == mark.chunk)
345 			break;
346 		list_del(&chunk->node);
347 		kfree(chunk);
348 	}
349 
350 	if (mark.chunk) {
351 		mark.chunk->seq.len = mark.len;
352 		seq_buf_str(&mark.chunk->seq);
353 	}
354 }
355 
356 void bpf_diag_free(struct bpf_verifier_env *env)
357 {
358 	struct bpf_diag *diag = env->diag;
359 
360 	if (!diag)
361 		return;
362 
363 	diag_fmt_restore(env, (struct diag_fmt_mark){});
364 	kvfree(diag->log.events);
365 	kfree(diag);
366 	env->diag = NULL;
367 }
368 
369 static void diag_write(struct bpf_verifier_env *env, const char *fmt, ...)
370 {
371 	va_list args;
372 
373 	if (!bpf_diag_enabled(env))
374 		return;
375 
376 	va_start(args, fmt);
377 	bpf_verifier_vlog(&env->log, fmt, args);
378 	va_end(args);
379 }
380 
381 static u64 log_end(const struct bpf_diag_log *log)
382 {
383 	return log->first_seq + log->cnt;
384 }
385 
386 static u32 log_pos(const struct bpf_diag_log *log, u32 idx)
387 {
388 	u32 pos = log->head + idx;
389 
390 	return pos < log->cap ? pos : pos - log->cap;
391 }
392 
393 u64 bpf_diag_event_log_save(struct bpf_verifier_env *env)
394 {
395 	struct bpf_diag *diag = env->diag;
396 
397 	return diag ? log_end(&diag->log) : 0;
398 }
399 
400 void bpf_diag_event_log_restore(struct bpf_verifier_env *env, u64 log_pos)
401 {
402 	struct bpf_diag *diag = env->diag;
403 	struct bpf_diag_log *log;
404 	u64 end_seq;
405 
406 	if (!diag)
407 		return;
408 
409 	log = &diag->log;
410 	end_seq = log_end(log);
411 	if (WARN_ON_ONCE(log_pos > end_seq))
412 		log_pos = end_seq;
413 
414 	/*
415 	 * A deep abandoned path may have rotated away the shared prefix. In
416 	 * that case, restart with an empty retained suffix and remember that
417 	 * every event before the restored mark is unavailable.
418 	 */
419 	if (log_pos <= log->first_seq) {
420 		log->first_seq = log_pos;
421 		log->head = 0;
422 		log->cnt = 0;
423 		return;
424 	}
425 
426 	log->cnt = log_pos - log->first_seq;
427 }
428 
429 u32 bpf_diag_irq_depth(const struct bpf_verifier_state *state)
430 {
431 	u32 depth = 0;
432 	int i;
433 
434 	for (i = 0; i < state->acquired_refs; i++) {
435 		if (state->refs[i].type == REF_TYPE_IRQ)
436 			depth++;
437 	}
438 
439 	return depth;
440 }
441 
442 static void diag_append_history(struct bpf_verifier_env *env,
443 				const struct bpf_diag_history_event *event)
444 {
445 	struct bpf_diag_history_event *events;
446 	struct bpf_diag *diag = env->diag;
447 	struct bpf_diag_log *log;
448 	u32 cap, max_events;
449 
450 	if (!diag)
451 		return;
452 	log = &diag->log;
453 
454 	if (log->cnt < log->cap) {
455 		log->events[log_pos(log, log->cnt++)] = *event;
456 		return;
457 	}
458 
459 	max_events = BPF_DIAG_EVENT_LOG_MAX_SIZE / sizeof(*events);
460 	if (log->growth_failed || log->cap == max_events)
461 		goto rotate;
462 
463 	cap = min(log->cap ? log->cap * 2 : 64, max_events);
464 	events = kvrealloc(log->events, array_size(cap, sizeof(*events)), GFP_KERNEL_ACCOUNT);
465 	if (!events) {
466 		log->growth_failed = true;
467 		goto rotate;
468 	}
469 	log->events = events;
470 	log->cap = cap;
471 	log->events[log->cnt++] = *event;
472 	return;
473 
474 rotate:
475 	if (log->cap) {
476 		log->events[log->head++] = *event;
477 		if (log->head == log->cap)
478 			log->head = 0;
479 	}
480 	log->first_seq++;
481 }
482 
483 static void diag_print_wrapped_prefixed(struct bpf_verifier_env *env, const char *first_prefix,
484 					const char *next_prefix, const char *text)
485 {
486 	const char *prefix = first_prefix;
487 
488 	while (*text) {
489 		const char *line = text;
490 		int prefix_len = strlen(prefix);
491 		int text_width = BPF_DIAG_TEXT_WIDTH - prefix_len;
492 		int len = 0, last_space = -1;
493 
494 		if (text_width < 1)
495 			text_width = 1;
496 
497 		while (line[len] && line[len] != '\n' && len < text_width) {
498 			if (line[len] == ' ')
499 				last_space = len;
500 			len++;
501 		}
502 
503 		if (line[len] && line[len] != '\n' && line[len] != ' ' && last_space > 0)
504 			len = last_space;
505 
506 		diag_write(env, "%s%.*s\n", prefix, len, line);
507 
508 		text = line + len;
509 		while (*text == ' ')
510 			text++;
511 		if (*text == '\n')
512 			text++;
513 
514 		prefix = next_prefix;
515 	}
516 }
517 
518 const char *bpf_diag_fmt_btf_type(struct bpf_verifier_env *env, const struct btf *btf, u32 type_id)
519 {
520 	char *buf = bpf_diag_fmt_buf(env, BPF_DIAG_FMT_BUF_SIZE);
521 	size_t len;
522 	int ret;
523 
524 	if (!buf)
525 		return "";
526 
527 	buf[0] = '\0';
528 	ret = btf_type_name_to_buf(btf, type_id, buf, BPF_DIAG_FMT_BUF_SIZE);
529 	if (ret < 0 || !buf[0]) {
530 		scnprintf(buf, BPF_DIAG_FMT_BUF_SIZE, "BTF type ID %u", type_id);
531 		return buf;
532 	}
533 
534 	len = strlen(buf);
535 	if (len && buf[len - 1] == '{')
536 		buf[len - 1] = '\0';
537 	return buf;
538 }
539 
540 static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, va_list args)
541 	__printf(2, 0);
542 
543 static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, va_list args)
544 {
545 	char *buf;
546 
547 	if (!bpf_diag_enabled(env))
548 		return;
549 
550 	buf = kvasprintf(GFP_KERNEL_ACCOUNT, fmt, args);
551 	if (!buf) {
552 		diag_write(env, "%s<failed to allocate diagnostic text>\n", BPF_DIAG_TEXT_INDENT);
553 		return;
554 	}
555 
556 	diag_print_wrapped_prefixed(env, BPF_DIAG_TEXT_INDENT, BPF_DIAG_TEXT_INDENT, buf);
557 	kfree(buf);
558 }
559 
560 static int diag_line_width(unsigned int line)
561 {
562 	int width = 1;
563 
564 	while (line >= 10) {
565 		line /= 10;
566 		width++;
567 	}
568 
569 	return width;
570 }
571 
572 static int diag_line_indent(const char *line)
573 {
574 	int indent = 0;
575 
576 	while (*line == ' ' || *line == '\t') {
577 		if (*line == '\t')
578 			indent = round_up(indent + 1, BPF_DIAG_TAB_WIDTH);
579 		else
580 			indent++;
581 		line++;
582 	}
583 
584 	return indent;
585 }
586 
587 static void disasm_print(void *private_data, const char *fmt, ...) __printf(2, 3);
588 
589 static void disasm_print(void *private_data, const char *fmt, ...)
590 {
591 	struct disasm_ctx *ctx = private_data;
592 	va_list args;
593 
594 	va_start(args, fmt);
595 	seq_buf_vprintf(&ctx->seq, fmt, args);
596 	va_end(args);
597 }
598 
599 static const char *disasm_kfunc_name(void *private_data, const struct bpf_insn *insn)
600 {
601 	struct disasm_ctx *ctx = private_data;
602 
603 	return bpf_disasm_kfunc_name(ctx->env, insn);
604 }
605 
606 static void format_disasm_line(struct bpf_verifier_env *env, int insn_idx,
607 			       struct disasm_line *line)
608 {
609 	struct disasm_ctx ctx = { .env = env };
610 	struct bpf_insn *insn;
611 	const struct bpf_insn_cbs cbs = {
612 		.cb_call = disasm_kfunc_name,
613 		.cb_print = disasm_print,
614 		.private_data = &ctx,
615 	};
616 
617 	line->idx = insn_idx;
618 	line->valid = false;
619 	seq_buf_init(&ctx.seq, line->text, sizeof(line->text));
620 
621 	if (insn_idx < 0 || insn_idx >= env->prog->len)
622 		return;
623 
624 	if (insn_idx > 0 && bpf_is_ldimm64(&env->prog->insnsi[insn_idx - 1]))
625 		return;
626 
627 	insn = &env->prog->insnsi[insn_idx];
628 	if (bpf_is_ldimm64(insn) && insn_idx + 1 >= env->prog->len)
629 		return;
630 
631 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
632 	seq_buf_str(&ctx.seq);
633 	ctx.seq.len = strnlen(line->text, sizeof(line->text));
634 	while (ctx.seq.len && line->text[ctx.seq.len - 1] == '\n')
635 		seq_buf_pop(&ctx.seq);
636 	seq_buf_str(&ctx.seq);
637 
638 	line->valid = true;
639 }
640 
641 static void diag_format_source_text(char *buf, size_t size, const char *line, int width)
642 {
643 	int col = 0, len = 0;
644 
645 	if (!size)
646 		return;
647 	if (width <= 0) {
648 		buf[0] = '\0';
649 		return;
650 	}
651 
652 	line = line ?: "...";
653 	while (*line && col < width && len + 1 < size) {
654 		if (*line == '\t') {
655 			int next = round_up(col + 1, BPF_DIAG_TAB_WIDTH);
656 
657 			while (col < next && col < width && len + 1 < size) {
658 				buf[len++] = ' ';
659 				col++;
660 			}
661 			line++;
662 			continue;
663 		}
664 
665 		buf[len++] = *line++;
666 		col++;
667 	}
668 
669 	if (*line) {
670 		int ellipsis_len = min(3, width);
671 
672 		while (len > 0 && col > width - ellipsis_len) {
673 			len--;
674 			col--;
675 		}
676 		while (ellipsis_len-- && len + 1 < size)
677 			buf[len++] = '.';
678 	}
679 
680 	buf[len] = '\0';
681 }
682 
683 static void diag_format_source_lane(char *buf, size_t size, const char *source_prefix,
684 				    int source_line_width, int line_num, const char *line)
685 {
686 	int len, text_width;
687 
688 	if (line_num <= 0) {
689 		buf[0] = '\0';
690 		return;
691 	}
692 
693 	len = scnprintf(buf, size, "%s%*d | ", source_prefix, source_line_width, line_num);
694 	text_width = BPF_DIAG_SOURCE_LANE_WIDTH - len;
695 	diag_format_source_text(buf + len, size - len, line, text_width);
696 }
697 
698 static void bpf_diag_header(struct bpf_verifier_env *env, const char *category,
699 			    const char *problem)
700 {
701 	char first;
702 
703 	if (!bpf_diag_enabled(env))
704 		return;
705 
706 	category = category ?: "Verifier Error";
707 	problem = problem ?: "";
708 
709 	if (!problem[0]) {
710 		diag_write(env, "\nVerification failed: %s\n", category);
711 		return;
712 	}
713 
714 	first = toupper(problem[0]);
715 	diag_write(env, "\nVerification failed: %s: %c%s\n", category, first, problem + 1);
716 }
717 
718 static void diag_reason(struct bpf_verifier_env *env, const char *fmt, ...) __printf(2, 3);
719 static void diag_suggestion(struct bpf_verifier_env *env, const char *fmt, ...)
720 	__printf(2, 3);
721 
722 static void diag_section(struct bpf_verifier_env *env, const char *title)
723 {
724 	if (!bpf_diag_enabled(env))
725 		return;
726 
727 	diag_write(env, "\n%s:\n", title);
728 }
729 
730 static void diag_reason(struct bpf_verifier_env *env, const char *fmt, ...)
731 {
732 	va_list args;
733 
734 	if (!bpf_diag_enabled(env))
735 		return;
736 
737 	diag_section(env, "Reason");
738 
739 	va_start(args, fmt);
740 	diag_vprint_indented(env, fmt, args);
741 	va_end(args);
742 }
743 
744 static void diag_suggestion(struct bpf_verifier_env *env, const char *fmt, ...)
745 {
746 	va_list args;
747 
748 	if (!bpf_diag_enabled(env))
749 		return;
750 
751 	diag_section(env, "Suggestion");
752 
753 	va_start(args, fmt);
754 	diag_vprint_indented(env, fmt, args);
755 	va_end(args);
756 	diag_write(env, "\n");
757 }
758 
759 static void diag_print_source_annotation(struct bpf_verifier_env *env, int line_width, int indent,
760 					 const char *label, const char *msg)
761 {
762 	const char *first_prefix, *next_prefix, *text;
763 
764 	indent = min_t(int, indent, max_t(int, 0, BPF_DIAG_SOURCE_LANE_WIDTH - line_width - 8));
765 	text = bpf_diag_fmt(env, "%s: %s", label, msg);
766 	first_prefix = bpf_diag_fmt(env, "  %*s | %*s^-- ", line_width + 4, "", indent, "");
767 	next_prefix = bpf_diag_fmt(env, "  %*s | %*s    ", line_width + 4, "", indent, "");
768 
769 	diag_print_wrapped_prefixed(env, first_prefix, next_prefix, text);
770 }
771 
772 static void diag_print_insn_context(struct bpf_verifier_env *env, u32 insn_idx,
773 				    struct disasm_line *disasm_lines)
774 {
775 	int insn_width = diag_line_width(env->prog->len ? env->prog->len - 1 : 0);
776 	int i;
777 
778 	for (i = 0; i < BPF_DIAG_CONTEXT_CNT; i++) {
779 		int row = i - BPF_DIAG_CONTEXT;
780 
781 		format_disasm_line(env, insn_idx + row, &disasm_lines[i]);
782 	}
783 
784 	diag_write(env, "  Instruction context:\n");
785 	for (i = 0; i < BPF_DIAG_CONTEXT_CNT; i++) {
786 		struct disasm_line *line = &disasm_lines[i];
787 
788 		if (line->valid)
789 			diag_write(env, "  %s%*d | %s\n",
790 				   line->idx == insn_idx ? ">>> " : "    ",
791 				   insn_width, line->idx, line->text);
792 	}
793 }
794 
795 static void bpf_diag_source(struct bpf_verifier_env *env, u32 insn_idx, const char *label,
796 			    const char *fmt, ...)
797 {
798 	struct bpf_diag_scratch *scratch;
799 	struct bpf_linfo_source *source_lines;
800 	struct disasm_line *disasm_lines;
801 	struct bpf_linfo_source src = {};
802 	struct diag_fmt_mark mark;
803 	const struct bpf_line_info *linfo;
804 	const struct bpf_subprog_info *subprog;
805 	struct btf *btf = env->prog->aux->btf;
806 	char *source_lane;
807 	const char *msg;
808 	const char *func;
809 	int start_line, end_line, width, indent, subprogno, linfo_start, linfo_end, i;
810 	va_list args;
811 
812 	if (!bpf_diag_enabled(env))
813 		return;
814 	if (!env->diag)
815 		return;
816 
817 	mark = diag_fmt_save(env);
818 	label = label ?: "note";
819 	scratch = &env->diag->scratch;
820 	source_lines = scratch->source_lines;
821 	disasm_lines = scratch->disasm_lines;
822 	memset(source_lines, 0, sizeof(scratch->source_lines));
823 	memset(disasm_lines, 0, sizeof(scratch->disasm_lines));
824 
825 	va_start(args, fmt);
826 	msg = bpf_diag_vfmt(env, fmt, args);
827 	va_end(args);
828 	if (!*msg)
829 		msg = "<failed to allocate diagnostic text>";
830 
831 	linfo = bpf_find_linfo(env->prog, insn_idx);
832 	if (btf && linfo)
833 		bpf_get_linfo_source(btf, linfo, &src);
834 	if (!src.file || !*src.file || !src.line || !*src.line) {
835 		diag_write(env, "  insn %u\n", insn_idx);
836 		diag_print_source_annotation(env, 0, 0, label, msg);
837 		diag_print_insn_context(env, insn_idx, disasm_lines);
838 		goto out_restore;
839 	}
840 
841 	subprog = bpf_find_containing_subprog(env, insn_idx);
842 	subprogno = subprog ? subprog - env->subprog_info : -ENOENT;
843 	func = subprogno >= 0 ? bpf_subprog_name(env, subprogno) : NULL;
844 	if (func && *func)
845 		diag_write(env, "  %s @ %s:%d:%d\n", func, src.file, src.line_num, src.line_col);
846 	else
847 		diag_write(env, "  %s:%d:%d\n", src.file, src.line_num, src.line_col);
848 
849 	start_line = src.line_num - BPF_DIAG_CONTEXT;
850 	end_line = src.line_num + BPF_DIAG_CONTEXT;
851 	width = diag_line_width(end_line);
852 	indent = diag_line_indent(src.line);
853 	for (i = 0; i < BPF_DIAG_CONTEXT_CNT; i++)
854 		source_lines[i].line_num = start_line + i;
855 
856 	linfo = env->prog->aux->linfo;
857 	linfo_start = subprog ? subprog->linfo_idx : 0;
858 	linfo_end = subprogno >= 0 && subprogno + 1 < env->subprog_cnt ?
859 		    env->subprog_info[subprogno + 1].linfo_idx : env->prog->aux->nr_linfo;
860 	for (i = linfo_start; i < linfo_end; i++) {
861 		struct bpf_linfo_source line_src;
862 		int idx;
863 
864 		bpf_get_linfo_source(btf, &linfo[i], &line_src);
865 		if (line_src.file_name_off != src.file_name_off ||
866 		    line_src.line_num < start_line || line_src.line_num > end_line ||
867 		    !line_src.line || !*line_src.line)
868 			continue;
869 
870 		idx = line_src.line_num - start_line;
871 		if (!source_lines[idx].line)
872 			source_lines[idx] = line_src;
873 	}
874 
875 	diag_write(env, "  Source context:\n");
876 	source_lane = bpf_diag_fmt_buf(env, BPF_DIAG_FMT_BUF_SIZE);
877 	if (!source_lane)
878 		goto out_restore;
879 	for (i = 0; i < BPF_DIAG_CONTEXT_CNT; i++) {
880 		const char *source_prefix;
881 
882 		source_prefix = source_lines[i].line_num == src.line_num ? ">>> " : "    ";
883 		diag_format_source_lane(source_lane, BPF_DIAG_FMT_BUF_SIZE, source_prefix, width,
884 					source_lines[i].line_num, source_lines[i].line);
885 		diag_write(env, "  %s\n", source_lane);
886 		if (source_lines[i].line_num == src.line_num)
887 			diag_print_source_annotation(env, width, indent, label, msg);
888 	}
889 	diag_print_insn_context(env, insn_idx, disasm_lines);
890 
891 out_restore:
892 	diag_fmt_restore(env, mark);
893 }
894 
895 static const struct bpf_func_state *diag_current_frame(const struct bpf_verifier_env *env)
896 {
897 	return env->cur_state->frame[env->cur_state->curframe];
898 }
899 
900 void bpf_diag_register_type(struct bpf_verifier_env *env, u32 insn_idx, int regno,
901 			    const char *problem, const char *reason, const char *suggestion)
902 {
903 	const struct bpf_func_state *frame = diag_current_frame(env);
904 	struct bpf_diag_history_opts opts = {
905 		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
906 		.frame_id = frame->diag_frame_id,
907 		.frameno = frame->frameno,
908 		.regno = regno,
909 	};
910 
911 	bpf_diag_header(env, REGISTER_TYPE_SAFETY, problem);
912 	diag_reason(env, "%s", reason);
913 
914 	diag_section(env, "At");
915 	bpf_diag_source(env, insn_idx, "error", "%s", problem);
916 
917 	if (regno >= 0)
918 		diag_print_history(env, &opts);
919 
920 	diag_suggestion(env, "%s", suggestion);
921 }
922 
923 const char *bpf_diag_reg_type_plain(struct bpf_verifier_env *env, enum bpf_reg_type type)
924 {
925 	switch (base_type(type)) {
926 	case NOT_INIT:
927 		return "an uninitialized value";
928 	case SCALAR_VALUE:
929 		return "an integer scalar";
930 	case PTR_TO_CTX:
931 		return "a context pointer";
932 	case PTR_TO_STACK:
933 		return "a stack pointer";
934 	case PTR_TO_MAP_VALUE:
935 		if (type_may_be_null(type))
936 			return "a nullable map value pointer";
937 		return "a map value pointer";
938 	case PTR_TO_MEM:
939 		if (type_may_be_null(type))
940 			return "a nullable memory pointer";
941 		return "a memory pointer";
942 	case PTR_TO_BTF_ID:
943 		if (type_may_be_null(type))
944 			return "a nullable kernel object pointer";
945 		if (type_is_non_owning_ref(type))
946 			return "a borrowed allocated object pointer";
947 		if (type_is_ptr_alloc_obj(type))
948 			return "an owned allocated object pointer";
949 		if (type_flag(type) & PTR_UNTRUSTED)
950 			return "an untrusted kernel object pointer";
951 		return "a kernel object pointer";
952 	default:
953 		return reg_type_str(env, type);
954 	}
955 }
956 
957 static const char *diag_arg_ordinal(int argno)
958 {
959 	switch (argno) {
960 	case 1:
961 		return "first";
962 	case 2:
963 		return "second";
964 	case 3:
965 		return "third";
966 	case 4:
967 		return "fourth";
968 	case 5:
969 		return "fifth";
970 	case 6:
971 		return "sixth";
972 	case 7:
973 		return "seventh";
974 	case 8:
975 		return "eighth";
976 	case 9:
977 		return "ninth";
978 	case 10:
979 		return "tenth";
980 	case 11:
981 		return "eleventh";
982 	case 12:
983 		return "twelfth";
984 	default:
985 		return NULL;
986 	}
987 }
988 
989 void bpf_diag_call_type(struct bpf_verifier_env *env, u32 insn_idx, int argno, int regno,
990 			int stack_arg_slot, const char *call_name, const char *arg_name,
991 			const char *reason, const char *suggestion)
992 {
993 	const struct bpf_func_state *frame = diag_current_frame(env);
994 	struct bpf_diag_history_opts opts = {
995 		.frame_id = frame->diag_frame_id,
996 		.frameno = frame->frameno,
997 	};
998 	const char *ordinal = diag_arg_ordinal(argno);
999 	const char *arg_desc;
1000 	bool print_history = true;
1001 
1002 	if (regno >= 0) {
1003 		opts.scope = BPF_DIAG_HISTORY_SCOPE_REG;
1004 		opts.regno = regno;
1005 	} else if (stack_arg_slot >= 0) {
1006 		opts.scope = BPF_DIAG_HISTORY_SCOPE_STACK_ARG;
1007 		opts.stack_arg_slot = stack_arg_slot;
1008 	} else {
1009 		print_history = false;
1010 	}
1011 
1012 	if (ordinal && arg_name)
1013 		arg_desc = bpf_diag_fmt(env, "%s argument (%s)", ordinal, arg_name);
1014 	else if (ordinal)
1015 		arg_desc = bpf_diag_fmt(env, "%s argument", ordinal);
1016 	else if (arg_name)
1017 		arg_desc = bpf_diag_fmt(env, "argument %s", arg_name);
1018 	else
1019 		arg_desc = "argument";
1020 
1021 	bpf_diag_header(env, CALL_TYPE_SAFETY, "invalid call argument");
1022 	diag_reason(env, "The %s to %s does not satisfy the verifier contract: %s.",
1023 		    arg_desc, call_name, reason);
1024 
1025 	diag_section(env, "At");
1026 	bpf_diag_source(env, insn_idx, "error", "invalid %s for %s", arg_desc, call_name);
1027 
1028 	if (print_history)
1029 		diag_print_history(env, &opts);
1030 
1031 	diag_suggestion(env, "%s", suggestion);
1032 }
1033 
1034 static const char *diag_context_constraint(enum bpf_diag_context_kind kind)
1035 {
1036 	switch (kind) {
1037 	case BPF_DIAG_CONTEXT_RCU:
1038 		return "RCU read-side critical sections cannot call operations that may sleep";
1039 	case BPF_DIAG_CONTEXT_PREEMPT:
1040 		return "preemption-disabled code cannot call operations that may sleep";
1041 	case BPF_DIAG_CONTEXT_IRQ:
1042 		return "IRQ-disabled code cannot call operations that may sleep";
1043 	case BPF_DIAG_CONTEXT_LOCK:
1044 		return "code holding a BPF spin lock cannot call operations that may sleep";
1045 	case BPF_DIAG_CONTEXT_NONE:
1046 	default:
1047 		return NULL;
1048 	}
1049 }
1050 
1051 static const char *diag_active_context(struct bpf_verifier_env *env, u32 depth,
1052 				       const char *context)
1053 {
1054 	if (depth == 1)
1055 		return bpf_diag_fmt(env, "an active %s (depth 1)", context);
1056 	return bpf_diag_fmt(env, "%u active %ss (depth %u)", depth, context, depth);
1057 }
1058 
1059 static u32 diag_context_depth(struct bpf_verifier_env *env, enum bpf_diag_context_kind kind)
1060 {
1061 	switch (kind) {
1062 	case BPF_DIAG_CONTEXT_RCU:
1063 		return env->cur_state->active_rcu_locks;
1064 	case BPF_DIAG_CONTEXT_PREEMPT:
1065 		return env->cur_state->active_preempt_locks;
1066 	case BPF_DIAG_CONTEXT_IRQ:
1067 		return bpf_diag_irq_depth(env->cur_state);
1068 	case BPF_DIAG_CONTEXT_LOCK:
1069 		return env->cur_state->active_locks;
1070 	case BPF_DIAG_CONTEXT_NONE:
1071 	default:
1072 		return 0;
1073 	}
1074 }
1075 
1076 void bpf_diag_ctx_forbidden(struct bpf_verifier_env *env, u32 insn_idx,
1077 			    const char *operation, const char *suggestion)
1078 {
1079 	struct bpf_diag_history_opts opts;
1080 	enum bpf_diag_context_kind ctx_kind;
1081 	const char *constraint, *context;
1082 	u32 depth;
1083 
1084 	if (env->cur_state->active_rcu_locks)
1085 		ctx_kind = BPF_DIAG_CONTEXT_RCU;
1086 	else if (env->cur_state->active_preempt_locks)
1087 		ctx_kind = BPF_DIAG_CONTEXT_PREEMPT;
1088 	else if (env->cur_state->active_irq_id)
1089 		ctx_kind = BPF_DIAG_CONTEXT_IRQ;
1090 	else if (env->cur_state->active_locks)
1091 		ctx_kind = BPF_DIAG_CONTEXT_LOCK;
1092 	else
1093 		ctx_kind = BPF_DIAG_CONTEXT_NONE;
1094 
1095 	depth = diag_context_depth(env, ctx_kind);
1096 	opts = (struct bpf_diag_history_opts) {
1097 		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
1098 		.ctx_kind = ctx_kind,
1099 		.ctx_depth = depth,
1100 	};
1101 	constraint = diag_context_constraint(ctx_kind);
1102 	context = diag_context_name(ctx_kind);
1103 
1104 	bpf_diag_header(env, EXECUTION_CONTEXT_SAFETY,
1105 			"operation is not allowed in this context");
1106 	if (constraint) {
1107 		if (depth) {
1108 			diag_reason(
1109 				env, "The operation %s cannot be used in %s because %s. This path is still inside %s.",
1110 				operation, context, constraint, diag_active_context(env, depth, context));
1111 		} else {
1112 			diag_reason(env, "The operation %s cannot be used in %s because %s.",
1113 				    operation, context, constraint);
1114 		}
1115 	} else {
1116 		diag_reason(env, "The operation %s cannot be used in %s.", operation,
1117 			    context);
1118 	}
1119 
1120 	diag_section(env, "At");
1121 	bpf_diag_source(env, insn_idx, "error", "%s is not allowed in %s", operation,
1122 			context);
1123 
1124 	if (ctx_kind != BPF_DIAG_CONTEXT_NONE)
1125 		diag_print_history(env, &opts);
1126 
1127 	diag_suggestion(env, "%s", suggestion);
1128 }
1129 
1130 void bpf_diag_ctx_active(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
1131 			 enum bpf_diag_context_kind ctx_kind, const char *suggestion)
1132 {
1133 	u32 depth = diag_context_depth(env, ctx_kind);
1134 	struct bpf_diag_history_opts opts = {
1135 		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
1136 		.ctx_kind = ctx_kind,
1137 		.ctx_depth = depth,
1138 	};
1139 	const char *context = diag_context_name(ctx_kind);
1140 
1141 	bpf_diag_header(env, EXECUTION_CONTEXT_SAFETY,
1142 			"operation is not allowed in this context");
1143 	diag_reason(
1144 		env, "The operation %s cannot be used while this path is still inside %s. Leave the region before this operation.",
1145 		operation, diag_active_context(env, depth, context));
1146 
1147 	diag_section(env, "At");
1148 	bpf_diag_source(env, insn_idx, "error", "%s is not allowed before leaving %s",
1149 			operation, context);
1150 
1151 	diag_print_history(env, &opts);
1152 
1153 	diag_suggestion(env, "%s", suggestion);
1154 }
1155 
1156 void bpf_diag_ctx_required(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
1157 			   enum bpf_diag_context_kind ctx_kind, const char *suggestion)
1158 {
1159 	const char *context = diag_context_name(ctx_kind);
1160 
1161 	bpf_diag_header(env, EXECUTION_CONTEXT_SAFETY, "required context is not active");
1162 	diag_reason(env, "The operation %s requires an active %s, but this path is outside one.",
1163 		    operation, context);
1164 
1165 	diag_section(env, "At");
1166 	bpf_diag_source(env, insn_idx, "error", "%s requires %s", operation, context);
1167 
1168 	diag_suggestion(env, "%s", suggestion);
1169 }
1170 
1171 void bpf_diag_ctx_underflow(struct bpf_verifier_env *env, u32 insn_idx,
1172 			    const char *operation, enum bpf_diag_context_kind ctx_kind,
1173 			    const char *suggestion)
1174 {
1175 	struct bpf_diag_history_opts opts = {
1176 		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
1177 		.ctx_kind = ctx_kind,
1178 	};
1179 	const char *context = diag_context_name(ctx_kind);
1180 
1181 	bpf_diag_header(env, EXECUTION_CONTEXT_SAFETY, "unmatched context exit");
1182 	diag_reason(
1183 		env, "The operation %s tries to leave %s, but this path has no active %s to leave. The current depth is 0.",
1184 		operation, context, context);
1185 
1186 	diag_section(env, "At");
1187 	bpf_diag_source(env, insn_idx, "error", "%s has no matching enter on this path",
1188 			operation);
1189 
1190 	diag_print_history(env, &opts);
1191 
1192 	diag_suggestion(env, "%s", suggestion);
1193 }
1194 
1195 void bpf_diag_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
1196 			    const char *reg_name, const struct bpf_reg_state *reg,
1197 			    enum bpf_diag_invalid_deref_kind kind, s64 offset)
1198 {
1199 	const struct bpf_func_state *frame = diag_current_frame(env);
1200 	struct bpf_diag_history_opts opts = {
1201 		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
1202 		.frame_id = frame->diag_frame_id,
1203 		.frameno = frame->frameno,
1204 		.regno = regno,
1205 	};
1206 	const char *type_name = bpf_diag_reg_type_plain(env, reg->type);
1207 
1208 	bpf_diag_header(env, REGISTER_TYPE_SAFETY, "invalid dereference");
1209 
1210 	switch (kind) {
1211 	case BPF_DIAG_DEREF_SCALAR:
1212 		diag_reason(env, "%s is an integer scalar here, not a pointer to memory.",
1213 			    reg_name);
1214 		break;
1215 	case BPF_DIAG_DEREF_NULLABLE_PTR:
1216 		diag_reason(
1217 			env, "%s may be NULL here (%s). The program could dereference NULL on this path, so the verifier cannot prove this access is safe.",
1218 			reg_name, type_name);
1219 		break;
1220 	case BPF_DIAG_DEREF_MODIFIED_PTR:
1221 		diag_reason(
1222 			env, "%s has offset %lld here, but this pointer type must be dereferenced in its original form.",
1223 			reg_name, offset);
1224 		break;
1225 	case BPF_DIAG_DEREF_INVALID_PTR:
1226 	default:
1227 		diag_reason(
1228 			env, "%s has type %s here, which is not valid for this memory access.",
1229 			reg_name, type_name);
1230 		break;
1231 	}
1232 
1233 	diag_section(env, "At");
1234 	if (kind == BPF_DIAG_DEREF_MODIFIED_PTR)
1235 		bpf_diag_source(env, insn_idx, "error",
1236 				"dereference requires the original %s pointer", type_name);
1237 	else
1238 		bpf_diag_source(env, insn_idx, "error", "invalid dereference of %s (%s)",
1239 				reg_name, type_name);
1240 
1241 	if (regno >= 0)
1242 		diag_print_history(env, &opts);
1243 
1244 	switch (kind) {
1245 	case BPF_DIAG_DEREF_NULLABLE_PTR:
1246 		diag_suggestion(
1247 			env, "Add a NULL check before the access and dereference the pointer only on the non-NULL path.");
1248 		break;
1249 	case BPF_DIAG_DEREF_MODIFIED_PTR:
1250 		diag_suggestion(
1251 			env, "Preserve the original pointer in another register, or use only offsets this pointer type permits before dereferencing it.");
1252 		break;
1253 	case BPF_DIAG_DEREF_SCALAR:
1254 	case BPF_DIAG_DEREF_INVALID_PTR:
1255 	default:
1256 		diag_suggestion(
1257 			env, "Preserve a pointer-valued register where needed, or reload and revalidate the pointer after scalar arithmetic, helper calls, or other operations that can invalidate it.");
1258 		break;
1259 	}
1260 }
1261 
1262 void bpf_diag_unreadable_reg(struct bpf_verifier_env *env, u32 insn_idx, int regno)
1263 {
1264 	const struct bpf_func_state *frame = diag_current_frame(env);
1265 	struct bpf_diag_history_opts opts = {
1266 		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
1267 		.frame_id = frame->diag_frame_id,
1268 		.frameno = frame->frameno,
1269 		.regno = regno,
1270 	};
1271 	const struct bpf_diag_log *log = env->diag ? &env->diag->log : NULL;
1272 	struct bpf_diag_mod_target target;
1273 	bool invalidated = false;
1274 	int i;
1275 
1276 	target = diag_reg_target(opts.frame_id, opts.frameno, regno);
1277 	for (i = log ? log->cnt : 0; i > 0; i--) {
1278 		const struct bpf_diag_history_event *event;
1279 
1280 		event = &log->events[log_pos(log, i - 1)];
1281 
1282 		if (event->kind != BPF_DIAG_HISTORY_MOD ||
1283 		    !diag_target_matches(&event->mod.target, &target))
1284 			continue;
1285 		invalidated = event->mod.new.type == NOT_INIT;
1286 		break;
1287 	}
1288 
1289 	bpf_diag_header(env, REGISTER_TYPE_SAFETY, "unreadable register");
1290 	if (invalidated)
1291 		diag_reason(
1292 			env, "R%d is not readable here. A previous operation invalidated this register, so the verifier cannot use it as an input.",
1293 			regno);
1294 	else if (log && !log->first_seq)
1295 		diag_reason(env,
1296 			    "R%d has never been initialized on this path, so the verifier cannot use it as an input.",
1297 			    regno);
1298 	else
1299 		diag_reason(
1300 			env, "R%d is not readable here. It may never have been initialized, or an earlier operation may have invalidated it.",
1301 			regno);
1302 
1303 	diag_section(env, "At");
1304 	bpf_diag_source(env, insn_idx, "error", "R%d is not readable", regno);
1305 
1306 	if (regno >= 0)
1307 		diag_print_history(env, &opts);
1308 
1309 	if (invalidated)
1310 		diag_suggestion(
1311 			env, "Avoid using the register after it is invalidated, or initialize it again before this instruction.");
1312 	else if (log && !log->first_seq)
1313 		diag_suggestion(env, "Initialize R%d on every path before this instruction.", regno);
1314 	else
1315 		diag_suggestion(
1316 			env, "Initialize the register on every path, or initialize it again after any operation that invalidates it.");
1317 }
1318 
1319 static int diag_stack_argno(u8 slot)
1320 {
1321 	return MAX_BPF_FUNC_REG_ARGS + slot + 1;
1322 }
1323 
1324 static void diag_format_stack_arg(char *buf, size_t size, u8 slot, const char *arg_name)
1325 {
1326 	int argno = diag_stack_argno(slot);
1327 	const char *ordinal = diag_arg_ordinal(argno);
1328 
1329 	if (ordinal && arg_name)
1330 		scnprintf(buf, size, "outgoing stack argument %u (%s argument, %s)", slot + 1,
1331 			  ordinal, arg_name);
1332 	else if (ordinal)
1333 		scnprintf(buf, size, "outgoing stack argument %u (%s argument)", slot + 1, ordinal);
1334 	else if (arg_name)
1335 		scnprintf(buf, size, "outgoing stack argument %u (%s)", slot + 1, arg_name);
1336 	else
1337 		scnprintf(buf, size, "outgoing stack argument %u", slot + 1);
1338 }
1339 
1340 void bpf_diag_stack_arg_uninit(struct bpf_verifier_env *env, u32 insn_idx, int nargs,
1341 			       int stack_arg_slot, const char *callee_name,
1342 			       const char *arg_name)
1343 {
1344 	const struct bpf_func_state *frame = diag_current_frame(env);
1345 	struct bpf_diag_history_opts opts = {
1346 		.scope = BPF_DIAG_HISTORY_SCOPE_STACK_ARG,
1347 		.frame_id = frame->diag_frame_id,
1348 		.frameno = frame->frameno,
1349 		.stack_arg_slot = stack_arg_slot,
1350 	};
1351 	const char *arg_buf;
1352 
1353 	arg_buf = bpf_diag_fmt_buf(env, BPF_DIAG_FMT_BUF_SIZE);
1354 	if (arg_buf)
1355 		diag_format_stack_arg((char *)arg_buf, BPF_DIAG_FMT_BUF_SIZE, stack_arg_slot,
1356 				      arg_name);
1357 	else
1358 		arg_buf = "";
1359 	bpf_diag_header(env, REGISTER_TYPE_SAFETY, "missing stack argument");
1360 	if (callee_name && *callee_name)
1361 		diag_reason(
1362 			env, "Function %s expects %d arguments, but %s is not initialized at this call.",
1363 			callee_name, nargs, arg_buf);
1364 	else
1365 		diag_reason(
1366 			env, "The callee expects %d arguments, but %s is not initialized at this call.",
1367 			nargs, arg_buf);
1368 
1369 	diag_section(env, "At");
1370 	bpf_diag_source(env, insn_idx, "error", "%s is not initialized", arg_buf);
1371 
1372 	if (stack_arg_slot >= 0)
1373 		diag_print_history(env, &opts);
1374 
1375 	diag_suggestion(
1376 		env, "Write the outgoing stack argument after any operation that may invalidate stored pointer values, and before making this call.");
1377 }
1378 
1379 void bpf_diag_memory(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
1380 		     const char *reason, const char *suggestion)
1381 {
1382 	bpf_diag_header(env, MEMORY_SAFETY, problem);
1383 	diag_reason(env, "%s", reason);
1384 
1385 	diag_section(env, "At");
1386 	bpf_diag_source(env, insn_idx, "error", "%s", problem);
1387 
1388 	diag_suggestion(env, "%s", suggestion);
1389 }
1390 
1391 void bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true)
1392 {
1393 	struct bpf_diag_history_event event = {
1394 		.insn_idx = insn_idx,
1395 		.kind = BPF_DIAG_HISTORY_BRANCH,
1396 		.branch = {
1397 			.cond_true = cond_true,
1398 		},
1399 	};
1400 
1401 	diag_append_history(env, &event);
1402 }
1403 
1404 static void diag_snapshot_reg(struct bpf_diag_reg_snapshot *snapshot,
1405 			      const struct bpf_reg_state *reg)
1406 {
1407 	snapshot->type = reg->type;
1408 	if (type_is_map_ptr(reg->type))
1409 		snapshot->map_ptr = reg->map_ptr;
1410 	if (base_type(reg->type) == PTR_TO_BTF_ID && reg->btf && reg->btf_id) {
1411 		snapshot->btf_id = reg->btf_id;
1412 		snapshot->btf = reg->btf;
1413 	}
1414 	snapshot->var_off = reg->var_off;
1415 	snapshot->r64 = reg->r64;
1416 }
1417 
1418 static bool diag_mod_insn_origin(struct bpf_verifier_env *env, u32 insn_idx,
1419 				 const struct bpf_diag_mod_target *target,
1420 				 struct bpf_diag_mod_target *origin)
1421 {
1422 	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
1423 	u8 class = BPF_CLASS(insn->code);
1424 	const struct bpf_func_state *state;
1425 
1426 	if (target->kind == BPF_DIAG_MOD_TARGET_REG && (class == BPF_ALU || class == BPF_ALU64) &&
1427 	    BPF_OP(insn->code) == BPF_MOV && BPF_SRC(insn->code) == BPF_X) {
1428 		*origin = diag_reg_target(target->frame_id, target->frameno, insn->src_reg);
1429 		return true;
1430 	}
1431 
1432 	if ((target->kind != BPF_DIAG_MOD_TARGET_STACK_ARG &&
1433 	     target->kind != BPF_DIAG_MOD_TARGET_STACK_SLOT) ||
1434 	    class != BPF_STX)
1435 		return false;
1436 
1437 	state = env->cur_state->frame[env->cur_state->curframe];
1438 	*origin = diag_reg_target(state->diag_frame_id, state->frameno, insn->src_reg);
1439 	return true;
1440 }
1441 
1442 static bool diag_mod_keeps_lineage(struct bpf_verifier_env *env,
1443 				   const struct bpf_diag_history_event *event)
1444 {
1445 	const struct bpf_insn *insn;
1446 	u8 class;
1447 
1448 	if (event->mod.reason != BPF_DIAG_MOD_WRITE ||
1449 	    event->mod.target.kind != BPF_DIAG_MOD_TARGET_REG)
1450 		return false;
1451 
1452 	insn = &env->prog->insnsi[event->insn_idx];
1453 	class = BPF_CLASS(insn->code);
1454 	if (class != BPF_ALU && class != BPF_ALU64)
1455 		return false;
1456 
1457 	switch (BPF_OP(insn->code)) {
1458 	case BPF_ADD:
1459 	case BPF_SUB:
1460 	case BPF_MUL:
1461 	case BPF_OR:
1462 	case BPF_AND:
1463 	case BPF_LSH:
1464 	case BPF_RSH:
1465 	case BPF_ARSH:
1466 	case BPF_XOR:
1467 	case BPF_NEG:
1468 	case BPF_END:
1469 		return true;
1470 	default:
1471 		return false;
1472 	}
1473 }
1474 
1475 static void diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
1476 			    struct bpf_diag_mod_target target,
1477 			    enum bpf_diag_mod_reason reason,
1478 			    const struct bpf_reg_state *old_reg,
1479 			    const struct bpf_reg_state *new_reg,
1480 			    const struct bpf_diag_mod_target *origin)
1481 {
1482 	struct bpf_diag_history_event event = {
1483 		.insn_idx = insn_idx,
1484 		.kind = BPF_DIAG_HISTORY_MOD,
1485 		.mod = {
1486 			.target = target,
1487 			.reason = reason,
1488 		},
1489 	};
1490 
1491 	if (old_reg)
1492 		diag_snapshot_reg(&event.mod.old, old_reg);
1493 	if (new_reg)
1494 		diag_snapshot_reg(&event.mod.new, new_reg);
1495 	if (origin) {
1496 		event.mod.origin = *origin;
1497 		event.mod.origin_valid = true;
1498 	} else if (diag_mod_insn_origin(env, insn_idx, &target, &event.mod.origin)) {
1499 		event.mod.origin_valid = true;
1500 	}
1501 	if (old_reg && new_reg &&
1502 	    (reason == BPF_DIAG_MOD_WRITE || reason == BPF_DIAG_MOD_SPILL) &&
1503 	    !memcmp(&event.mod.old, &event.mod.new, sizeof(event.mod.old)) &&
1504 	    !event.mod.origin_valid &&
1505 	    diag_mod_keeps_lineage(env, &event))
1506 		return;
1507 
1508 	diag_append_history(env, &event);
1509 }
1510 
1511 static struct bpf_reg_state *target_to_reg(struct bpf_verifier_env *env,
1512 					   const struct bpf_diag_mod_target *target)
1513 {
1514 	struct bpf_verifier_state *vstate = env->cur_state;
1515 	struct bpf_func_state *state;
1516 
1517 	state = target->frameno <= vstate->curframe ? vstate->frame[target->frameno] : NULL;
1518 
1519 	if (!state)
1520 		return NULL;
1521 	if (state->diag_frame_id != target->frame_id)
1522 		return NULL;
1523 
1524 	switch (target->kind) {
1525 	case BPF_DIAG_MOD_TARGET_REG:
1526 		if (target->regno >= MAX_BPF_REG)
1527 			return NULL;
1528 		return &state->regs[target->regno];
1529 	case BPF_DIAG_MOD_TARGET_STACK_ARG:
1530 		if (target->stack_arg >= state->out_stack_arg_cnt)
1531 			return NULL;
1532 		return &state->stack_arg_regs[target->stack_arg];
1533 	case BPF_DIAG_MOD_TARGET_STACK_SLOT:
1534 		if (target->spi >= state->allocated_stack / BPF_REG_SIZE)
1535 			return NULL;
1536 		return &state->stack[target->spi].spilled_ptr;
1537 	default:
1538 		return NULL;
1539 	}
1540 }
1541 
1542 static bool reg_to_target(struct bpf_verifier_env *env, const struct bpf_reg_state *reg,
1543 			  struct bpf_diag_mod_target *target)
1544 {
1545 	struct bpf_verifier_state *vstate = env->cur_state;
1546 	unsigned long addr = (unsigned long)reg;
1547 	int frame;
1548 
1549 	for (frame = 0; frame <= vstate->curframe; frame++) {
1550 		struct bpf_func_state *state = vstate->frame[frame];
1551 		unsigned long start, end;
1552 		u32 nslots = state->allocated_stack / BPF_REG_SIZE;
1553 		int spi;
1554 
1555 		start = (unsigned long)state->regs;
1556 		end = (unsigned long)(state->regs + MAX_BPF_REG);
1557 		if (addr >= start && addr < end) {
1558 			*target = diag_reg_target(state->diag_frame_id, state->frameno,
1559 						  reg - state->regs);
1560 			return true;
1561 		}
1562 
1563 		start = (unsigned long)state->stack_arg_regs;
1564 		end = (unsigned long)(state->stack_arg_regs + state->out_stack_arg_cnt);
1565 		if (state->out_stack_arg_cnt && addr >= start && addr < end) {
1566 			*target = diag_stack_arg_target(state->diag_frame_id, state->frameno,
1567 							reg - state->stack_arg_regs);
1568 			return true;
1569 		}
1570 
1571 		start = (unsigned long)state->stack;
1572 		end = (unsigned long)(state->stack + nslots);
1573 		if (nslots && addr >= start && addr < end) {
1574 			spi = ((const char *)reg - (const char *)state->stack) /
1575 			      sizeof(*state->stack);
1576 			*target = diag_stack_slot_target(state->diag_frame_id, state->frameno, spi);
1577 			return true;
1578 		}
1579 	}
1580 	return false;
1581 }
1582 
1583 void bpf_diag_mod_begin(struct bpf_verifier_env *env, const struct bpf_reg_state *reg,
1584 			const struct bpf_reg_state *origin, enum bpf_diag_mod_reason reason)
1585 {
1586 	struct bpf_diag *diag = env->diag;
1587 
1588 	if (!diag)
1589 		return;
1590 	diag->mod.active = reg_to_target(env, reg, &diag->mod.target);
1591 	if (!diag->mod.active)
1592 		return;
1593 	diag->mod.target_reg_snapshot = *reg;
1594 	diag->mod.insn_idx = env->insn_idx;
1595 	diag->mod.reason = reason;
1596 	diag->mod.origin_valid = origin && reg_to_target(env, origin, &diag->mod.origin);
1597 }
1598 
1599 void bpf_diag_mod_end(struct bpf_verifier_env *env)
1600 {
1601 	struct bpf_diag *diag = env->diag;
1602 	const struct bpf_reg_state *new_reg;
1603 
1604 	if (!diag || !diag->mod.active)
1605 		return;
1606 	diag->mod.active = false;
1607 	/*
1608 	 * Resolve the target again because the enclosing function state's stack
1609 	 * may have been reallocated while the modification was in progress.
1610 	 */
1611 	new_reg = target_to_reg(env, &diag->mod.target);
1612 	if (!new_reg)
1613 		return;
1614 	diag_record_mod(env, diag->mod.insn_idx, diag->mod.target, diag->mod.reason,
1615 			&diag->mod.target_reg_snapshot, new_reg,
1616 			diag->mod.origin_valid ? &diag->mod.origin : NULL);
1617 }
1618 
1619 void bpf_diag_record_scrub(struct bpf_verifier_env *env, const struct bpf_reg_state *reg,
1620 			   enum bpf_diag_mod_reason reason)
1621 {
1622 	struct bpf_diag_mod_target target;
1623 
1624 	if (!env->diag || reg->type == NOT_INIT || !reg_to_target(env, reg, &target))
1625 		return;
1626 	diag_record_mod(env, env->insn_idx, target, reason, reg, NULL, NULL);
1627 }
1628 
1629 void bpf_diag_record_scrub_stack(struct bpf_verifier_env *env,
1630 				 const struct bpf_func_state *state, s16 min_off, s16 max_off,
1631 				 enum bpf_diag_mod_reason reason)
1632 {
1633 	diag_record_mod(env, env->insn_idx,
1634 			diag_stack_range_target(state->diag_frame_id, state->frameno, min_off, max_off),
1635 			reason, NULL, NULL, NULL);
1636 }
1637 
1638 static void diag_record_ref(struct bpf_verifier_env *env, u32 insn_idx, u8 kind, u32 ref_id)
1639 {
1640 	struct bpf_diag_history_event event = {
1641 		.insn_idx = insn_idx,
1642 		.kind = kind,
1643 		.ref = {
1644 			.ref_id = ref_id,
1645 		},
1646 	};
1647 
1648 	diag_append_history(env, &event);
1649 }
1650 
1651 void bpf_diag_record_ref_acquire(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id)
1652 {
1653 	diag_record_ref(env, insn_idx, BPF_DIAG_HISTORY_REF_ACQUIRE, ref_id);
1654 }
1655 
1656 void bpf_diag_record_ref_release(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id)
1657 {
1658 	diag_record_ref(env, insn_idx, BPF_DIAG_HISTORY_REF_RELEASE, ref_id);
1659 }
1660 
1661 void bpf_diag_record_context(struct bpf_verifier_env *env, u32 insn_idx,
1662 			     enum bpf_diag_context_kind ctx_kind, bool enter, u32 depth)
1663 {
1664 	/*
1665 	 * Keep leave events so context rendering can stop at a depth-zero exit
1666 	 * and show nested-region depth accurately for the active path.
1667 	 */
1668 	struct bpf_diag_history_event event = {
1669 		.insn_idx = insn_idx,
1670 		.kind = BPF_DIAG_HISTORY_CONTEXT,
1671 		.ctx = {
1672 			.kind = ctx_kind,
1673 			.enter = enter,
1674 			.depth = depth,
1675 		},
1676 	};
1677 
1678 	diag_append_history(env, &event);
1679 }
1680 
1681 static int diag_history_context_start_idx(const struct bpf_diag_log *log,
1682 					  const struct bpf_diag_history_opts *opts)
1683 {
1684 	int i;
1685 
1686 	if (!opts->ctx_depth)
1687 		return 0;
1688 
1689 	/* Find the most recent outermost entry, or a depth-zero exit. */
1690 	for (i = log->cnt; i > 0; i--) {
1691 		const struct bpf_diag_history_event *event;
1692 
1693 		event = &log->events[log_pos(log, i - 1)];
1694 
1695 		if (event->kind != BPF_DIAG_HISTORY_CONTEXT || event->ctx.kind != opts->ctx_kind)
1696 			continue;
1697 
1698 		if (event->ctx.enter && event->ctx.depth == 1)
1699 			return i - 1;
1700 		if (!event->ctx.enter && event->ctx.depth == 0)
1701 			return 0;
1702 	}
1703 
1704 	return 0;
1705 }
1706 
1707 struct bpf_diag_history_filter {
1708 	const struct bpf_diag_history_opts *opts;
1709 	u32 lineage_start;
1710 	bool lineage_valid;
1711 };
1712 
1713 static bool diag_target_matches(const struct bpf_diag_mod_target *event_target,
1714 				const struct bpf_diag_mod_target *target)
1715 {
1716 	int slot_off;
1717 
1718 	if (event_target->frame_id != target->frame_id || event_target->frameno != target->frameno)
1719 		return false;
1720 
1721 	if (event_target->kind == BPF_DIAG_MOD_TARGET_STACK_RANGE &&
1722 	    target->kind == BPF_DIAG_MOD_TARGET_STACK_SLOT) {
1723 		slot_off = -(target->spi + 1) * BPF_REG_SIZE;
1724 		return event_target->range.min_off < slot_off + BPF_REG_SIZE &&
1725 		       event_target->range.max_off > slot_off;
1726 	}
1727 
1728 	if (event_target->kind != target->kind)
1729 		return false;
1730 
1731 	switch (target->kind) {
1732 	case BPF_DIAG_MOD_TARGET_REG:
1733 		return event_target->regno == target->regno;
1734 	case BPF_DIAG_MOD_TARGET_STACK_ARG:
1735 		return event_target->stack_arg == target->stack_arg;
1736 	case BPF_DIAG_MOD_TARGET_STACK_SLOT:
1737 		return event_target->spi == target->spi;
1738 	default:
1739 		return false;
1740 	}
1741 }
1742 
1743 static void diag_build_lineage(struct bpf_verifier_env *env, struct bpf_diag_log *log,
1744 			       struct bpf_diag_history_filter *filter)
1745 {
1746 	const struct bpf_diag_history_opts *opts = filter->opts;
1747 	struct bpf_diag_mod_target target;
1748 	int i;
1749 
1750 	for (i = 0; i < log->cnt; i++)
1751 		log->events[log_pos(log, i)].in_lineage = false;
1752 
1753 	if (opts->scope == BPF_DIAG_HISTORY_SCOPE_REG)
1754 		target = diag_reg_target(opts->frame_id, opts->frameno, opts->regno);
1755 	else if (opts->scope == BPF_DIAG_HISTORY_SCOPE_STACK_ARG)
1756 		target = diag_stack_arg_target(opts->frame_id, opts->frameno,
1757 					       opts->stack_arg_slot);
1758 	else
1759 		return;
1760 
1761 	/*
1762 	 * Find the nearest mutation of the active target. A fill or spill changes
1763 	 * the target to its origin, so the same walk follows register/stack
1764 	 * lineage recursively until it reaches the write that created the value.
1765 	 */
1766 	for (i = log->cnt; i > 0; i--) {
1767 		struct bpf_diag_history_event *event;
1768 
1769 		event = &log->events[log_pos(log, i - 1)];
1770 		if (event->kind != BPF_DIAG_HISTORY_MOD ||
1771 		    !diag_target_matches(&event->mod.target, &target))
1772 			continue;
1773 
1774 		event->in_lineage = true;
1775 		filter->lineage_start = i - 1;
1776 		filter->lineage_valid = true;
1777 
1778 		if (event->mod.origin_valid) {
1779 			target = event->mod.origin;
1780 			continue;
1781 		}
1782 		if (event->mod.reason != BPF_DIAG_MOD_WRITE &&
1783 		    event->mod.reason != BPF_DIAG_MOD_SPILL)
1784 			continue;
1785 		if (diag_mod_keeps_lineage(env, event))
1786 			continue;
1787 		break;
1788 	}
1789 }
1790 
1791 static int diag_history_start_idx(const struct bpf_diag_log *log,
1792 				  const struct bpf_diag_history_filter *filter)
1793 {
1794 	const struct bpf_diag_history_opts *opts = filter->opts;
1795 	int i;
1796 
1797 	if (opts->scope == BPF_DIAG_HISTORY_SCOPE_CONTEXT)
1798 		return diag_history_context_start_idx(log, opts);
1799 	if (filter->lineage_valid)
1800 		return filter->lineage_start;
1801 	if (opts->scope != BPF_DIAG_HISTORY_SCOPE_REF)
1802 		return 0;
1803 
1804 	for (i = log->cnt; i > 0; i--) {
1805 		const struct bpf_diag_history_event *event;
1806 
1807 		event = &log->events[log_pos(log, i - 1)];
1808 		if (event->kind == BPF_DIAG_HISTORY_REF_ACQUIRE &&
1809 		    event->ref.ref_id == opts->ref_id)
1810 			return i - 1;
1811 	}
1812 
1813 	return 0;
1814 }
1815 
1816 static bool diag_history_event_visible(const struct bpf_diag_history_event *event,
1817 				       const struct bpf_diag_history_filter *filter)
1818 {
1819 	const struct bpf_diag_history_opts *opts = filter->opts;
1820 
1821 	switch (event->kind) {
1822 	case BPF_DIAG_HISTORY_BRANCH:
1823 		return true;
1824 	case BPF_DIAG_HISTORY_MOD:
1825 		return filter->lineage_valid && event->in_lineage;
1826 	case BPF_DIAG_HISTORY_REF_ACQUIRE:
1827 	case BPF_DIAG_HISTORY_REF_RELEASE:
1828 		return opts->scope == BPF_DIAG_HISTORY_SCOPE_REF &&
1829 		       event->ref.ref_id == opts->ref_id;
1830 	case BPF_DIAG_HISTORY_CONTEXT:
1831 		return opts->scope == BPF_DIAG_HISTORY_SCOPE_CONTEXT &&
1832 		       event->ctx.kind == opts->ctx_kind;
1833 	default:
1834 		return false;
1835 	}
1836 }
1837 
1838 static const char *diag_s64_bound_name(s64 value)
1839 {
1840 	if (value == S64_MIN)
1841 		return "S64_MIN";
1842 	if (value == S64_MAX)
1843 		return "S64_MAX";
1844 	return NULL;
1845 }
1846 
1847 static const char *diag_u64_bound_name(u64 value)
1848 {
1849 	if (value == U64_MAX)
1850 		return "U64_MAX";
1851 	return NULL;
1852 }
1853 
1854 static const char *diag_s64_str(struct bpf_verifier_env *env, s64 value)
1855 {
1856 	return diag_s64_bound_name(value) ?: bpf_diag_fmt(env, "%lld", value);
1857 }
1858 
1859 static const char *diag_u64_str(struct bpf_verifier_env *env, u64 value)
1860 {
1861 	return diag_u64_bound_name(value) ?: bpf_diag_fmt(env, "%llu", value);
1862 }
1863 
1864 static bool diag_cnum64_unknown(struct cnum64 range)
1865 {
1866 	return cnum64_smin(range) == S64_MIN && cnum64_smax(range) == S64_MAX &&
1867 	       cnum64_umin(range) == 0 && cnum64_umax(range) == U64_MAX;
1868 }
1869 
1870 static bool diag_snapshot_unknown(const struct bpf_diag_reg_snapshot *snapshot)
1871 {
1872 	return tnum_is_unknown(snapshot->var_off) && diag_cnum64_unknown(snapshot->r64);
1873 }
1874 
1875 static const char *diag_scalar_range(struct bpf_verifier_env *env, struct cnum64 range)
1876 {
1877 	return bpf_diag_fmt(env, "signed range [%s, %s], unsigned range [%s, %s]",
1878 			    diag_s64_str(env, cnum64_smin(range)),
1879 			    diag_s64_str(env, cnum64_smax(range)),
1880 			    diag_u64_str(env, cnum64_umin(range)),
1881 			    diag_u64_str(env, cnum64_umax(range)));
1882 }
1883 
1884 const char *bpf_diag_fmt_s64_sum(struct bpf_verifier_env *env, s64 value, int addend)
1885 {
1886 	s64 sum;
1887 
1888 	if (check_add_overflow(value, (s64)addend, &sum))
1889 		return bpf_diag_fmt(env, "%lld plus %d (%s)", value, addend,
1890 				    addend < 0 ? "below S64_MIN" : "above S64_MAX");
1891 
1892 	return bpf_diag_fmt(env, "%lld", sum);
1893 }
1894 
1895 static const char *diag_access_offset(struct bpf_verifier_env *env, int off,
1896 				      const struct bpf_reg_state *reg)
1897 {
1898 	if (tnum_is_const(reg->var_off))
1899 		return bpf_diag_fmt(env, "constant %s",
1900 				    bpf_diag_fmt_s64_sum(env, (s64)reg->var_off.value, off));
1901 
1902 	if (tnum_is_unknown(reg->var_off) && diag_cnum64_unknown(reg->r64))
1903 		return bpf_diag_fmt(env, "unbounded");
1904 
1905 	if (off)
1906 		return bpf_diag_fmt(env,
1907 			"variable: known bits %#llx, unknown mask %#llx, plus fixed offset %d; %s",
1908 			(u64)reg->var_off.value, reg->var_off.mask, off,
1909 			diag_scalar_range(env, reg->r64));
1910 	return bpf_diag_fmt(env, "variable: known bits %#llx, unknown mask %#llx; %s",
1911 			    (u64)reg->var_off.value, reg->var_off.mask,
1912 			    diag_scalar_range(env, reg->r64));
1913 }
1914 
1915 void bpf_diag_mem_bounds(struct bpf_verifier_env *env, u32 insn_idx, int regno,
1916 			 const char *reg_name, const char *type_name, const char *proof,
1917 			 int off, int size, u32 mem_size, const struct bpf_reg_state *reg)
1918 {
1919 	const struct bpf_func_state *frame = diag_current_frame(env);
1920 	struct bpf_diag_history_opts opts = {
1921 		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
1922 		.frame_id = frame->diag_frame_id,
1923 		.frameno = frame->frameno,
1924 		.regno = regno,
1925 	};
1926 	const char *offset_desc;
1927 
1928 	if (!bpf_diag_enabled(env))
1929 		return;
1930 
1931 	offset_desc = diag_access_offset(env, off, reg);
1932 
1933 	bpf_diag_header(env, MEMORY_SAFETY, "access outside bounds");
1934 	diag_reason(
1935 		env, "The verifier cannot prove offset + access_size <= object_size. Here, %s. %s is %s; offset is %s; access_size is %d; object_size is %u.",
1936 		proof, reg_name, type_name, offset_desc, size, mem_size);
1937 
1938 	diag_section(env, "At");
1939 	bpf_diag_source(env, insn_idx, "error", "access may be outside object bounds");
1940 
1941 	if (regno >= 0)
1942 		diag_print_history(env, &opts);
1943 
1944 	diag_suggestion(
1945 		env, "Add or adjust a bounds check that proves offset + access_size stays within the object.");
1946 }
1947 
1948 static const char *diag_lock_name(const struct bpf_reference_state *lock)
1949 {
1950 	switch (lock->type) {
1951 	case REF_TYPE_LOCK:
1952 		return "bpf_spin_lock";
1953 	case REF_TYPE_RES_LOCK:
1954 		return "resource spin lock";
1955 	case REF_TYPE_RES_LOCK_IRQ:
1956 		return "IRQ-saving resource spin lock";
1957 	default:
1958 		return "lock";
1959 	}
1960 }
1961 
1962 static void diag_res_report(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
1963 			    const char *reason)
1964 {
1965 	bpf_diag_header(env, RESOURCE_LIFETIME_SAFETY, problem);
1966 	diag_reason(env, "%s", reason);
1967 
1968 	diag_section(env, "At");
1969 	bpf_diag_source(env, insn_idx, "error", "%s", problem);
1970 }
1971 
1972 void bpf_diag_res(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
1973 		  const char *reason, const char *suggestion)
1974 {
1975 	diag_res_report(env, insn_idx, problem, reason);
1976 	diag_suggestion(env, "%s", suggestion);
1977 }
1978 
1979 void bpf_diag_lock(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
1980 		   const char *reason, const char *suggestion,
1981 		   const struct bpf_reference_state *active_lock)
1982 {
1983 	diag_res_report(env, insn_idx, problem, reason);
1984 
1985 	if (active_lock) {
1986 		diag_section(env, "Active lock");
1987 		bpf_diag_source(env, active_lock->insn_idx, "acquired",
1988 				"active %s has verifier identity %d",
1989 				diag_lock_name(active_lock), active_lock->id);
1990 	}
1991 
1992 	diag_suggestion(env, "%s", suggestion);
1993 }
1994 
1995 void bpf_diag_irq(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
1996 		  const char *reason, const char *suggestion, u32 depth)
1997 {
1998 	struct bpf_diag_history_opts opts = {
1999 		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
2000 		.ctx_kind = BPF_DIAG_CONTEXT_IRQ,
2001 		.ctx_depth = depth,
2002 	};
2003 
2004 	bpf_diag_header(env, RESOURCE_LIFETIME_SAFETY, problem);
2005 	diag_reason(env, "%s", reason);
2006 
2007 	diag_section(env, "At");
2008 	bpf_diag_source(env, insn_idx, "error", "%s", problem);
2009 
2010 	if (depth)
2011 		diag_print_history(env, &opts);
2012 
2013 	diag_suggestion(env, "%s", suggestion);
2014 }
2015 
2016 void bpf_diag_leak(struct bpf_verifier_env *env, u32 ref_id, u32 alloc_insn, u32 fail_insn)
2017 {
2018 	struct bpf_diag_history_opts opts = {
2019 		.scope = BPF_DIAG_HISTORY_SCOPE_REF,
2020 		.ref_id = ref_id,
2021 	};
2022 
2023 	bpf_diag_header(env, RESOURCE_LIFETIME_SAFETY, "unreleased resource");
2024 	diag_reason(
2025 		env, "Owned resource (id=%u) was acquired at instruction %u and still needs to be released before this exit path.",
2026 		ref_id, alloc_insn);
2027 
2028 	diag_section(env, "At");
2029 	bpf_diag_source(env, fail_insn, "error",
2030 			"owned resource (id=%u) still needs release", ref_id);
2031 
2032 	diag_print_history(env, &opts);
2033 
2034 	diag_suggestion(
2035 		env, "Release or transfer ownership of the acquired resource on every path before the program exits.");
2036 }
2037 
2038 static const char *diag_var_offset(struct bpf_verifier_env *env,
2039 				   const struct bpf_diag_reg_snapshot *snapshot)
2040 {
2041 	if (tnum_is_const(snapshot->var_off))
2042 		return bpf_diag_fmt(env, "at offset %lld", (s64)snapshot->var_off.value);
2043 
2044 	if (diag_snapshot_unknown(snapshot))
2045 		return bpf_diag_fmt(env, "with unknown offset");
2046 
2047 	return bpf_diag_fmt(env,
2048 			    "with variable offset: known bits %#llx, unknown mask %#llx, %s",
2049 			    snapshot->var_off.value, snapshot->var_off.mask,
2050 			    diag_scalar_range(env, snapshot->r64));
2051 }
2052 
2053 static const char *diag_reg_map_name(const struct bpf_map *map)
2054 {
2055 	if (!map || !map->name[0])
2056 		return NULL;
2057 
2058 	return map->name;
2059 }
2060 
2061 static const char *diag_reg_snapshot(struct bpf_verifier_env *env,
2062 				     const struct bpf_diag_reg_snapshot *snapshot)
2063 {
2064 	const char *type_name = reg_type_str(env, snapshot->type);
2065 	const char *offset = diag_var_offset(env, snapshot);
2066 	const char *btf = snapshot->btf && snapshot->btf_id ?
2067 			  bpf_diag_fmt_btf_type(env, snapshot->btf, snapshot->btf_id) : NULL;
2068 	const char *map_name;
2069 
2070 	if (snapshot->type == SCALAR_VALUE) {
2071 		if (tnum_is_const(snapshot->var_off))
2072 			return bpf_diag_fmt(env, "integer scalar value %lld",
2073 					    (s64)snapshot->var_off.value);
2074 		if (diag_snapshot_unknown(snapshot))
2075 			return bpf_diag_fmt(env, "integer scalar with unknown value");
2076 		if (cnum64_is_const(snapshot->r64))
2077 			return bpf_diag_fmt(env, "integer scalar value %lld",
2078 					    cnum64_smin(snapshot->r64));
2079 		return bpf_diag_fmt(env, "integer scalar with %s",
2080 				    diag_scalar_range(env, snapshot->r64));
2081 	}
2082 
2083 	if (snapshot->type == NOT_INIT)
2084 		return bpf_diag_fmt(env, "uninitialized value");
2085 
2086 	if (base_type(snapshot->type) == PTR_TO_CTX)
2087 		return bpf_diag_fmt(env, "context pointer %s", offset);
2088 
2089 	if (base_type(snapshot->type) == PTR_TO_STACK)
2090 		return bpf_diag_fmt(env, "stack pointer %s", offset);
2091 
2092 	if (base_type(snapshot->type) == PTR_TO_MAP_VALUE) {
2093 		const char *kind = type_may_be_null(snapshot->type) ? "nullable map value" :
2094 								      "map value";
2095 
2096 		map_name = diag_reg_map_name(snapshot->map_ptr);
2097 		if (map_name)
2098 			return bpf_diag_fmt(env, "%s from %s %s", kind, map_name, offset);
2099 		return bpf_diag_fmt(env, "%s %s", kind, offset);
2100 	}
2101 
2102 	if (base_type(snapshot->type) == CONST_PTR_TO_MAP) {
2103 		map_name = diag_reg_map_name(snapshot->map_ptr);
2104 		if (map_name)
2105 			return bpf_diag_fmt(env, "map pointer for map %s", map_name);
2106 		return bpf_diag_fmt(env, "map pointer");
2107 	}
2108 
2109 	if (type_is_non_owning_ref(snapshot->type)) {
2110 		if (btf)
2111 			return bpf_diag_fmt(env, "borrowed allocated object pointer type=%s", btf);
2112 		return bpf_diag_fmt(env, "borrowed allocated object pointer");
2113 	}
2114 
2115 	if (type_is_ptr_alloc_obj(snapshot->type)) {
2116 		if (btf)
2117 			return bpf_diag_fmt(env, "owned allocated object pointer type=%s", btf);
2118 		return bpf_diag_fmt(env, "owned allocated object pointer");
2119 	}
2120 
2121 	if (base_type(snapshot->type) == PTR_TO_BTF_ID && btf)
2122 		return bpf_diag_fmt(env, "%s type=%s %s", type_name, btf, offset);
2123 
2124 	return bpf_diag_fmt(env, "%s %s", type_name, offset);
2125 }
2126 
2127 static const char *diag_mod_target_desc(struct bpf_verifier_env *env,
2128 					const struct bpf_diag_mod_target *target)
2129 {
2130 	switch (target->kind) {
2131 	case BPF_DIAG_MOD_TARGET_REG:
2132 		return bpf_diag_fmt(env, "R%u", target->regno);
2133 	case BPF_DIAG_MOD_TARGET_STACK_ARG:
2134 		return bpf_diag_fmt(env, "stack arg%d", diag_stack_argno(target->stack_arg));
2135 	case BPF_DIAG_MOD_TARGET_STACK_SLOT:
2136 		return bpf_diag_fmt(env, "stack slot fp%d", -(target->spi + 1) * BPF_REG_SIZE);
2137 	default:
2138 		return "value";
2139 	}
2140 }
2141 
2142 static void diag_print_mod(struct bpf_verifier_env *env, const struct bpf_diag_history_event *event)
2143 {
2144 	const struct bpf_diag_mod_target *target = &event->mod.target;
2145 	const char *target_desc, *reason = NULL, *old, *new;
2146 	const char *label = "update";
2147 
2148 	if (target->kind == BPF_DIAG_MOD_TARGET_STACK_RANGE) {
2149 		bpf_diag_source(
2150 			env, event->insn_idx, "invalidated",
2151 			"variable-offset stack write may affect bytes fp%d through fp%d",
2152 			target->range.min_off, target->range.max_off - 1);
2153 		return;
2154 	}
2155 
2156 	old = diag_reg_snapshot(env, &event->mod.old);
2157 	new = diag_reg_snapshot(env, &event->mod.new);
2158 	target_desc = diag_mod_target_desc(env, target);
2159 
2160 	switch (event->mod.reason) {
2161 	case BPF_DIAG_MOD_REF_RELEASE:
2162 		reason = target->kind == BPF_DIAG_MOD_TARGET_REG ? "resource release invalidated "
2163 								   "this pointer" :
2164 								   "resource release invalidated "
2165 								   "this value";
2166 		break;
2167 	case BPF_DIAG_MOD_PKT_DATA_CHANGE:
2168 		reason = "packet data may have moved";
2169 		break;
2170 	case BPF_DIAG_MOD_NON_OWN_REF:
2171 		reason = "leaving the protected region invalidated this borrowed pointer";
2172 		break;
2173 	case BPF_DIAG_MOD_CALLER_SAVED:
2174 		reason = target->kind == BPF_DIAG_MOD_TARGET_STACK_ARG ?
2175 			 "call invalidated this outgoing stack argument" :
2176 			 "call invalidated this caller-saved register";
2177 		break;
2178 	case BPF_DIAG_MOD_WRITE:
2179 		if (target->kind == BPF_DIAG_MOD_TARGET_STACK_SLOT)
2180 			reason = "a later stack write overwrote this spilled value";
2181 		break;
2182 	case BPF_DIAG_MOD_SPILL:
2183 		label = "spilled";
2184 		break;
2185 	case BPF_DIAG_MOD_VAR_WRITE:
2186 	default:
2187 		break;
2188 	}
2189 
2190 	if (reason) {
2191 		bpf_diag_source(env, event->insn_idx, "invalidated",
2192 				"%s: %s; previous value was %s", target_desc, reason, old);
2193 		return;
2194 	}
2195 
2196 	bpf_diag_source(env, event->insn_idx, label, "%s changed from %s to %s", target_desc,
2197 			old, new);
2198 }
2199 
2200 static void diag_print_ref_event(struct bpf_verifier_env *env,
2201 				 const struct bpf_diag_history_event *event)
2202 {
2203 	const char *label;
2204 
2205 	label = event->kind == BPF_DIAG_HISTORY_REF_ACQUIRE ? "acquired" : "released";
2206 	bpf_diag_source(env, event->insn_idx, label, "owned resource (id=%u)",
2207 			event->ref.ref_id);
2208 }
2209 
2210 static const char *diag_context_name(enum bpf_diag_context_kind kind)
2211 {
2212 	switch (kind) {
2213 	case BPF_DIAG_CONTEXT_RCU:
2214 		return "RCU read lock region";
2215 	case BPF_DIAG_CONTEXT_PREEMPT:
2216 		return "non-preemptible region";
2217 	case BPF_DIAG_CONTEXT_IRQ:
2218 		return "IRQ-disabled region";
2219 	case BPF_DIAG_CONTEXT_LOCK:
2220 		return "lock region";
2221 	case BPF_DIAG_CONTEXT_NONE:
2222 	default:
2223 		return "non-sleepable program";
2224 	}
2225 }
2226 
2227 static void diag_print_context_event(struct bpf_verifier_env *env,
2228 				     const struct bpf_diag_history_event *event)
2229 {
2230 	bpf_diag_source(env, event->insn_idx, "context", "%s %s; depth is now %u",
2231 			event->ctx.enter ? "entered" : "left",
2232 			diag_context_name(event->ctx.kind), event->ctx.depth);
2233 }
2234 
2235 static void diag_print_history(struct bpf_verifier_env *env,
2236 			       const struct bpf_diag_history_opts *opts)
2237 {
2238 	const struct bpf_diag_history_event *event;
2239 	struct bpf_diag_history_filter filter = {
2240 		.opts = opts,
2241 	};
2242 	struct bpf_diag_log *log;
2243 	struct diag_fmt_mark mark;
2244 	bool first = true;
2245 	int start_idx;
2246 	u32 i, visible_cnt = 0, visible_idx = 0;
2247 
2248 	if (!bpf_diag_enabled(env))
2249 		return;
2250 
2251 	if (!env->diag)
2252 		return;
2253 	log = &env->diag->log;
2254 
2255 	diag_build_lineage(env, log, &filter);
2256 
2257 	start_idx = diag_history_start_idx(log, &filter);
2258 	for (i = start_idx; i < log->cnt; i++) {
2259 		event = &log->events[log_pos(log, i)];
2260 		if (diag_history_event_visible(event, &filter))
2261 			visible_cnt++;
2262 	}
2263 
2264 	if (!visible_cnt && !log->first_seq && opts->scope == BPF_DIAG_HISTORY_SCOPE_STACK_ARG)
2265 		return;
2266 
2267 	diag_section(env, "Causal path");
2268 	mark = diag_fmt_save(env);
2269 	for (i = start_idx; i < log->cnt; i++) {
2270 		event = &log->events[log_pos(log, i)];
2271 		if (!diag_history_event_visible(event, &filter))
2272 			continue;
2273 
2274 		diag_fmt_restore(env, mark);
2275 		if (visible_cnt > BPF_DIAG_HISTORY_RENDER_MAX &&
2276 		    visible_idx >= BPF_DIAG_HISTORY_RENDER_MAX / 2 &&
2277 		    visible_idx < visible_cnt - BPF_DIAG_HISTORY_RENDER_MAX / 2) {
2278 			if (visible_idx++ != BPF_DIAG_HISTORY_RENDER_MAX / 2)
2279 				continue;
2280 			if (!first)
2281 				diag_write(env, "\n");
2282 			first = false;
2283 			diag_write(env, "  %u intermediate causal-history events omitted\n",
2284 				   visible_cnt - BPF_DIAG_HISTORY_RENDER_MAX);
2285 			continue;
2286 		}
2287 		visible_idx++;
2288 
2289 		if (!first)
2290 			diag_write(env, "\n");
2291 		first = false;
2292 
2293 		switch (event->kind) {
2294 		case BPF_DIAG_HISTORY_BRANCH:
2295 			bpf_diag_source(env, event->insn_idx, "branch",
2296 					"took the %s branch of this conditional, goto %s",
2297 					event->branch.cond_true ? "true" : "false",
2298 					event->branch.cond_true ? "followed" : "not followed");
2299 			break;
2300 		case BPF_DIAG_HISTORY_MOD:
2301 			diag_print_mod(env, event);
2302 			break;
2303 		case BPF_DIAG_HISTORY_REF_ACQUIRE:
2304 		case BPF_DIAG_HISTORY_REF_RELEASE:
2305 			diag_print_ref_event(env, event);
2306 			break;
2307 		case BPF_DIAG_HISTORY_CONTEXT:
2308 			diag_print_context_event(env, event);
2309 			break;
2310 		default:
2311 			break;
2312 		}
2313 	}
2314 
2315 	if (!visible_cnt)
2316 		diag_write(env, "  no retained diagnostic events on this path\n");
2317 	if (log->first_seq)
2318 		diag_write(env, "  %llu older causal-history event%s not retained because diagnostic "
2319 			   "event storage reached capacity\n",
2320 			   log->first_seq, log->first_seq == 1 ? "" : "s");
2321 	diag_fmt_restore(env, mark);
2322 }
2323