Linux Audio

Check our new training course

Embedded Linux training

Mar 10-20, 2025, special US time zones
Register
Loading...
v6.8
  1// SPDX-License-Identifier: GPL-2.0
  2/*
  3 * This file contains common KASAN error reporting code.
  4 *
  5 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
  6 * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
  7 *
  8 * Some code borrowed from https://github.com/xairy/kasan-prototype by
  9 *        Andrey Konovalov <andreyknvl@gmail.com>
 
 
 
 
 
 10 */
 11
 12#include <kunit/test.h>
 13#include <linux/bitops.h>
 14#include <linux/ftrace.h>
 15#include <linux/init.h>
 16#include <linux/kernel.h>
 17#include <linux/lockdep.h>
 18#include <linux/mm.h>
 19#include <linux/printk.h>
 20#include <linux/sched.h>
 21#include <linux/slab.h>
 22#include <linux/stackdepot.h>
 23#include <linux/stacktrace.h>
 24#include <linux/string.h>
 25#include <linux/types.h>
 26#include <linux/vmalloc.h>
 27#include <linux/kasan.h>
 28#include <linux/module.h>
 29#include <linux/sched/task_stack.h>
 30#include <linux/uaccess.h>
 31#include <trace/events/error_report.h>
 32
 33#include <asm/sections.h>
 34
 35#include "kasan.h"
 36#include "../slab.h"
 37
 38static unsigned long kasan_flags;
 39
 40#define KASAN_BIT_REPORTED	0
 41#define KASAN_BIT_MULTI_SHOT	1
 
 42
 43enum kasan_arg_fault {
 44	KASAN_ARG_FAULT_DEFAULT,
 45	KASAN_ARG_FAULT_REPORT,
 46	KASAN_ARG_FAULT_PANIC,
 47	KASAN_ARG_FAULT_PANIC_ON_WRITE,
 48};
 49
 50static enum kasan_arg_fault kasan_arg_fault __ro_after_init = KASAN_ARG_FAULT_DEFAULT;
 51
 52/* kasan.fault=report/panic */
 53static int __init early_kasan_fault(char *arg)
 54{
 55	if (!arg)
 56		return -EINVAL;
 57
 58	if (!strcmp(arg, "report"))
 59		kasan_arg_fault = KASAN_ARG_FAULT_REPORT;
 60	else if (!strcmp(arg, "panic"))
 61		kasan_arg_fault = KASAN_ARG_FAULT_PANIC;
 62	else if (!strcmp(arg, "panic_on_write"))
 63		kasan_arg_fault = KASAN_ARG_FAULT_PANIC_ON_WRITE;
 64	else
 65		return -EINVAL;
 66
 67	return 0;
 
 
 
 
 68}
 69early_param("kasan.fault", early_kasan_fault);
 70
 71static int __init kasan_set_multi_shot(char *str)
 72{
 73	set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
 74	return 1;
 75}
 76__setup("kasan_multi_shot", kasan_set_multi_shot);
 77
 78/*
 79 * This function is used to check whether KASAN reports are suppressed for
 80 * software KASAN modes via kasan_disable/enable_current() critical sections.
 81 *
 82 * This is done to avoid:
 83 * 1. False-positive reports when accessing slab metadata,
 84 * 2. Deadlocking when poisoned memory is accessed by the reporting code.
 85 *
 86 * Hardware Tag-Based KASAN instead relies on:
 87 * For #1: Resetting tags via kasan_reset_tag().
 88 * For #2: Suppression of tag checks via CPU, see report_suppress_start/end().
 89 */
 90static bool report_suppressed_sw(void)
 91{
 92#if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
 93	if (current->kasan_depth)
 94		return true;
 95#endif
 96	return false;
 97}
 98
 99static void report_suppress_start(void)
