xref: /openbmc/linux/mm/kfence/report.c (revision 6a143a7c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KFENCE reporting.
4  *
5  * Copyright (C) 2020, Google LLC.
6  */
7 
8 #include <stdarg.h>
9 
10 #include <linux/kernel.h>
11 #include <linux/lockdep.h>
12 #include <linux/printk.h>
13 #include <linux/sched/debug.h>
14 #include <linux/seq_file.h>
15 #include <linux/stacktrace.h>
16 #include <linux/string.h>
17 #include <trace/events/error_report.h>
18 
19 #include <asm/kfence.h>
20 
21 #include "kfence.h"
22 
23 extern bool no_hash_pointers;
24 
25 /* Helper function to either print to a seq_file or to console. */
26 __printf(2, 3)
27 static void seq_con_printf(struct seq_file *seq, const char *fmt, ...)
28 {
29 	va_list args;
30 
31 	va_start(args, fmt);
32 	if (seq)
33 		seq_vprintf(seq, fmt, args);
34 	else
35 		vprintk(fmt, args);
36 	va_end(args);
37 }
38 
39 /*
40  * Get the number of stack entries to skip to get out of MM internals. @type is
41  * optional, and if set to NULL, assumes an allocation or free stack.
42  */
43 static int get_stack_skipnr(const unsigned long stack_entries[], int num_entries,
44 			    const enum kfence_error_type *type)
45 {
46 	char buf[64];
47 	int skipnr, fallback = 0;
48 
49 	if (type) {
50 		/* Depending on error type, find different stack entries. */
51 		switch (*type) {
52 		case KFENCE_ERROR_UAF:
53 		case KFENCE_ERROR_OOB:
54 		case KFENCE_ERROR_INVALID:
55 			/*
56 			 * kfence_handle_page_fault() may be called with pt_regs
57 			 * set to NULL; in that case we'll simply show the full
58 			 * stack trace.
59 			 */
60 			return 0;
61 		case KFENCE_ERROR_CORRUPTION:
62 		case KFENCE_ERROR_INVALID_FREE:
63 			break;
64 		}
65 	}
66 
67 	for (skipnr = 0; skipnr < num_entries; skipnr++) {
68 		int len = scnprintf(buf, sizeof(buf), "%ps", (void *)stack_entries[skipnr]);
69 
70 		if (str_has_prefix(buf, "kfence_") || str_has_prefix(buf, "__kfence_") ||
71 		    !strncmp(buf, "__slab_free", len)) {
72 			/*
73 			 * In case of tail calls from any of the below
74 			 * to any of the above.
75 			 */
76 			fallback = skipnr + 1;
77 		}
78 
79 		/* Also the *_bulk() variants by only checking prefixes. */
80 		if (str_has_prefix(buf, "kfree") ||
81 		    str_has_prefix(buf, "kmem_cache_free") ||
82 		    str_has_prefix(buf, "__kmalloc") ||
83 		    str_has_prefix(buf, "kmem_cache_alloc"))
84 			goto found;
85 	}
86 	if (fallback < num_entries)
87 		return fallback;
88 found:
89 	skipnr++;
90 	return skipnr < num_entries ? skipnr : 0;
91 }
92 
93 static void kfence_print_stack(struct seq_file *seq, const struct kfence_metadata *meta,
94 			       bool show_alloc)
95 {
96 	const struct kfence_track *track = show_alloc ? &meta->alloc_track : &meta->free_track;
97 
98 	if (track->num_stack_entries) {
99 		/* Skip allocation/free internals stack. */
100 		int i = get_stack_skipnr(track->stack_entries, track->num_stack_entries, NULL);
101 
102 		/* stack_trace_seq_print() does not exist; open code our own. */
103 		for (; i < track->num_stack_entries; i++)
104 			seq_con_printf(seq, " %pS\n", (void *)track->stack_entries[i]);
105 	} else {
106 		seq_con_printf(seq, " no %s stack\n", show_alloc ? "allocation" : "deallocation");
107 	}
108 }
109 
110 void kfence_print_object(struct seq_file *seq, const struct kfence_metadata *meta)
111 {
112 	const int size = abs(meta->size);
113 	const unsigned long start = meta->addr;
114 	const struct kmem_cache *const cache = meta->cache;
115 
116 	lockdep_assert_held(&meta->lock);
117 
118 	if (meta->state == KFENCE_OBJECT_UNUSED) {
119 		seq_con_printf(seq, "kfence-#%zd unused\n", meta - kfence_metadata);
120 		return;
121 	}
122 
123 	seq_con_printf(seq,
124 		       "kfence-#%zd [0x%p-0x%p"
125 		       ", size=%d, cache=%s] allocated by task %d:\n",
126 		       meta - kfence_metadata, (void *)start, (void *)(start + size - 1), size,
127 		       (cache && cache->name) ? cache->name : "<destroyed>", meta->alloc_track.pid);
128 	kfence_print_stack(seq, meta, true);
129 
130 	if (meta->state == KFENCE_OBJECT_FREED) {
131 		seq_con_printf(seq, "\nfreed by task %d:\n", meta->free_track.pid);
132 		kfence_print_stack(seq, meta, false);
133 	}
134 }
135 
136 /*
137  * Show bytes at @addr that are different from the expected canary values, up to
138  * @max_bytes.
139  */
140 static void print_diff_canary(unsigned long address, size_t bytes_to_show,
141 			      const struct kfence_metadata *meta)
142 {
143 	const unsigned long show_until_addr = address + bytes_to_show;
144 	const u8 *cur, *end;
145 
146 	/* Do not show contents of object nor read into following guard page. */
147 	end = (const u8 *)(address < meta->addr ? min(show_until_addr, meta->addr)
148 						: min(show_until_addr, PAGE_ALIGN(address)));
149 
150 	pr_cont("[");
151 	for (cur = (const u8 *)address; cur < end; cur++) {
152 		if (*cur == KFENCE_CANARY_PATTERN(cur))
153 			pr_cont(" .");
154 		else if (no_hash_pointers)
155 			pr_cont(" 0x%02x", *cur);
156 		else /* Do not leak kernel memory in non-debug builds. */
157 			pr_cont(" !");
158 	}
159 	pr_cont(" ]");
160 }
161 
162 static const char *get_access_type(bool is_write)
163 {
164 	return is_write ? "write" : "read";
165 }
166 
167 void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *regs,
168 			 const struct kfence_metadata *meta, enum kfence_error_type type)
169 {
170 	unsigned long stack_entries[KFENCE_STACK_DEPTH] = { 0 };
171 	const ptrdiff_t object_index = meta ? meta - kfence_metadata : -1;
172 	int num_stack_entries;
173 	int skipnr = 0;
174 
175 	if (regs) {
176 		num_stack_entries = stack_trace_save_regs(regs, stack_entries, KFENCE_STACK_DEPTH, 0);
177 	} else {
178 		num_stack_entries = stack_trace_save(stack_entries, KFENCE_STACK_DEPTH, 1);
179 		skipnr = get_stack_skipnr(stack_entries, num_stack_entries, &type);
180 	}
181 
182 	/* Require non-NULL meta, except if KFENCE_ERROR_INVALID. */
183 	if (WARN_ON(type != KFENCE_ERROR_INVALID && !meta))
184 		return;
185 
186 	if (meta)
187 		lockdep_assert_held(&meta->lock);
188 	/*
189 	 * Because we may generate reports in printk-unfriendly parts of the
190 	 * kernel, such as scheduler code, the use of printk() could deadlock.
191 	 * Until such time that all printing code here is safe in all parts of
192 	 * the kernel, accept the risk, and just get our message out (given the
193 	 * system might already behave unpredictably due to the memory error).
194 	 * As such, also disable lockdep to hide warnings, and avoid disabling
195 	 * lockdep for the rest of the kernel.
196 	 */
197 	lockdep_off();
198 
199 	pr_err("==================================================================\n");
200 	/* Print report header. */
201 	switch (type) {
202 	case KFENCE_ERROR_OOB: {
203 		const bool left_of_object = address < meta->addr;
204 
205 		pr_err("BUG: KFENCE: out-of-bounds %s in %pS\n\n", get_access_type(is_write),
206 		       (void *)stack_entries[skipnr]);
207 		pr_err("Out-of-bounds %s at 0x%p (%luB %s of kfence-#%zd):\n",
208 		       get_access_type(is_write), (void *)address,
209 		       left_of_object ? meta->addr - address : address - meta->addr,
210 		       left_of_object ? "left" : "right", object_index);
211 		break;
212 	}
213 	case KFENCE_ERROR_UAF:
214 		pr_err("BUG: KFENCE: use-after-free %s in %pS\n\n", get_access_type(is_write),
215 		       (void *)stack_entries[skipnr]);
216 		pr_err("Use-after-free %s at 0x%p (in kfence-#%zd):\n",
217 		       get_access_type(is_write), (void *)address, object_index);
218 		break;
219 	case KFENCE_ERROR_CORRUPTION:
220 		pr_err("BUG: KFENCE: memory corruption in %pS\n\n", (void *)stack_entries[skipnr]);
221 		pr_err("Corrupted memory at 0x%p ", (void *)address);
222 		print_diff_canary(address, 16, meta);
223 		pr_cont(" (in kfence-#%zd):\n", object_index);
224 		break;
225 	case KFENCE_ERROR_INVALID:
226 		pr_err("BUG: KFENCE: invalid %s in %pS\n\n", get_access_type(is_write),
227 		       (void *)stack_entries[skipnr]);
228 		pr_err("Invalid %s at 0x%p:\n", get_access_type(is_write),
229 		       (void *)address);
230 		break;
231 	case KFENCE_ERROR_INVALID_FREE:
232 		pr_err("BUG: KFENCE: invalid free in %pS\n\n", (void *)stack_entries[skipnr]);
233 		pr_err("Invalid free of 0x%p (in kfence-#%zd):\n", (void *)address,
234 		       object_index);
235 		break;
236 	}
237 
238 	/* Print stack trace and object info. */
239 	stack_trace_print(stack_entries + skipnr, num_stack_entries - skipnr, 0);
240 
241 	if (meta) {
242 		pr_err("\n");
243 		kfence_print_object(NULL, meta);
244 	}
245 
246 	/* Print report footer. */
247 	pr_err("\n");
248 	if (no_hash_pointers && regs)
249 		show_regs(regs);
250 	else
251 		dump_stack_print_info(KERN_ERR);
252 	trace_error_report_end(ERROR_DETECTOR_KFENCE, address);
253 	pr_err("==================================================================\n");
254 
255 	lockdep_on();
256 
257 	if (panic_on_warn)
258 		panic("panic_on_warn set ...\n");
259 
260 	/* We encountered a memory unsafety error, taint the kernel! */
261 	add_taint(TAINT_BAD_PAGE, LOCKDEP_STILL_OK);
262 }
263