1 // SPDX-License-Identifier: GPL-2.0
3 * This file contains software tag-based KASAN specific 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>
17 #include <linux/printk.h>
18 #include <linux/sched.h>
19 #include <linux/sched/task_stack.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>
28 #include <asm/sections.h>
33 void *kasan_find_first_bad_addr(void *addr, size_t size)
35 u8 tag = get_tag(addr);
36 void *p = kasan_reset_tag(addr);
39 if (!addr_has_metadata(p))
42 while (p < end && tag == *(u8 *)kasan_mem_to_shadow(p))
43 p += KASAN_GRANULE_SIZE;
48 size_t kasan_get_alloc_size(void *object, struct kmem_cache *cache)
54 * Skip the addr_has_metadata check, as this function only operates on
55 * slab memory, which must have metadata.
59 * The loop below returns 0 for freed objects, for which KASAN cannot
60 * calculate the allocation size based on the metadata.
62 shadow = (u8 *)kasan_mem_to_shadow(object);
63 while (size < cache->object_size) {
64 if (*shadow != KASAN_TAG_INVALID)
65 size += KASAN_GRANULE_SIZE;
71 return cache->object_size;
74 void kasan_metadata_fetch_row(char *buffer, void *row)
76 memcpy(buffer, kasan_mem_to_shadow(row), META_BYTES_PER_ROW);
79 void kasan_print_tags(u8 addr_tag, const void *addr)
81 u8 *shadow = (u8 *)kasan_mem_to_shadow(addr);
83 pr_err("Pointer tag: [%02x], memory tag: [%02x]\n", addr_tag, *shadow);
86 #ifdef CONFIG_KASAN_STACK
87 void kasan_print_address_stack_frame(const void *addr)
89 if (WARN_ON(!object_is_on_stack(addr)))
92 pr_err("The buggy address belongs to stack of task %s/%d\n",
93 current->comm, task_pid_nr(current));