100{
101#ifdef CONFIG_KASAN_HW_TAGS
102	/*
103	 * Disable preemption for the duration of printing a KASAN report, as
104	 * hw_suppress_tag_checks_start() disables checks on the current CPU.
105	 */
106	preempt_disable();
107	hw_suppress_tag_checks_start();
108#else
109	kasan_disable_current();
110#endif
111}
112
113static void report_suppress_stop(void)
114{
115#ifdef CONFIG_KASAN_HW_TAGS
116	hw_suppress_tag_checks_stop();
117	preempt_enable();
118#else
119	kasan_enable_current();
120#endif
121}
122
123/*
124 * Used to avoid reporting more than one KASAN bug unless kasan_multi_shot
125 * is enabled. Note that KASAN tests effectively enable kasan_multi_shot
126 * for their duration.
127 */
128static bool report_enabled(void)
129{
130	if (test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
131		return true;
132	return !test_and_set_bit(KASAN_BIT_REPORTED, &kasan_flags);
133}
134
135#if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST) || IS_ENABLED(CONFIG_KASAN_MODULE_TEST)
136
137bool kasan_save_enable_multi_shot(void)
138{
139	return test_and_set_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
140}
141EXPORT_SYMBOL_GPL(kasan_save_enable_multi_shot);
142
143void kasan_restore_multi_shot(bool enabled)
144{
145	if (!enabled)
146		clear_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags);
147}
148EXPORT_SYMBOL_GPL(kasan_restore_multi_shot);
149
150#endif
151
152#if IS_ENABLED(CONFIG_KASAN_KUNIT_TEST)
153
154/*
155 * Whether the KASAN KUnit test suite is currently being executed.
156 * Updated in kasan_test.c.
157 */
158static bool kasan_kunit_executing;
159
160void kasan_kunit_test_suite_start(void)
161{
162	WRITE_ONCE(kasan_kunit_executing, true);
163}
164EXPORT_SYMBOL_GPL(kasan_kunit_test_suite_start);
165
166void kasan_kunit_test_suite_end(void)
167{
168	WRITE_ONCE(kasan_kunit_executing, false);
 
 
 
169}
170EXPORT_SYMBOL_GPL(kasan_kunit_test_suite_end);
171
172static bool kasan_kunit_test_suite_executing(void)
173{
174	return READ_ONCE(kasan_kunit_executing);
 
 
 
 
175}
176
177#else /* CONFIG_KASAN_KUNIT_TEST */
178
179static inline bool kasan_kunit_test_suite_executing(void) { return false; }
180
181#endif /* CONFIG_KASAN_KUNIT_TEST */
182
183#if IS_ENABLED(CONFIG_KUNIT)
184
185static void fail_non_kasan_kunit_test(void)
186{
187	struct kunit *test;
188
189	if (kasan_kunit_test_suite_executing())
190		return;
191
192	test = current->kunit_test;
193	if (test)
194		kunit_set_failure(test);
195}
196
197#else /* CONFIG_KUNIT */
198
199static inline void fail_non_kasan_kunit_test(void) { }
200
201#endif /* CONFIG_KUNIT */
202
203static DEFINE_SPINLOCK(report_lock);
204
205static void start_report(unsigned long *flags, bool sync)
206{
207	fail_non_kasan_kunit_test();
208	/* Respect the /proc/sys/kernel/traceoff_on_warning interface. */
209	disable_trace_on_warning();
210	/* Do not allow LOCKDEP mangling KASAN reports. */
211	lockdep_off();
212	/* Make sure we don't end up in loop. */
213	report_suppress_start();
214	spin_lock_irqsave(&report_lock, *flags);
215	pr_err("==================================================================\n");
216}
217
218static void end_report(unsigned long *flags, const void *addr, bool is_write)
219{
220	if (addr)
221		trace_error_report_end(ERROR_DETECTOR_KASAN,
222				       (unsigned long)addr);
223	pr_err("==================================================================\n");
224	spin_unlock_irqrestore(&report_lock, *flags);
225	if (!test_bit(KASAN_BIT_MULTI_SHOT, &kasan_flags))
226		check_panic_on_warn("KASAN");
227	switch (kasan_arg_fault) {
228	case KASAN_ARG_FAULT_DEFAULT:
229	case KASAN_ARG_FAULT_REPORT:
230		break;
231	case KASAN_ARG_FAULT_PANIC:
232		panic("kasan.fault=panic set ...\n");
233		break;
234	case KASAN_ARG_FAULT_PANIC_ON_WRITE:
235		if (is_write)
236			panic("kasan.fault=panic_on_write set ...\n");
237		break;
238	}
239	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
240	lockdep_on();
241	report_suppress_stop();
242}
243
244static void print_error_description(struct kasan_report_info *info)
245{
246	pr_err("BUG: KASAN: %s in %pS\n", info->bug_type, (void *)info->ip);
247
248	if (info->type != KASAN_REPORT_ACCESS) {
249		pr_err("Free of addr %px by task %s/%d\n",
250			info->access_addr, current->comm, task_pid_nr(current));
251		return;
252	}
253
254	if (info->access_size)
255		pr_err("%s of size %zu at addr %px by task %s/%d\n",
256			info->is_write ? "Write" : "Read", info->access_size,
257			info->access_addr, current->comm, task_pid_nr(current));
258	else
259		pr_err("%s at addr %px by task %s/%d\n",
260			info->is_write ? "Write" : "Read",
261			info->access_addr, current->comm, task_pid_nr(current));
262}
263
264static void print_track(struct kasan_track *track, const char *prefix)
265{
266#ifdef CONFIG_KASAN_EXTRA_INFO
267	u64 ts_nsec = track->timestamp;
268	unsigned long rem_usec;
269
270	ts_nsec <<= 3;
271	rem_usec = do_div(ts_nsec, NSEC_PER_SEC) / 1000;
272
273	pr_err("%s by task %u on cpu %d at %lu.%06lus:\n",
274			prefix, track->pid, track->cpu,
275			(unsigned long)ts_nsec, rem_usec);
276#else
277	pr_err("%s by task %u:\n", prefix, track->pid);
278#endif /* CONFIG_KASAN_EXTRA_INFO */
279	if (track->stack)
280		stack_depot_print(track->stack);
281	else
282		pr_err("(stack is not available)\n");
283}
284
285static inline struct page *addr_to_page(const void *addr)
286{
287	if (virt_addr_valid(addr))
288		return virt_to_head_page(addr);
289	return NULL;
290}
291
292static void describe_object_addr(const void *addr, struct kasan_report_info *info)
293{
294	unsigned long access_addr = (unsigned long)addr;
295	unsigned long object_addr = (unsigned long)info->object;
296	const char *rel_type, *region_state = "";
297	int rel_bytes;
298
299	pr_err("The buggy address belongs to the object at %px\n"
300	       " which belongs to the cache %s of size %d\n",
301		info->object, info->cache->name, info->cache->object_size);
302
303	if (access_addr < object_addr) {
304		rel_type = "to the left";
305		rel_bytes = object_addr - access_addr;
306	} else if (access_addr >= object_addr + info->alloc_size) {
307		rel_type = "to the right";
308		rel_bytes = access_addr - (object_addr + info->alloc_size);
309	} else {
310		rel_type = "inside";
311		rel_bytes = access_addr - object_addr;
312	}
313
314	/*
315	 * Tag-Based modes use the stack ring to infer the bug type, but the
316	 * memory region state description is generated based on the metadata.
317	 * Thus, defining the region state as below can contradict the metadata.
318	 * Fixing this requires further improvements, so only infer the state
319	 * for the Generic mode.
320	 */
321	if (IS_ENABLED(CONFIG_KASAN_GENERIC)) {
322		if (strcmp(info->bug_type, "slab-out-of-bounds") == 0)
323			region_state = "allocated ";
324		else if (strcmp(info->bug_type, "slab-use-after-free") == 0)
325			region_state = "freed ";
326	}
327
328	pr_err("The buggy address is located %d bytes %s of\n"
329	       " %s%zu-byte region [%px, %px)\n",
330	       rel_bytes, rel_type, region_state, info->alloc_size,
331	       (void *)object_addr, (void *)(object_addr + info->alloc_size));
332}
333
334static void describe_object_stacks(struct kasan_report_info *info)
335{
336	if (info->alloc_track.stack) {
337		print_track(&info->alloc_track, "Allocated");
338		pr_err("\n");
339	}
340
341	if (info->free_track.stack) {
342		print_track(&info->free_track, "Freed");
343		pr_err("\n");
344	}
345
346	kasan_print_aux_stacks(info->cache, info->object);
347}
 
