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