1 // SPDX-License-Identifier: GPL-2.0
3 * This file contains common KASAN 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/export.h>
13 #include <linux/init.h>
14 #include <linux/kasan.h>
15 #include <linux/kernel.h>
16 #include <linux/linkage.h>
17 #include <linux/memblock.h>
18 #include <linux/memory.h>
20 #include <linux/module.h>
21 #include <linux/printk.h>
22 #include <linux/sched.h>
23 #include <linux/sched/task_stack.h>
24 #include <linux/slab.h>
25 #include <linux/stacktrace.h>
26 #include <linux/string.h>
27 #include <linux/types.h>
28 #include <linux/bug.h>
33 depot_stack_handle_t kasan_save_stack(gfp_t flags)
35 unsigned long entries[KASAN_STACK_DEPTH];
36 unsigned int nr_entries;
38 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 0);
39 nr_entries = filter_irq_stacks(entries, nr_entries);
40 return stack_depot_save(entries, nr_entries, flags);
43 void kasan_set_track(struct kasan_track *track, gfp_t flags)
45 track->pid = current->pid;
46 track->stack = kasan_save_stack(flags);
49 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
50 void kasan_enable_current(void)
52 current->kasan_depth++;
55 void kasan_disable_current(void)
57 current->kasan_depth--;
59 #endif /* CONFIG_KASAN_GENERIC || CONFIG_KASAN_SW_TAGS */
61 void __kasan_unpoison_range(const void *address, size_t size)
63 kasan_unpoison(address, size, false);
66 #ifdef CONFIG_KASAN_STACK
67 /* Unpoison the entire stack for a task. */
68 void kasan_unpoison_task_stack(struct task_struct *task)
70 void *base = task_stack_page(task);
72 kasan_unpoison(base, THREAD_SIZE, false);
75 /* Unpoison the stack for the current task beyond a watermark sp value. */
76 asmlinkage void kasan_unpoison_task_stack_below(const void *watermark)
79 * Calculate the task stack base address. Avoid using 'current'
80 * because this function is called by early resume code which hasn't
81 * yet set up the percpu register (%gs).
83 void *base = (void *)((unsigned long)watermark & ~(THREAD_SIZE - 1));
85 kasan_unpoison(base, watermark - base, false);
87 #endif /* CONFIG_KASAN_STACK */
90 * Only allow cache merging when stack collection is disabled and no metadata
93 slab_flags_t __kasan_never_merge(void)
95 if (kasan_stack_collection_enabled())
100 void __kasan_alloc_pages(struct page *page, unsigned int order, bool init)
105 if (unlikely(PageHighMem(page)))
108 tag = kasan_random_tag();
109 for (i = 0; i < (1 << order); i++)
110 page_kasan_tag_set(page + i, tag);
111 kasan_unpoison(page_address(page), PAGE_SIZE << order, init);
114 void __kasan_free_pages(struct page *page, unsigned int order, bool init)
116 if (likely(!PageHighMem(page)))
117 kasan_poison(page_address(page), PAGE_SIZE << order,
118 KASAN_FREE_PAGE, init);
122 * Adaptive redzone policy taken from the userspace AddressSanitizer runtime.
123 * For larger allocations larger redzones are used.
125 static inline unsigned int optimal_redzone(unsigned int object_size)
128 object_size <= 64 - 16 ? 16 :
129 object_size <= 128 - 32 ? 32 :
130 object_size <= 512 - 64 ? 64 :
131 object_size <= 4096 - 128 ? 128 :
132 object_size <= (1 << 14) - 256 ? 256 :
133 object_size <= (1 << 15) - 512 ? 512 :
134 object_size <= (1 << 16) - 1024 ? 1024 : 2048;
137 void __kasan_cache_create(struct kmem_cache *cache, unsigned int *size,
140 unsigned int ok_size;
141 unsigned int optimal_size;
144 * SLAB_KASAN is used to mark caches as ones that are sanitized by
145 * KASAN. Currently this flag is used in two places:
146 * 1. In slab_ksize() when calculating the size of the accessible
147 * memory within the object.
148 * 2. In slab_common.c to prevent merging of sanitized caches.
150 *flags |= SLAB_KASAN;
152 if (!kasan_stack_collection_enabled())
157 /* Add alloc meta into redzone. */
158 cache->kasan_info.alloc_meta_offset = *size;
159 *size += sizeof(struct kasan_alloc_meta);
162 * If alloc meta doesn't fit, don't add it.
163 * This can only happen with SLAB, as it has KMALLOC_MAX_SIZE equal
164 * to KMALLOC_MAX_CACHE_SIZE and doesn't fall back to page_alloc for
167 if (*size > KMALLOC_MAX_SIZE) {
168 cache->kasan_info.alloc_meta_offset = 0;
170 /* Continue, since free meta might still fit. */
173 /* Only the generic mode uses free meta or flexible redzones. */
174 if (!IS_ENABLED(CONFIG_KASAN_GENERIC)) {
175 cache->kasan_info.free_meta_offset = KASAN_NO_FREE_META;
180 * Add free meta into redzone when it's not possible to store
181 * it in the object. This is the case when:
182 * 1. Object is SLAB_TYPESAFE_BY_RCU, which means that it can
183 * be touched after it was freed, or
184 * 2. Object has a constructor, which means it's expected to
185 * retain its content until the next allocation, or
186 * 3. Object is too small.
187 * Otherwise cache->kasan_info.free_meta_offset = 0 is implied.
189 if ((cache->flags & SLAB_TYPESAFE_BY_RCU) || cache->ctor ||
190 cache->object_size < sizeof(struct kasan_free_meta)) {
193 cache->kasan_info.free_meta_offset = *size;
194 *size += sizeof(struct kasan_free_meta);
196 /* If free meta doesn't fit, don't add it. */
197 if (*size > KMALLOC_MAX_SIZE) {
198 cache->kasan_info.free_meta_offset = KASAN_NO_FREE_META;
203 /* Calculate size with optimal redzone. */
204 optimal_size = cache->object_size + optimal_redzone(cache->object_size);
205 /* Limit it with KMALLOC_MAX_SIZE (relevant for SLAB only). */
206 if (optimal_size > KMALLOC_MAX_SIZE)
207 optimal_size = KMALLOC_MAX_SIZE;
208 /* Use optimal size if the size with added metas is not large enough. */
209 if (*size < optimal_size)
210 *size = optimal_size;
213 void __kasan_cache_create_kmalloc(struct kmem_cache *cache)
215 cache->kasan_info.is_kmalloc = true;
218 size_t __kasan_metadata_size(struct kmem_cache *cache)
220 if (!kasan_stack_collection_enabled())
222 return (cache->kasan_info.alloc_meta_offset ?
223 sizeof(struct kasan_alloc_meta) : 0) +
224 (cache->kasan_info.free_meta_offset ?
225 sizeof(struct kasan_free_meta) : 0);
228 struct kasan_alloc_meta *kasan_get_alloc_meta(struct kmem_cache *cache,
231 if (!cache->kasan_info.alloc_meta_offset)
233 return kasan_reset_tag(object) + cache->kasan_info.alloc_meta_offset;
236 #ifdef CONFIG_KASAN_GENERIC
237 struct kasan_free_meta *kasan_get_free_meta(struct kmem_cache *cache,
240 BUILD_BUG_ON(sizeof(struct kasan_free_meta) > 32);
241 if (cache->kasan_info.free_meta_offset == KASAN_NO_FREE_META)
243 return kasan_reset_tag(object) + cache->kasan_info.free_meta_offset;
247 void __kasan_poison_slab(struct page *page)
251 for (i = 0; i < compound_nr(page); i++)
252 page_kasan_tag_reset(page + i);
253 kasan_poison(page_address(page), page_size(page),
254 KASAN_KMALLOC_REDZONE, false);
257 void __kasan_unpoison_object_data(struct kmem_cache *cache, void *object)
259 kasan_unpoison(object, cache->object_size, false);
262 void __kasan_poison_object_data(struct kmem_cache *cache, void *object)
264 kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE),
265 KASAN_KMALLOC_REDZONE, false);
269 * This function assigns a tag to an object considering the following:
270 * 1. A cache might have a constructor, which might save a pointer to a slab
271 * object somewhere (e.g. in the object itself). We preassign a tag for
272 * each object in caches with constructors during slab creation and reuse
273 * the same tag each time a particular object is allocated.
274 * 2. A cache might be SLAB_TYPESAFE_BY_RCU, which means objects can be
275 * accessed after being freed. We preassign tags for objects in these
277 * 3. For SLAB allocator we can't preassign tags randomly since the freelist
278 * is stored as an array of indexes instead of a linked list. Assign tags
279 * based on objects indexes, so that objects that are next to each other
280 * get different tags.
282 static inline u8 assign_tag(struct kmem_cache *cache,
283 const void *object, bool init)
285 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
289 * If the cache neither has a constructor nor has SLAB_TYPESAFE_BY_RCU
290 * set, assign a tag when the object is being allocated (init == false).
292 if (!cache->ctor && !(cache->flags & SLAB_TYPESAFE_BY_RCU))
293 return init ? KASAN_TAG_KERNEL : kasan_random_tag();
295 /* For caches that either have a constructor or SLAB_TYPESAFE_BY_RCU: */
297 /* For SLAB assign tags based on the object index in the freelist. */
298 return (u8)obj_to_index(cache, virt_to_page(object), (void *)object);
301 * For SLUB assign a random tag during slab creation, otherwise reuse
302 * the already assigned tag.
304 return init ? kasan_random_tag() : get_tag(object);
308 void * __must_check __kasan_init_slab_obj(struct kmem_cache *cache,
311 struct kasan_alloc_meta *alloc_meta;
313 if (kasan_stack_collection_enabled()) {
314 alloc_meta = kasan_get_alloc_meta(cache, object);
316 __memset(alloc_meta, 0, sizeof(*alloc_meta));
319 /* Tag is ignored in set_tag() without CONFIG_KASAN_SW/HW_TAGS */
320 object = set_tag(object, assign_tag(cache, object, true));
322 return (void *)object;
325 static inline bool ____kasan_slab_free(struct kmem_cache *cache,
326 void *object, unsigned long ip, bool quarantine)
331 tag = get_tag(object);
332 tagged_object = object;
333 object = kasan_reset_tag(object);
335 if (is_kfence_address(object))
338 if (unlikely(nearest_obj(cache, virt_to_head_page(object), object) !=
340 kasan_report_invalid_free(tagged_object, ip);
344 /* RCU slabs could be legally used after free within the RCU period */
345 if (unlikely(cache->flags & SLAB_TYPESAFE_BY_RCU))
348 if (!kasan_byte_accessible(tagged_object)) {
349 kasan_report_invalid_free(tagged_object, ip);
353 kasan_poison(object, round_up(cache->object_size, KASAN_GRANULE_SIZE),
354 KASAN_KMALLOC_FREE, false);
356 if ((IS_ENABLED(CONFIG_KASAN_GENERIC) && !quarantine))
359 if (kasan_stack_collection_enabled())
360 kasan_set_free_info(cache, object, tag);
362 return kasan_quarantine_put(cache, object);
365 bool __kasan_slab_free(struct kmem_cache *cache, void *object, unsigned long ip)
367 return ____kasan_slab_free(cache, object, ip, true);
370 static inline bool ____kasan_kfree_large(void *ptr, unsigned long ip)
372 if (ptr != page_address(virt_to_head_page(ptr))) {
373 kasan_report_invalid_free(ptr, ip);
377 if (!kasan_byte_accessible(ptr)) {
378 kasan_report_invalid_free(ptr, ip);
383 * The object will be poisoned by kasan_free_pages() or
384 * kasan_slab_free_mempool().
390 void __kasan_kfree_large(void *ptr, unsigned long ip)
392 ____kasan_kfree_large(ptr, ip);
395 void __kasan_slab_free_mempool(void *ptr, unsigned long ip)
399 page = virt_to_head_page(ptr);
402 * Even though this function is only called for kmem_cache_alloc and
403 * kmalloc backed mempool allocations, those allocations can still be
404 * !PageSlab() when the size provided to kmalloc is larger than
405 * KMALLOC_MAX_SIZE, and kmalloc falls back onto page_alloc.
407 if (unlikely(!PageSlab(page))) {
408 if (____kasan_kfree_large(ptr, ip))
410 kasan_poison(ptr, page_size(page), KASAN_FREE_PAGE, false);
412 ____kasan_slab_free(page->slab_cache, ptr, ip, false);
416 static void set_alloc_info(struct kmem_cache *cache, void *object,
417 gfp_t flags, bool is_kmalloc)
419 struct kasan_alloc_meta *alloc_meta;
421 /* Don't save alloc info for kmalloc caches in kasan_slab_alloc(). */
422 if (cache->kasan_info.is_kmalloc && !is_kmalloc)
425 alloc_meta = kasan_get_alloc_meta(cache, object);
427 kasan_set_track(&alloc_meta->alloc_track, flags);
430 void * __must_check __kasan_slab_alloc(struct kmem_cache *cache,
431 void *object, gfp_t flags, bool init)
436 if (gfpflags_allow_blocking(flags))
437 kasan_quarantine_reduce();
439 if (unlikely(object == NULL))
442 if (is_kfence_address(object))
443 return (void *)object;
446 * Generate and assign random tag for tag-based modes.
447 * Tag is ignored in set_tag() for the generic mode.
449 tag = assign_tag(cache, object, false);
450 tagged_object = set_tag(object, tag);
453 * Unpoison the whole object.
454 * For kmalloc() allocations, kasan_kmalloc() will do precise poisoning.
456 kasan_unpoison(tagged_object, cache->object_size, init);
458 /* Save alloc info (if possible) for non-kmalloc() allocations. */
459 if (kasan_stack_collection_enabled())
460 set_alloc_info(cache, (void *)object, flags, false);
462 return tagged_object;
465 static inline void *____kasan_kmalloc(struct kmem_cache *cache,
466 const void *object, size_t size, gfp_t flags)
468 unsigned long redzone_start;
469 unsigned long redzone_end;
471 if (gfpflags_allow_blocking(flags))
472 kasan_quarantine_reduce();
474 if (unlikely(object == NULL))
477 if (is_kfence_address(kasan_reset_tag(object)))
478 return (void *)object;
481 * The object has already been unpoisoned by kasan_slab_alloc() for
482 * kmalloc() or by kasan_krealloc() for krealloc().
486 * The redzone has byte-level precision for the generic mode.
487 * Partially poison the last object granule to cover the unaligned
488 * part of the redzone.
490 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
491 kasan_poison_last_granule((void *)object, size);
493 /* Poison the aligned part of the redzone. */
494 redzone_start = round_up((unsigned long)(object + size),
496 redzone_end = round_up((unsigned long)(object + cache->object_size),
498 kasan_poison((void *)redzone_start, redzone_end - redzone_start,
499 KASAN_KMALLOC_REDZONE, false);
502 * Save alloc info (if possible) for kmalloc() allocations.
503 * This also rewrites the alloc info when called from kasan_krealloc().
505 if (kasan_stack_collection_enabled())
506 set_alloc_info(cache, (void *)object, flags, true);
508 /* Keep the tag that was set by kasan_slab_alloc(). */
509 return (void *)object;
512 void * __must_check __kasan_kmalloc(struct kmem_cache *cache, const void *object,
513 size_t size, gfp_t flags)
515 return ____kasan_kmalloc(cache, object, size, flags);
517 EXPORT_SYMBOL(__kasan_kmalloc);
519 void * __must_check __kasan_kmalloc_large(const void *ptr, size_t size,
522 unsigned long redzone_start;
523 unsigned long redzone_end;
525 if (gfpflags_allow_blocking(flags))
526 kasan_quarantine_reduce();
528 if (unlikely(ptr == NULL))
532 * The object has already been unpoisoned by kasan_alloc_pages() for
533 * alloc_pages() or by kasan_krealloc() for krealloc().
537 * The redzone has byte-level precision for the generic mode.
538 * Partially poison the last object granule to cover the unaligned
539 * part of the redzone.
541 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
542 kasan_poison_last_granule(ptr, size);
544 /* Poison the aligned part of the redzone. */
545 redzone_start = round_up((unsigned long)(ptr + size),
547 redzone_end = (unsigned long)ptr + page_size(virt_to_page(ptr));
548 kasan_poison((void *)redzone_start, redzone_end - redzone_start,
549 KASAN_PAGE_REDZONE, false);
554 void * __must_check __kasan_krealloc(const void *object, size_t size, gfp_t flags)
558 if (unlikely(object == ZERO_SIZE_PTR))
559 return (void *)object;
562 * Unpoison the object's data.
563 * Part of it might already have been unpoisoned, but it's unknown
564 * how big that part is.
566 kasan_unpoison(object, size, false);
568 page = virt_to_head_page(object);
570 /* Piggy-back on kmalloc() instrumentation to poison the redzone. */
571 if (unlikely(!PageSlab(page)))
572 return __kasan_kmalloc_large(object, size, flags);
574 return ____kasan_kmalloc(page->slab_cache, object, size, flags);
577 bool __kasan_check_byte(const void *address, unsigned long ip)
579 if (!kasan_byte_accessible(address)) {
580 kasan_report((unsigned long)address, 1, false, ip);