348
349static void describe_object(const void *addr, struct kasan_report_info *info)
350{
351	if (kasan_stack_collection_enabled())
352		describe_object_stacks(info);
353	describe_object_addr(addr, info);
354}
355
356static inline bool kernel_or_module_addr(const void *addr)
357{
358	if (is_kernel((unsigned long)addr))
359		return true;
360	if (is_module_address((unsigned long)addr))
361		return true;
362	return false;
363}
364
365static inline bool init_task_stack_addr(const void *addr)
 
366{
367	return addr >= (void *)&init_thread_union.stack &&
368		(addr <= (void *)&init_thread_union.stack +
369			sizeof(init_thread_union.stack));
370}
371
372static void print_address_description(void *addr, u8 tag,
373				      struct kasan_report_info *info)
374{
375	struct page *page = addr_to_page(addr);
376
377	dump_stack_lvl(KERN_ERR);
378	pr_err("\n");
379
380	if (info->cache && info->object) {
381		describe_object(addr, info);
382		pr_err("\n");
383	}
384
385	if (kernel_or_module_addr(addr) && !init_task_stack_addr(addr)) {
386		pr_err("The buggy address belongs to the variable:\n");
387		pr_err(" %pS\n", addr);
388		pr_err("\n");
389	}
390
391	if (object_is_on_stack(addr)) {
392		/*
393		 * Currently, KASAN supports printing frame information only
394		 * for accesses to the task's own stack.
395		 */
396		kasan_print_address_stack_frame(addr);
397		pr_err("\n");
398	}
399
400	if (is_vmalloc_addr(addr)) {
401		struct vm_struct *va = find_vm_area(addr);
402
403		if (va) {
404			pr_err("The buggy address belongs to the virtual mapping at\n"
405			       " [%px, %px) created by:\n"
406			       " %pS\n",
407			       va->addr, va->addr + va->size, va->caller);
408			pr_err("\n");
409
410			page = vmalloc_to_page(addr);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411		}
 
412	}
413
414	if (page) {
415		pr_err("The buggy address belongs to the physical page:\n");
416		dump_page(page, "kasan: bad access detected");
417		pr_err("\n");
418	}
 
419}
420
421static bool meta_row_is_guilty(const void *row, const void *addr)
422{
423	return (row <= addr) && (addr < row + META_MEM_BYTES_PER_ROW);
424}
425
426static int meta_pointer_offset(const void *row, const void *addr)
427{
428	/*
429	 * Memory state around the buggy address:
430	 *  ff00ff00ff00ff00: 00 00 00 05 fe fe fe fe fe fe fe fe fe fe fe fe
431	 *  ...
432	 *
433	 * The length of ">ff00ff00ff00ff00: " is
434	 *    3 + (BITS_PER_LONG / 8) * 2 chars.
435	 * The length of each granule metadata is 2 bytes
436	 *    plus 1 byte for space.
437	 */
438	return 3 + (BITS_PER_LONG / 8) * 2 +
439		(addr - row) / KASAN_GRANULE_SIZE * 3 + 1;
440}
441
442static void print_memory_metadata(const void *addr)
443{
444	int i;
445	void *row;
 
446
447	row = (void *)round_down((unsigned long)addr, META_MEM_BYTES_PER_ROW)
448			- META_ROWS_AROUND_ADDR * META_MEM_BYTES_PER_ROW;
 
449
450	pr_err("Memory state around the buggy address:\n");
451
452	for (i = -META_ROWS_AROUND_ADDR; i <= META_ROWS_AROUND_ADDR; i++) {
453		char buffer[4 + (BITS_PER_LONG / 8) * 2];
454		char metadata[META_BYTES_PER_ROW];
 
455
456		snprintf(buffer, sizeof(buffer),
457				(i == 0) ? ">%px: " : " %px: ", row);
458
459		/*
460		 * We should not pass a shadow pointer to generic
461		 * function, because generic functions may try to
462		 * access kasan mapping for the passed address.
463		 */
464		kasan_metadata_fetch_row(&metadata[0], row);
465
466		print_hex_dump(KERN_ERR, buffer,
467			DUMP_PREFIX_NONE, META_BYTES_PER_ROW, 1,
468			metadata, META_BYTES_PER_ROW, 0);
469
470		if (meta_row_is_guilty(row, addr))
471			pr_err("%*c\n", meta_pointer_offset(row, addr), '^');
 
 
472
473		row += META_MEM_BYTES_PER_ROW;
474	}
475}
476
477static void print_report(struct kasan_report_info *info)
478{
479	void *addr = kasan_reset_tag((void *)info->access_addr);
480	u8 tag = get_tag((void *)info->access_addr);
481
482	print_error_description(info);
483	if (addr_has_metadata(addr))
484		kasan_print_tags(tag, info->first_bad_addr);
485	pr_err("\n");
486
487	if (addr_has_metadata(addr)) {
488		print_address_description(addr, tag, info);
489		print_memory_metadata(info->first_bad_addr);
490	} else {
491		dump_stack_lvl(KERN_ERR);
492	}
493}
494
495static void complete_report_info(struct kasan_report_info *info)
496{
497	void *addr = kasan_reset_tag((void *)info->access_addr);
498	struct slab *slab;
499
500	if (info->type == KASAN_REPORT_ACCESS)
501		info->first_bad_addr = kasan_find_first_bad_addr(
502					(void *)info->access_addr, info->access_size);
503	else
504		info->first_bad_addr = addr;
505
506	slab = kasan_addr_to_slab(addr);
507	if (slab) {
508		info->cache = slab->slab_cache;
509		info->object = nearest_obj(info->cache, slab, addr);
510
511		/* Try to determine allocation size based on the metadata. */
512		info->alloc_size = kasan_get_alloc_size(info->object, info->cache);
513		/* Fallback to the object size if failed. */
514		if (!info->alloc_size)
515			info->alloc_size = info->cache->object_size;
516	} else
517		info->cache = info->object = NULL;
518
519	switch (info->type) {
520	case KASAN_REPORT_INVALID_FREE:
521		info->bug_type = "invalid-free";
522		break;
523	case KASAN_REPORT_DOUBLE_FREE:
524		info->bug_type = "double-free";
525		break;
526	default:
527		/* bug_type filled in by kasan_complete_mode_report_info. */
528		break;
529	}
530
531	/* Fill in mode-specific report info fields. */
532	kasan_complete_mode_report_info(info);
533}
534
535void kasan_report_invalid_free(void *ptr, unsigned long ip, enum kasan_report_type type)
 
