Skip to contentSkip to conversation

string: Add __realloc_size hint to kmemdup()

PATCH New Kees Cook 1 participant 1 message Oct 29, 2022

Subsystems (2)
lore
Share & tools
lore

Kees Cook

author
#0 lore raw

PATCH v2 1/1 string: Add __realloc_size hint to kmemdup()

Add __realloc_size() hint to kmemdup() so the compiler can reason about the length of the returned buffer. (These must not use __alloc_size, since those include __malloc which says the contents aren't defined[1]).

[1] https://lore.kernel.org/linux-hardening/[email protected]/

Cc Rasmus Villemoes <[email protected]>
Cc Guenter Roeck <[email protected]>
Cc Andy Shevchenko <[email protected]>
Cc Paolo Abeni <[email protected]>
Cc Geert Uytterhoeven <[email protected]>

---
v2: use __realloc_size() instead of __alloc_size()
v1: https://lore.kernel.org/linux-hardening/[email protected]/

---
 include/linux/fortify-string.h | 3 ++-
 include/linux/string.h         | 2 +-
 2 files changed, 3 insertions(+), 2 deletions(-)
include/linux/fortify-string.h +2 -1
index e5b39b1cc2fc..49782f63f015 100644
@@ -659,7 +659,8 @@ __FORTIFY_INLINE void *memchr_inv(const void * const POS0 p, int c, size_t size)
 	return __real_memchr_inv(p, c, size);
 }
 
-extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup);
+extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup)
+								    __realloc_size(2);
 __FORTIFY_INLINE void *kmemdup(const void * const POS0 p, size_t size, gfp_t gfp)
 {
 	size_t p_size = __struct_size(p);
include/linux/string.h +1 -1
index cf7607b32102..db28802ab0a6 100644
@@ -176,7 +176,7 @@ extern void kfree_const(const void *x);
 extern char *kstrdup(const char *s, gfp_t gfp) __malloc;
 extern const char *kstrdup_const(const char *s, gfp_t gfp);
 extern char *kstrndup(const char *s, size_t len, gfp_t gfp);
-extern void *kmemdup(const void *src, size_t len, gfp_t gfp);
+extern void *kmemdup(const void *src, size_t len, gfp_t gfp) __realloc_size(2);
 extern char *kmemdup_nul(const char *s, size_t len, gfp_t gfp);
 
 extern char **argv_split(gfp_t gfp, const char *str, int *argcp);
Signature · 1 line
2.34.1