[PATCH 16/16] mm/sl[au]b: check if large object is valid in __ksize()

From: Hyeonggon Yoo
Date: Tue Jul 12 2022 - 09:42:08 EST


__ksize() returns size of objects allocated from slab allocator.
When invalid object is passed to __ksize(), returning zero
prevents further memory corruption and makes caller be able to
check if there is an error.

If address of large object is not beginning of folio or size of
the folio is too small, it must be invalid. Return zero in such cases.

Suggested-by: Vlastimil Babka <vbabka@xxxxxxx>
Signed-off-by: Hyeonggon Yoo <42.hyeyoo@xxxxxxxxx>
---
mm/slab_common.c | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/mm/slab_common.c b/mm/slab_common.c
index 1f8db7959366..0d6cbe9d7ad0 100644
--- a/mm/slab_common.c
+++ b/mm/slab_common.c
@@ -1013,8 +1013,12 @@ size_t __ksize(const void *object)

folio = virt_to_folio(object);

- if (unlikely(!folio_test_slab(folio)))
+ if (unlikely(!folio_test_slab(folio))) {
+ if (WARN_ON(object != folio_address(folio) ||
+ folio_size(folio) <= KMALLOC_MAX_CACHE_SIZE))
+ return 0;
return folio_size(folio);
+ }

return slab_ksize(folio_slab(folio)->slab_cache);
}
--
2.34.1