1// SPDX-License-Identifier: GPL-2.0 2/* 3 * This file contains software tag-based KASAN specific 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 <linux/bitops.h> 13#include <linux/ftrace.h> 14#include <linux/init.h> 15#include <linux/kernel.h> 16#include <linux/mm.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> 27 28#include <asm/sections.h> 29 30#include "kasan.h" 31#include "../slab.h" 32 33const void *kasan_find_first_bad_addr(const void *addr, size_t size) 34{ 35 u8 tag = get_tag(addr); 36 void *p = kasan_reset_tag(addr); 37 void *end = p + size; 38 39 if (!addr_has_metadata(p)) 40 return p; 41 42 while (p < end && tag == *(u8 *)kasan_mem_to_shadow(p)) 43 p += KASAN_GRANULE_SIZE; 44 45 return p; 46} 47 48size_t kasan_get_alloc_size(void *object, struct kmem_cache *cache) 49{ 50 size_t size = 0; 51 u8 *shadow; 52 53 /* 54 * Skip the addr_has_metadata check, as this function only operates on 55 * slab memory, which must have metadata. 56 */ 57 58 /* 59 * The loop below returns 0 for freed objects, for which KASAN cannot 60 * calculate the allocation size based on the metadata. 61 */ 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; 66 else 67 return size; 68 shadow++; 69 } 70 71 return cache->object_size; 72} 73 74void kasan_metadata_fetch_row(char *buffer, void *row) 75{ 76 memcpy(buffer, kasan_mem_to_shadow(row), META_BYTES_PER_ROW); 77} 78 79void kasan_print_tags(u8 addr_tag, const void *addr) 80{ 81 u8 *shadow = (u8 *)kasan_mem_to_shadow(addr); 82 83 pr_err("Pointer tag: [%02x], memory tag: [%02x]\n", addr_tag, *shadow); 84} 85 86#ifdef CONFIG_KASAN_STACK 87void kasan_print_address_stack_frame(const void *addr) 88{ 89 if (WARN_ON(!object_is_on_stack(addr))) 90 return; 91 92 pr_err("The buggy address belongs to stack of task %s/%d\n", 93 current->comm, task_pid_nr(current)); 94} 95#endif 96