1 // SPDX-License-Identifier: GPL-2.0
3 * This file contains common KASAN error reporting code.
5 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
6 * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
8 * Some code borrowed from https://github.com/xairy/kasan-prototype by
9 * Andrey Konovalov <andreyknvl@gmail.com>
12 #include <linux/bitops.h>
13 #include <linux/ftrace.h>
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/lockdep.h>
18 #include <linux/printk.h>
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/stackdepot.h>
22 #include <linux/stacktrace.h>
23 #include <linux/string.h>
24 #include <linux/types.h>
25 #include <linux/kasan.h>
26 #include <linux/module.h>
27 #include <linux/sched/task_stack.h>
28 #include <linux/uaccess.h>
29 #include <trace/events/error_report.h>
31 #include <asm/sections.h>
33 #include <kunit/test.h>
38 static unsigned long kasan_flags;
40 #define KASAN_BIT_REPORTED 0
41 #define KASAN_BIT_MULTI_SHOT 1
43 enum kasan_arg_fault {
44 KASAN_ARG_FAULT_DEFAULT,
45 KASAN_ARG_FAULT_REPORT,
46 KASAN_ARG_FAULT_PANIC,
49 static enum kasan_arg_fault kasan_arg_fault __ro_after_init = KASAN_ARG_FAULT_DEFAULT;
51 /* kasan.fault=report/panic */
52 static int __init early_kasan_fault(char *arg)
57 if (!strcmp(arg, "report"))
58 kasan_arg_fault = KASAN_ARG_FAULT_REPORT;
59 else if (!strcmp(arg, "panic"))
60 kasan_arg_fault = KASAN_ARG_FAULT_PANIC;
66 early_param("kasan.fault", early_kasan_fault);
68 static int __init kasan_set_multi_shot(char *str)
70 set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
73 __setup("kasan_multi_shot", kasan_set_multi_shot);
76 * Used to suppress reports within kasan_disable/enable_current() critical
77 * sections, which are used for marking accesses to slab metadata.
79 static bool report_suppressed(void)
81 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
82 if (current->kasan_depth)
89 * Used to avoid reporting more than one KASAN bug unless kasan_multi_shot
90 * is enabled. Note that KASAN tests effectively enable kasan_multi_shot
93 static bool report_enabled(void)
95 if (test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
97 return !test_and_set_bit(KASAN_BIT_REPORTED, &kasan_flags);
100 #if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST) || IS_ENABLED(CONFIG_KASAN_MODULE_TEST)
102 bool kasan_save_enable_multi_shot(void)
104 return test_and_set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
106 EXPORT_SYMBOL_GPL(kasan_save_enable_multi_shot);
108 void kasan_restore_multi_shot(bool enabled)
111 clear_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
113 EXPORT_SYMBOL_GPL(kasan_restore_multi_shot);
117 #if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST)
118 static void update_kunit_status(bool sync)
121 struct kunit_resource *resource;
122 struct kunit_kasan_status *status;
124 test = current->kunit_test;
128 resource = kunit_find_named_resource(test, "kasan_status");
130 kunit_set_failure(test);
134 status = (struct kunit_kasan_status *)resource->data;
135 WRITE_ONCE(status->report_found, true);
136 WRITE_ONCE(status->sync_fault, sync);
138 kunit_put_resource(resource);
141 static void update_kunit_status(bool sync) { }
144 static DEFINE_SPINLOCK(report_lock);
146 static void start_report(unsigned long *flags, bool sync)
148 /* Respect the /proc/sys/kernel/traceoff_on_warning interface. */
149 disable_trace_on_warning();
150 /* Update status of the currently running KASAN test. */
151 update_kunit_status(sync);
152 /* Do not allow LOCKDEP mangling KASAN reports. */
154 /* Make sure we don't end up in loop. */
155 kasan_disable_current();
156 spin_lock_irqsave(&report_lock, *flags);
157 pr_err("==================================================================\n");
160 static void end_report(unsigned long *flags, void *addr)
163 trace_error_report_end(ERROR_DETECTOR_KASAN,
164 (unsigned long)addr);
165 pr_err("==================================================================\n");
166 spin_unlock_irqrestore(&report_lock, *flags);
167 if (panic_on_warn && !test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
168 panic("panic_on_warn set ...\n");
169 if (kasan_arg_fault == KASAN_ARG_FAULT_PANIC)
170 panic("kasan.fault=panic set ...\n");
171 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
173 kasan_enable_current();
176 static void print_error_description(struct kasan_report_info *info)
178 if (info->type == KASAN_REPORT_INVALID_FREE) {
179 pr_err("BUG: KASAN: double-free or invalid-free in %pS\n",
184 pr_err("BUG: KASAN: %s in %pS\n",
185 kasan_get_bug_type(info), (void *)info->ip);
186 if (info->access_size)
187 pr_err("%s of size %zu at addr %px by task %s/%d\n",
188 info->is_write ? "Write" : "Read", info->access_size,
189 info->access_addr, current->comm, task_pid_nr(current));
191 pr_err("%s at addr %px by task %s/%d\n",
192 info->is_write ? "Write" : "Read",
193 info->access_addr, current->comm, task_pid_nr(current));
196 static void print_track(struct kasan_track *track, const char *prefix)
198 pr_err("%s by task %u:\n", prefix, track->pid);
200 stack_depot_print(track->stack);
202 pr_err("(stack is not available)\n");
206 struct page *kasan_addr_to_page(const void *addr)
208 if ((addr >= (void *)PAGE_OFFSET) &&
209 (addr < high_memory))
210 return virt_to_head_page(addr);
214 struct slab *kasan_addr_to_slab(const void *addr)
216 if ((addr >= (void *)PAGE_OFFSET) &&
217 (addr < high_memory))
218 return virt_to_slab(addr);
222 static void describe_object_addr(struct kmem_cache *cache, void *object,
225 unsigned long access_addr = (unsigned long)addr;
226 unsigned long object_addr = (unsigned long)object;
227 const char *rel_type;
230 pr_err("The buggy address belongs to the object at %px\n"
231 " which belongs to the cache %s of size %d\n",
232 object, cache->name, cache->object_size);
234 if (access_addr < object_addr) {
235 rel_type = "to the left";
236 rel_bytes = object_addr - access_addr;
237 } else if (access_addr >= object_addr + cache->object_size) {
238 rel_type = "to the right";
239 rel_bytes = access_addr - (object_addr + cache->object_size);
242 rel_bytes = access_addr - object_addr;
245 pr_err("The buggy address is located %d bytes %s of\n"
246 " %d-byte region [%px, %px)\n",
247 rel_bytes, rel_type, cache->object_size, (void *)object_addr,
248 (void *)(object_addr + cache->object_size));
251 static void describe_object_stacks(struct kmem_cache *cache, void *object,
252 const void *addr, u8 tag)
254 struct kasan_alloc_meta *alloc_meta;
255 struct kasan_track *free_track;
257 alloc_meta = kasan_get_alloc_meta(cache, object);
259 print_track(&alloc_meta->alloc_track, "Allocated");
263 free_track = kasan_get_free_track(cache, object, tag);
265 print_track(free_track, "Freed");
269 #ifdef CONFIG_KASAN_GENERIC
272 if (alloc_meta->aux_stack[0]) {
273 pr_err("Last potentially related work creation:\n");
274 stack_depot_print(alloc_meta->aux_stack[0]);
277 if (alloc_meta->aux_stack[1]) {
278 pr_err("Second to last potentially related work creation:\n");
279 stack_depot_print(alloc_meta->aux_stack[1]);
285 static void describe_object(struct kmem_cache *cache, void *object,
286 const void *addr, u8 tag)
288 if (kasan_stack_collection_enabled())
289 describe_object_stacks(cache, object, addr, tag);
290 describe_object_addr(cache, object, addr);
293 static inline bool kernel_or_module_addr(const void *addr)
295 if (is_kernel((unsigned long)addr))
297 if (is_module_address((unsigned long)addr))
302 static inline bool init_task_stack_addr(const void *addr)
304 return addr >= (void *)&init_thread_union.stack &&
305 (addr <= (void *)&init_thread_union.stack +
306 sizeof(init_thread_union.stack));
309 static void print_address_description(void *addr, u8 tag)
311 struct page *page = kasan_addr_to_page(addr);
313 dump_stack_lvl(KERN_ERR);
316 if (page && PageSlab(page)) {
317 struct slab *slab = page_slab(page);
318 struct kmem_cache *cache = slab->slab_cache;
319 void *object = nearest_obj(cache, slab, addr);
321 describe_object(cache, object, addr, tag);
325 if (kernel_or_module_addr(addr) && !init_task_stack_addr(addr)) {
326 pr_err("The buggy address belongs to the variable:\n");
327 pr_err(" %pS\n", addr);
331 if (object_is_on_stack(addr)) {
333 * Currently, KASAN supports printing frame information only
334 * for accesses to the task's own stack.
336 kasan_print_address_stack_frame(addr);
340 if (is_vmalloc_addr(addr)) {
341 struct vm_struct *va = find_vm_area(addr);
344 pr_err("The buggy address belongs to the virtual mapping at\n"
345 " [%px, %px) created by:\n"
347 va->addr, va->addr + va->size, va->caller);
350 page = vmalloc_to_page(addr);
355 pr_err("The buggy address belongs to the physical page:\n");
356 dump_page(page, "kasan: bad access detected");
361 static bool meta_row_is_guilty(const void *row, const void *addr)
363 return (row <= addr) && (addr < row + META_MEM_BYTES_PER_ROW);
366 static int meta_pointer_offset(const void *row, const void *addr)
369 * Memory state around the buggy address:
370 * ff00ff00ff00ff00: 00 00 00 05 fe fe fe fe fe fe fe fe fe fe fe fe
373 * The length of ">ff00ff00ff00ff00: " is
374 * 3 + (BITS_PER_LONG / 8) * 2 chars.
375 * The length of each granule metadata is 2 bytes
376 * plus 1 byte for space.
378 return 3 + (BITS_PER_LONG / 8) * 2 +
379 (addr - row) / KASAN_GRANULE_SIZE * 3 + 1;
382 static void print_memory_metadata(const void *addr)
387 row = (void *)round_down((unsigned long)addr, META_MEM_BYTES_PER_ROW)
388 - META_ROWS_AROUND_ADDR * META_MEM_BYTES_PER_ROW;
390 pr_err("Memory state around the buggy address:\n");
392 for (i = -META_ROWS_AROUND_ADDR; i <= META_ROWS_AROUND_ADDR; i++) {
393 char buffer[4 + (BITS_PER_LONG / 8) * 2];
394 char metadata[META_BYTES_PER_ROW];
396 snprintf(buffer, sizeof(buffer),
397 (i == 0) ? ">%px: " : " %px: ", row);
400 * We should not pass a shadow pointer to generic
401 * function, because generic functions may try to
402 * access kasan mapping for the passed address.
404 kasan_metadata_fetch_row(&metadata[0], row);
406 print_hex_dump(KERN_ERR, buffer,
407 DUMP_PREFIX_NONE, META_BYTES_PER_ROW, 1,
408 metadata, META_BYTES_PER_ROW, 0);
410 if (meta_row_is_guilty(row, addr))
411 pr_err("%*c\n", meta_pointer_offset(row, addr), '^');
413 row += META_MEM_BYTES_PER_ROW;
417 static void print_report(struct kasan_report_info *info)
419 void *tagged_addr = info->access_addr;
420 void *untagged_addr = kasan_reset_tag(tagged_addr);
421 u8 tag = get_tag(tagged_addr);
423 print_error_description(info);
424 if (addr_has_metadata(untagged_addr))
425 kasan_print_tags(tag, info->first_bad_addr);
428 if (addr_has_metadata(untagged_addr)) {
429 print_address_description(untagged_addr, tag);
430 print_memory_metadata(info->first_bad_addr);
432 dump_stack_lvl(KERN_ERR);
436 void kasan_report_invalid_free(void *ptr, unsigned long ip)
439 struct kasan_report_info info;
442 * Do not check report_suppressed(), as an invalid-free cannot be
443 * caused by accessing slab metadata and thus should not be
444 * suppressed by kasan_disable/enable_current() critical sections.
446 if (unlikely(!report_enabled()))
449 start_report(&flags, true);
451 info.type = KASAN_REPORT_INVALID_FREE;
452 info.access_addr = ptr;
453 info.first_bad_addr = kasan_reset_tag(ptr);
454 info.access_size = 0;
455 info.is_write = false;
460 end_report(&flags, ptr);
464 * kasan_report() is the only reporting function that uses
465 * user_access_save/restore(): kasan_report_invalid_free() cannot be called
466 * from a UACCESS region, and kasan_report_async() is not used on x86.
468 bool kasan_report(unsigned long addr, size_t size, bool is_write,
472 void *ptr = (void *)addr;
473 unsigned long ua_flags = user_access_save();
474 unsigned long irq_flags;
475 struct kasan_report_info info;
477 if (unlikely(report_suppressed()) || unlikely(!report_enabled())) {
482 start_report(&irq_flags, true);
484 info.type = KASAN_REPORT_ACCESS;
485 info.access_addr = ptr;
486 info.first_bad_addr = kasan_find_first_bad_addr(ptr, size);
487 info.access_size = size;
488 info.is_write = is_write;
493 end_report(&irq_flags, ptr);
496 user_access_restore(ua_flags);
501 #ifdef CONFIG_KASAN_HW_TAGS
502 void kasan_report_async(void)
507 * Do not check report_suppressed(), as kasan_disable/enable_current()
508 * critical sections do not affect Hardware Tag-Based KASAN.
510 if (unlikely(!report_enabled()))
513 start_report(&flags, false);
514 pr_err("BUG: KASAN: invalid-access\n");
515 pr_err("Asynchronous fault: no details available\n");
517 dump_stack_lvl(KERN_ERR);
518 end_report(&flags, NULL);
520 #endif /* CONFIG_KASAN_HW_TAGS */
522 #ifdef CONFIG_KASAN_INLINE
524 * With CONFIG_KASAN_INLINE, accesses to bogus pointers (outside the high
525 * canonical half of the address space) cause out-of-bounds shadow memory reads
526 * before the actual access. For addresses in the low canonical half of the
527 * address space, as well as most non-canonical addresses, that out-of-bounds
528 * shadow memory access lands in the non-canonical part of the address space.
529 * Help the user figure out what the original bogus pointer was.
531 void kasan_non_canonical_hook(unsigned long addr)
533 unsigned long orig_addr;
534 const char *bug_type;
536 if (addr < KASAN_SHADOW_OFFSET)
539 orig_addr = (addr - KASAN_SHADOW_OFFSET) << KASAN_SHADOW_SCALE_SHIFT;
541 * For faults near the shadow address for NULL, we can be fairly certain
542 * that this is a KASAN shadow memory access.
543 * For faults that correspond to shadow for low canonical addresses, we
544 * can still be pretty sure - that shadow region is a fairly narrow
545 * chunk of the non-canonical address space.
546 * But faults that look like shadow for non-canonical addresses are a
547 * really large chunk of the address space. In that case, we still
548 * print the decoded address, but make it clear that this is not
549 * necessarily what's actually going on.
551 if (orig_addr < PAGE_SIZE)
552 bug_type = "null-ptr-deref";
553 else if (orig_addr < TASK_SIZE)
554 bug_type = "probably user-memory-access";
556 bug_type = "maybe wild-memory-access";
557 pr_alert("KASAN: %s in range [0x%016lx-0x%016lx]\n", bug_type,
558 orig_addr, orig_addr + KASAN_GRANULE_SIZE - 1);