536{
537	unsigned long flags;
538	struct kasan_report_info info;
539
540	/*
541	 * Do not check report_suppressed_sw(), as an invalid-free cannot be
542	 * caused by accessing poisoned memory and thus should not be suppressed
543	 * by kasan_disable/enable_current() critical sections.
544	 *
545	 * Note that for Hardware Tag-Based KASAN, kasan_report_invalid_free()
546	 * is triggered by explicit tag checks and not by the ones performed by
547	 * the CPU. Thus, reporting invalid-free is not suppressed as well.
548	 */
549	if (unlikely(!report_enabled()))
550		return;
551
552	start_report(&flags, true);
553
554	__memset(&info, 0, sizeof(info));
555	info.type = type;
556	info.access_addr = ptr;
557	info.access_size = 0;
558	info.is_write = false;
559	info.ip = ip;
560
561	complete_report_info(&info);
562
563	print_report(&info);
564
565	/*
566	 * Invalid free is considered a "write" since the allocator's metadata
567	 * updates involves writes.
568	 */
569	end_report(&flags, ptr, true);
570}
571
572/*
573 * kasan_report() is the only reporting function that uses
574 * user_access_save/restore(): kasan_report_invalid_free() cannot be called
575 * from a UACCESS region, and kasan_report_async() is not used on x86.
576 */
577bool kasan_report(const void *addr, size_t size, bool is_write,
578			unsigned long ip)
579{
580	bool ret = true;
581	unsigned long ua_flags = user_access_save();
582	unsigned long irq_flags;
583	struct kasan_report_info info;
584
585	if (unlikely(report_suppressed_sw()) || unlikely(!report_enabled())) {
586		ret = false;
587		goto out;
588	}
589
590	start_report(&irq_flags, true);
591
592	__memset(&info, 0, sizeof(info));
593	info.type = KASAN_REPORT_ACCESS;
594	info.access_addr = addr;
595	info.access_size = size;
596	info.is_write = is_write;
597	info.ip = ip;
598
599	complete_report_info(&info);
 
600
601	print_report(&info);
602
603	end_report(&irq_flags, (void *)addr, is_write);
 
 
 
 
 
604
605out:
606	user_access_restore(ua_flags);
 
 
 
 
607
608	return ret;
609}
 
 
 
 
 
 
 
 
610
611#ifdef CONFIG_KASAN_HW_TAGS
612void kasan_report_async(void)
613{
614	unsigned long flags;
615
616	/*
617	 * Do not check report_suppressed_sw(), as
618	 * kasan_disable/enable_current() critical sections do not affect
619	 * Hardware Tag-Based KASAN.
620	 */
621	if (unlikely(!report_enabled()))
622		return;
623
624	start_report(&flags, false);
625	pr_err("BUG: KASAN: invalid-access\n");
626	pr_err("Asynchronous fault: no details available\n");
627	pr_err("\n");
628	dump_stack_lvl(KERN_ERR);
629	/*
630	 * Conservatively set is_write=true, because no details are available.
631	 * In this mode, kasan.fault=panic_on_write is like kasan.fault=panic.
632	 */
633	end_report(&flags, NULL, true);
634}
635#endif /* CONFIG_KASAN_HW_TAGS */
636
637#if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
638/*
639 * With compiler-based KASAN modes, accesses to bogus pointers (outside of the
640 * mapped kernel address space regions) cause faults when KASAN tries to check
641 * the shadow memory before the actual memory access. This results in cryptic
642 * GPF reports, which are hard for users to interpret. This hook helps users to
643 * figure out what the original bogus pointer was.
644 */
645void kasan_non_canonical_hook(unsigned long addr)
646{
647	unsigned long orig_addr;
648	const char *bug_type;
649
650	/*
651	 * All addresses that came as a result of the memory-to-shadow mapping
652	 * (even for bogus pointers) must be >= KASAN_SHADOW_OFFSET.
653	 */
654	if (addr < KASAN_SHADOW_OFFSET)
655		return;
656
657	orig_addr = (unsigned long)kasan_shadow_to_mem((void *)addr);
658
659	/*
660	 * For faults near the shadow address for NULL, we can be fairly certain
661	 * that this is a KASAN shadow memory access.
662	 * For faults that correspond to the shadow for low or high canonical
663	 * addresses, we can still be pretty sure: these shadow regions are a
664	 * fairly narrow chunk of the address space.
665	 * But the shadow for non-canonical addresses is a really large chunk
666	 * of the address space. For this case, we still print the decoded
667	 * address, but make it clear that this is not necessarily what's
668	 * actually going on.
669	 */
670	if (orig_addr < PAGE_SIZE)
671		bug_type = "null-ptr-deref";
672	else if (orig_addr < TASK_SIZE)
673		bug_type = "probably user-memory-access";
674	else if (addr_in_shadow((void *)addr))
675		bug_type = "probably wild-memory-access";
676	else
677		bug_type = "maybe wild-memory-access";
678	pr_alert("KASAN: %s in range [0x%016lx-0x%016lx]\n", bug_type,
679		 orig_addr, orig_addr + KASAN_GRANULE_SIZE - 1);
680}
681#endif
v4.10.11
 
  1/*
  2 * This file contains error reporting code.
  3 *
  4 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
  5 * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
  6 *
  7 * Some code borrowed from https://github.com/xairy/kasan-prototype by
  8 *        Andrey Konovalov <adech.fo@gmail.com>
  9 *
 10 * This program is free software; you can redistribute it and/or modify
 11 * it under the terms of the GNU General Public License version 2 as
 12 * published by the Free Software Foundation.
 13 *
 14 */
 15
 
 
 16#include <linux/ftrace.h>
 
 17#include <linux/kernel.h>
 
 18#include <linux/mm.h>
 19#include <linux/printk.h>
 20#include <linux/sched.h>
 21#include <linux/slab.h>
 22#include <linux/stackdepot.h>
 23#include <linux/stacktrace.h>
 24#include <linux/string.h>
 25#include <linux/types.h>
 
 26#include <linux/kasan.h>
 27#include <linux/module.h>
 
 
 
 28
 29#include <asm/sections.h>
 30
 31#include "kasan.h"
 32#include "../slab.h"
 33
 34/* Shadow layout customization. */
 35#define SHADOW_BYTES_PER_BLOCK 1
 36#define SHADOW_BLOCKS_PER_ROW 16
 37#define SHADOW_BYTES_PER_ROW (SHADOW_BLOCKS_PER_ROW * SHADOW_BYTES_PER_BLOCK)
 38#define SHADOW_ROWS_AROUND_ADDR 2
 39
 40static const void *find_first_bad_addr(const void *addr, size_t size)
 
 
 
 
 
 
 
 
 
 
 41{
 42	u8 shadow_val = *(u8 *)kasan_mem_to_shadow(addr);
 43	const void *first_bad_addr = addr;
 
 
 
 
 
 
 
 
 
 44
 45	while (!shadow_val && first_bad_addr < addr + size) {
 46		first_bad_addr += KASAN_SHADOW_SCALE_SIZE;
 47		shadow_val = *(u8 *)kasan_mem_to_shadow(first_bad_addr);
 48	}
 49	return first_bad_addr;
 50}
 
 51
 52static void print_error_description(struct kasan_access_info *info)
 53{
 54	const char *bug_type = "unknown-crash";
 55	u8 *shadow_addr;
 
 
 56
 57	info->first_bad_addr = find_first_bad_addr(info->access_addr,
 58						info->access_size);
 59
 60	shadow_addr = (u8 *)kasan_mem_to_shadow(info->first_bad_addr);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 61
 
 
 
 62	/*
 63	 * If shadow byte value is in [0, KASAN_SHADOW_SCALE_SIZE) we can look
 64	 * at the next shadow byte to determine the type of the bad access.
 65	 */
 66	if (*shadow_addr > 0 && *shadow_addr <= KASAN_SHADOW_SCALE_SIZE - 1)
 67		shadow_addr++;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 68
 69	switch (*shadow_addr) {
 70	case 0 ... KASAN_SHADOW_SCALE_SIZE - 1:
 71		/*
 72		 * In theory it's still possible to see these shadow values
 73		 * due to a data race in the kernel code.
 74		 */
 75		bug_type = "out-of-bounds";
 76		break;
 77	case KASAN_PAGE_REDZONE:
 78	case KASAN_KMALLOC_REDZONE:
 79		bug_type = "slab-out-of-bounds";
 80		break;
 81	case KASAN_GLOBAL_REDZONE:
 82		bug_type = "global-out-of-bounds";
 83		break;
 84	case KASAN_STACK_LEFT:
 85	case KASAN_STACK_MID:
 86	case KASAN_STACK_RIGHT:
 87	case KASAN_STACK_PARTIAL:
 88		bug_type = "stack-out-of-bounds";
 89		break;
 90	case KASAN_FREE_PAGE:
 91	case KASAN_KMALLOC_FREE:
 92		bug_type = "use-after-free";
 93		break;
 94	case KASAN_USE_AFTER_SCOPE:
 95		bug_type = "use-after-scope";
 96		break;
 97	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 98
 99	pr_err("BUG: KASAN: %s in %pS at addr %p\n",
100		bug_type, (void *)info->ip,
101		info->access_addr);
102	pr_err("%s of size %zu by task %s/%d\n",
103		info->is_write ? "Write" : "Read",
104		info->access_size, current->comm, task_pid_nr(current));
105}
 
106
107static inline bool kernel_or_module_addr(const void *addr)
108{
109	if (addr >= (void *)_stext && addr < (void *)_end)
110		return true;
111	if (is_module_address((unsigned long)addr))
112		return true;
113	return false;
114}
115
116static inline bool init_task_stack_addr(const void *addr)
 
 
 
 
 
 
 
 
117{
118	return addr >= (void *)&init_thread_union.stack &&
119		(addr <= (void *)&init_thread_union.stack +
120			sizeof(init_thread_union.stack));
 
 
 
 
 
121}
122
 
 
 
 
 
 
123static DEFINE_SPINLOCK(report_lock);
124
125static void kasan_start_report(unsigned long *flags)
126{
127	/*
128	 * Make sure we don't end up in loop.
129	 */
130	kasan_disable_current();
 
 
 
131	spin_lock_irqsave(&report_lock, *flags);
132	pr_err("==================================================================\n");
133}
134
135static void kasan_end_report(unsigned long *flags)
136{
 
 
 
137	pr_err("==================================================================\n");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
139	spin_unlock_irqrestore(&report_lock, *flags);
140	if (panic_on_warn)
141		panic("panic_on_warn set ...\n");
142	kasan_enable_current();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143}
144
145static void print_track(struct kasan_track *track)
146{
147	pr_err("PID = %u\n", track->pid);
148	if (track->stack) {
149		struct stack_trace trace;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
151		depot_fetch_stack(track->stack, &trace);
152		print_stack_trace(&trace, 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153	} else {
154		pr_err("(stack is not available)\n");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155	}
 
 
 
 
 
156}
157
158static void kasan_object_err(struct kmem_cache *cache, void *object)
159{
160	struct kasan_alloc_meta *alloc_info = get_alloc_info(cache, object);
 
 
 
 
 
 
 
 
161
162	dump_stack();
163	pr_err("Object at %p, in cache %s size: %d\n", object, cache->name,
164		cache->object_size);
165
166	if (!(cache->flags & SLAB_KASAN))
167		return;
 
 
 
 
168
169	pr_err("Allocated:\n");
170	print_track(&alloc_info->alloc_track);
171	pr_err("Freed:\n");
172	print_track(&alloc_info->free_track);
 
 
 
173}
174
175void kasan_report_double_free(struct kmem_cache *cache, void *object,
176			s8 shadow)
177{
178	unsigned long flags;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
180	kasan_start_report(&flags);
181	pr_err("BUG: Double free or freeing an invalid pointer\n");
182	pr_err("Unexpected shadow byte: 0x%hhX\n", shadow);
183	kasan_object_err(cache, object);
184	kasan_end_report(&flags);
185}
186
187static void print_address_description(struct kasan_access_info *info)
188{
189	const void *addr = info->access_addr;
190
191	if ((addr >= (void *)PAGE_OFFSET) &&
192		(addr < high_memory)) {
193		struct page *page = virt_to_head_page(addr);
194
195		if (PageSlab(page)) {
196			void *object;
197			struct kmem_cache *cache = page->slab_cache;
198			object = nearest_obj(cache, page,
199						(void *)info->access_addr);
200			kasan_object_err(cache, object);
201			return;
202		}
203		dump_page(page, "kasan: bad access detected");
204	}
205
206	if (kernel_or_module_addr(addr)) {
207		if (!init_task_stack_addr(addr))
208			pr_err("Address belongs to variable %pS\n", addr);
 
209	}
210	dump_stack();
211}
212
213static bool row_is_guilty(const void *row, const void *guilty)
214{
215	return (row <= guilty) && (guilty < row + SHADOW_BYTES_PER_ROW);
216}
217
218static int shadow_pointer_offset(const void *row, const void *shadow)
219{
220	/* The length of ">ff00ff00ff00ff00: " is
221	 *    3 + (BITS_PER_LONG/8)*2 chars.
 
 
 
 
 
 
 
222	 */
223	return 3 + (BITS_PER_LONG/8)*2 + (shadow - row)*2 +
224		(shadow - row) / SHADOW_BYTES_PER_BLOCK + 1;
225}
226
227static void print_shadow_for_address(const void *addr)
228{
229	int i;
230	const void *shadow = kasan_mem_to_shadow(addr);
231	const void *shadow_row;
232
233	shadow_row = (void *)round_down((unsigned long)shadow,
234					SHADOW_BYTES_PER_ROW)
235		- SHADOW_ROWS_AROUND_ADDR * SHADOW_BYTES_PER_ROW;
236
237	pr_err("Memory state around the buggy address:\n");
238
239	for (i = -SHADOW_ROWS_AROUND_ADDR; i <= SHADOW_ROWS_AROUND_ADDR; i++) {
240		const void *kaddr = kasan_shadow_to_mem(shadow_row);
241		char buffer[4 + (BITS_PER_LONG/8)*2];
242		char shadow_buf[SHADOW_BYTES_PER_ROW];
243
244		snprintf(buffer, sizeof(buffer),
245			(i == 0) ? ">%p: " : " %p: ", kaddr);
 
246		/*
247		 * We should not pass a shadow pointer to generic
248		 * function, because generic functions may try to
249		 * access kasan mapping for the passed address.
250		 */
251		memcpy(shadow_buf, shadow_row, SHADOW_BYTES_PER_ROW);
 
252		print_hex_dump(KERN_ERR, buffer,
253			DUMP_PREFIX_NONE, SHADOW_BYTES_PER_ROW, 1,
254			shadow_buf, SHADOW_BYTES_PER_ROW, 0);
255
256		if (row_is_guilty(shadow_row, shadow))
257			pr_err("%*c\n",
258				shadow_pointer_offset(shadow_row, shadow),
259				'^');
260
261		shadow_row += SHADOW_BYTES_PER_ROW;
262	}
263}
264
265static void kasan_report_error(struct kasan_access_info *info)
266{
267	unsigned long flags;
268	const char *bug_type;
 
 
 
 
 
 
 
 
 
 
 
 
 
269
270	kasan_start_report(&flags);
 
 
 
271
272	if (info->access_addr <
273			kasan_shadow_to_mem((void *)KASAN_SHADOW_START)) {
274		if ((unsigned long)info->access_addr < PAGE_SIZE)
275			bug_type = "null-ptr-deref";
276		else if ((unsigned long)info->access_addr < TASK_SIZE)
277			bug_type = "user-memory-access";
278		else
279			bug_type = "wild-memory-access";
280		pr_err("BUG: KASAN: %s on address %p\n",
281			bug_type, info->access_addr);
282		pr_err("%s of size %zu by task %s/%d\n",
283			info->is_write ? "Write" : "Read",
284			info->access_size, current->comm,
285			task_pid_nr(current));
286		dump_stack();
287	} else {
288		print_error_description(info);
289		print_address_description(info);
290		print_shadow_for_address(info->first_bad_addr);
 
 
 
 
 
 
 
 
 
 
291	}
292
293	kasan_end_report(&flags);
 
294}
295
296void kasan_report(unsigned long addr, size_t size,
297		bool is_write, unsigned long ip)
298{
299	struct kasan_access_info info;
 
300
301	if (likely(!kasan_report_enabled()))
 
 
 
 
 
 
 
 
 
302		return;
303
304	disable_trace_on_warning();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
306	info.access_addr = (void *)addr;
 
 
307	info.access_size = size;
308	info.is_write = is_write;
309	info.ip = ip;
310
311	kasan_report_error(&info);
312}
313
 
314
315#define DEFINE_ASAN_REPORT_LOAD(size)                     \
316void __asan_report_load##size##_noabort(unsigned long addr) \
317{                                                         \
318	kasan_report(addr, size, false, _RET_IP_);	  \
319}                                                         \
320EXPORT_SYMBOL(__asan_report_load##size##_noabort)
321
322#define DEFINE_ASAN_REPORT_STORE(size)                     \
323void __asan_report_store##size##_noabort(unsigned long addr) \
324{                                                          \
325	kasan_report(addr, size, true, _RET_IP_);	   \
326}                                                          \
327EXPORT_SYMBOL(__asan_report_store##size##_noabort)
328
329DEFINE_ASAN_REPORT_LOAD(1);
330DEFINE_ASAN_REPORT_LOAD(2);
331DEFINE_ASAN_REPORT_LOAD(4);
332DEFINE_ASAN_REPORT_LOAD(8);
333DEFINE_ASAN_REPORT_LOAD(16);
334DEFINE_ASAN_REPORT_STORE(1);
335DEFINE_ASAN_REPORT_STORE(2);
336DEFINE_ASAN_REPORT_STORE(4);
337DEFINE_ASAN_REPORT_STORE(8);
338DEFINE_ASAN_REPORT_STORE(16);
339
340void __asan_report_load_n_noabort(unsigned long addr, size_t size)
 
341{
342	kasan_report(addr, size, false, _RET_IP_);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343}
344EXPORT_SYMBOL(__asan_report_load_n_noabort);
345
346void __asan_report_store_n_noabort(unsigned long addr, size_t size)
 
 
 
 
 
 
 
 
347{
348	kasan_report(addr, size, true, _RET_IP_);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349}
350EXPORT_SYMBOL(__asan_report_store_n_noabort);