Commit 49b7f898 authored by Kees Cook's avatar Kees Cook

mm: Use overflow helpers in kmalloc_array*()

Instead of open-coded multiplication and bounds checking, use the new
overflow helper.
Suggested-by: default avatarRasmus Villemoes <linux@rasmusvillemoes.dk>
Signed-off-by: default avatarKees Cook <keescook@chromium.org>
parent ca90800a
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
#define _LINUX_SLAB_H #define _LINUX_SLAB_H
#include <linux/gfp.h> #include <linux/gfp.h>
#include <linux/overflow.h>
#include <linux/types.h> #include <linux/types.h>
#include <linux/workqueue.h> #include <linux/workqueue.h>
...@@ -624,11 +625,13 @@ int memcg_update_all_caches(int num_memcgs); ...@@ -624,11 +625,13 @@ int memcg_update_all_caches(int num_memcgs);
*/ */
static inline void *kmalloc_array(size_t n, size_t size, gfp_t flags) static inline void *kmalloc_array(size_t n, size_t size, gfp_t flags)
{ {
if (size != 0 && n > SIZE_MAX / size) size_t bytes;
if (unlikely(check_mul_overflow(n, size, &bytes)))
return NULL; return NULL;
if (__builtin_constant_p(n) && __builtin_constant_p(size)) if (__builtin_constant_p(n) && __builtin_constant_p(size))
return kmalloc(n * size, flags); return kmalloc(bytes, flags);
return __kmalloc(n * size, flags); return __kmalloc(bytes, flags);
} }
/** /**
...@@ -657,11 +660,13 @@ extern void *__kmalloc_track_caller(size_t, gfp_t, unsigned long); ...@@ -657,11 +660,13 @@ extern void *__kmalloc_track_caller(size_t, gfp_t, unsigned long);
static inline void *kmalloc_array_node(size_t n, size_t size, gfp_t flags, static inline void *kmalloc_array_node(size_t n, size_t size, gfp_t flags,
int node) int node)
{ {
if (size != 0 && n > SIZE_MAX / size) size_t bytes;
if (unlikely(check_mul_overflow(n, size, &bytes)))
return NULL; return NULL;
if (__builtin_constant_p(n) && __builtin_constant_p(size)) if (__builtin_constant_p(n) && __builtin_constant_p(size))
return kmalloc_node(n * size, flags, node); return kmalloc_node(bytes, flags, node);
return __kmalloc_node(n * size, flags, node); return __kmalloc_node(bytes, flags, node);
} }
static inline void *kcalloc_node(size_t n, size_t size, gfp_t flags, int node) static inline void *kcalloc_node(size_t n, size_t size, gfp_t flags, int node)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment